From 3d55c0b45bf43a8aee2030d79cd3d4f3a546144b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Mart=C3=AD?= Date: Mon, 6 Apr 2015 22:30:41 +0200 Subject: [PATCH] Remove unused jdk* spongycastle source files --- .../lang/UnsupportedOperationException.java | 14 - .../security/AlgorithmParameterGenerator.java | 96 - .../AlgorithmParameterGeneratorSpi.java | 16 - .../java/security/AlgorithmParameters.java | 103 - .../java/security/AlgorithmParametersSpi.java | 27 - .../security/GeneralSecurityException.java | 14 - .../InvalidAlgorithmParameterException.java | 13 - .../main/jdk1.1/java/security/KeyFactory.java | 89 - .../jdk1.1/java/security/KeyFactorySpi.java | 24 - .../main/jdk1.1/java/security/KeyStore.java | 225 -- .../java/security/KeyStoreException.java | 14 - .../jdk1.1/java/security/KeyStoreSpi.java | 59 - .../jdk1.1/java/security/SecurityUtil.java | 114 - .../security/UnrecoverableKeyException.java | 14 - .../main/jdk1.1/java/security/cert/CRL.java | 20 - .../java/security/cert/CRLException.java | 16 - .../java/security/cert/CRLSelector.java | 39 - .../jdk1.1/java/security/cert/CertPath.java | 283 -- .../java/security/cert/CertPathBuilder.java | 243 -- .../cert/CertPathBuilderException.java | 182 -- .../security/cert/CertPathBuilderResult.java | 38 - .../security/cert/CertPathBuilderSpi.java | 50 - .../security/cert/CertPathParameters.java | 18 - .../java/security/cert/CertPathValidator.java | 250 -- .../cert/CertPathValidatorException.java | 248 -- .../cert/CertPathValidatorResult.java | 22 - .../security/cert/CertPathValidatorSpi.java | 59 - .../java/security/cert/CertSelector.java | 39 - .../jdk1.1/java/security/cert/CertStore.java | 352 --- .../security/cert/CertStoreException.java | 172 -- .../security/cert/CertStoreParameters.java | 52 - .../java/security/cert/CertStoreSpi.java | 104 - .../jdk1.1/java/security/cert/CertUtil.java | 556 ---- .../java/security/cert/Certificate.java | 80 - .../cert/CertificateEncodingException.java | 14 - .../security/cert/CertificateException.java | 16 - .../cert/CertificateExpiredException.java | 14 - .../security/cert/CertificateFactory.java | 183 -- .../security/cert/CertificateFactorySpi.java | 111 - .../cert/CertificateNotYetValidException.java | 14 - .../cert/CertificateParsingException.java | 14 - .../cert/CollectionCertStoreParameters.java | 117 - .../cert/LDAPCertStoreParameters.java | 130 - .../security/cert/PKIXBuilderParameters.java | 179 -- .../cert/PKIXCertPathBuilderResult.java | 93 - .../security/cert/PKIXCertPathChecker.java | 155 - .../cert/PKIXCertPathValidatorResult.java | 136 - .../java/security/cert/PKIXParameters.java | 770 ----- .../jdk1.1/java/security/cert/PolicyNode.java | 107 - .../security/cert/PolicyQualifierInfo.java | 196 -- .../java/security/cert/TrustAnchor.java | 293 -- .../jdk1.1/java/security/cert/X509CRL.java | 77 - .../java/security/cert/X509CRLEntry.java | 56 - .../java/security/cert/X509CRLSelector.java | 717 ----- .../java/security/cert/X509CertSelector.java | 2462 ---------------- .../java/security/cert/X509Certificate.java | 33 - .../java/security/cert/X509Extension.java | 12 - .../RSAMultiPrimePrivateCrtKey.java | 67 - .../security/interfaces/RSAPrivateCrtKey.java | 16 - .../security/interfaces/RSAPrivateKey.java | 13 - .../security/interfaces/RSAPublicKey.java | 13 - .../security/spec/AlgorithmParameterSpec.java | 6 - .../java/security/spec/DSAParameterSpec.java | 34 - .../java/security/spec/DSAPrivateKeySpec.java | 40 - .../java/security/spec/DSAPublicKeySpec.java | 40 - .../java/security/spec/EncodedKeySpec.java | 19 - .../spec/InvalidKeySpecException.java | 16 - .../spec/InvalidParameterSpecException.java | 16 - .../jdk1.1/java/security/spec/KeySpec.java | 6 - .../security/spec/PKCS8EncodedKeySpec.java | 20 - .../java/security/spec/PSSParameterSpec.java | 45 - .../security/spec/RSAKeyGenParameterSpec.java | 35 - .../spec/RSAMultiPrimePrivateCrtKeySpec.java | 159 - .../java/security/spec/RSAOtherPrimeInfo.java | 80 - .../security/spec/RSAPrivateCrtKeySpec.java | 64 - .../java/security/spec/RSAPrivateKeySpec.java | 28 - .../java/security/spec/RSAPublicKeySpec.java | 28 - .../security/spec/X509EncodedKeySpec.java | 20 - .../jdk1.1/java/util/AbstractCollection.java | 242 -- .../main/jdk1.1/java/util/AbstractList.java | 281 -- .../main/jdk1.1/java/util/AbstractMap.java | 164 -- .../main/jdk1.1/java/util/AbstractSet.java | 42 - .../src/main/jdk1.1/java/util/ArrayList.java | 107 - .../src/main/jdk1.1/java/util/Arrays.java | 90 - .../src/main/jdk1.1/java/util/Collection.java | 21 - .../main/jdk1.1/java/util/Collections.java | 377 --- .../src/main/jdk1.1/java/util/HashMap.java | 285 -- .../src/main/jdk1.1/java/util/HashSet.java | 83 - .../src/main/jdk1.1/java/util/Iterator.java | 9 - .../core/src/main/jdk1.1/java/util/List.java | 15 - .../main/jdk1.1/java/util/ListIterator.java | 19 - .../core/src/main/jdk1.1/java/util/Map.java | 37 - .../core/src/main/jdk1.1/java/util/Set.java | 26 - .../src/main/jdk1.1/java/util/Sublist.java | 125 - .../spongycastle/asn1/ASN1InputStream.java | 466 --- .../spongycastle/asn1/ASN1StreamParser.java | 247 -- .../asn1/DERApplicationSpecific.java | 276 -- .../spongycastle/asn1/x500/style/BCStyle.java | 481 --- .../asn1/x500/style/RFC4519Style.java | 380 --- .../agreement/jpake/JPAKEParticipant.java | 573 ---- .../agreement/jpake/JPAKEPrimeOrderGroup.java | 122 - .../crypto/digests/SkeinEngine.java | 817 ------ .../crypto/encodings/PKCS1Encoding.java | 410 --- .../crypto/engines/NullEngine.java | 96 - .../DSAParameterGenerationParameters.java | 80 - .../crypto/params/HKDFParameters.java | 123 - .../prng/BasicEntropySourceProvider.java | 57 - .../crypto/prng/SP800SecureRandomBuilder.java | 289 -- .../crypto/signers/RSADigestSigner.java | 238 -- .../crypto/tls/AbstractTlsContext.java | 135 - .../crypto/tls/DTLSReassembler.java | 136 - .../crypto/tls/DTLSReliableHandshake.java | 457 --- .../spongycastle/crypto/tls/UDPTransport.java | 106 - .../spongycastle/i18n/LocalizedMessage.java | 464 --- .../i18n/MissingEntryException.java | 63 - .../RSAMultiPrimePrivateCrtKey.java | 67 - .../java/security/spec/PSSParameterSpec.java | 45 - .../security/spec/RSAKeyGenParameterSpec.java | 35 - .../spec/RSAMultiPrimePrivateCrtKeySpec.java | 159 - .../java/security/spec/RSAOtherPrimeInfo.java | 80 - .../spongycastle/i18n/LocalizedMessage.java | 464 --- .../i18n/MissingEntryException.java | 63 - .../org/spongycastle/asn1/StreamUtil.java | 89 - .../spongycastle/crypto/tls/UDPTransport.java | 78 - .../spongycastle/i18n/LocalizedMessage.java | 464 --- .../i18n/MissingEntryException.java | 81 - .../org/spongycastle/util/Integers.java | 19 - .../jdk1.4/org/spongycastle/util/Shorts.java | 9 - .../jdk1.4/org/spongycastle/util/Times.java | 11 - .../cert/cmp/GeneralPKIMessage.java | 82 - .../cert/crmf/CertificateRequestMessage.java | 309 -- .../cert/crmf/FixedLengthMGF1Padder.java | 120 - .../cert/crmf/bc/BcFixedLengthMGF1Padder.java | 134 - .../cert/crmf/jcajce/CRMFHelper.java | 485 ---- .../JceAsymmetricValueDecryptorGenerator.java | 120 - .../crmf/jcajce/JceCRMFEncryptorBuilder.java | 140 - .../crmf/jcajce/JcePKMACValuesCalculator.java | 69 - .../cert/jcajce/JcaCertStoreBuilder.java | 149 - .../path/CertPathValidationException.java | 24 - .../selector/jcajce/JcaSelectorConverter.java | 34 - .../jcajce/JcaX509CertSelectorConverter.java | 57 - .../spongycastle/cms/CMSAbsentContent.java | 49 - .../cms/CMSProcessableByteArray.java | 55 - .../spongycastle/cms/CMSProcessableFile.java | 80 - .../org/spongycastle/cms/CMSTypedStream.java | 86 - .../cms/OriginatorInfoGenerator.java | 54 - .../org/spongycastle/cms/RecipientId.java | 31 - .../spongycastle/cms/SignerInfoGenerator.java | 291 -- .../cms/jcajce/EnvelopedDataHelper.java | 671 ----- .../cms/jcajce/JcaSelectorConverter.java | 54 - .../jcajce/JcaX509CertSelectorConverter.java | 24 - .../jcajce/JceCMSContentEncryptorBuilder.java | 166 -- .../cms/jcajce/JceKeyAgreeRecipient.java | 184 -- .../JceKeyAgreeRecipientInfoGenerator.java | 212 -- .../cms/jcajce/JcePasswordRecipient.java | 107 - .../JcePasswordRecipientInfoGenerator.java | 81 - .../cms/jcajce/ZlibExpanderProvider.java | 113 - ...eOpenSSLPKCS8DecryptorProviderBuilder.java | 156 - .../JceOpenSSLPKCS8EncryptorBuilder.java | 240 -- .../jcajce/JcaContentSignerBuilder.java | 164 -- .../JcaContentVerifierProviderBuilder.java | 311 -- .../jcajce/JceAsymmetricKeyUnwrapper.java | 127 - .../jcajce/JceSymmetricKeyWrapper.java | 159 - .../operator/jcajce/OperatorHelper.java | 477 --- .../crmf/jcajce/JceCRMFEncryptorBuilder.java | 135 - .../cert/jcajce/JcaAttrCertStore.java | 72 - .../cms/bc/BcCMSContentEncryptorBuilder.java | 124 - .../jcajce/JceCMSContentEncryptorBuilder.java | 161 - .../jcajce/JceCMSMacCalculatorBuilder.java | 155 - .../jcajce/JcaCertificateRequestMessage.java | 55 - .../JcaCertificateRequestMessageBuilder.java | 25 - .../jcajce/JcaPKIArchiveControlBuilder.java | 22 - .../cert/jcajce/JcaCertStoreBuilder.java | 151 - .../cert/jcajce/JcaX500NameUtil.java | 58 - .../cert/jcajce/JcaX509ExtensionUtils.java | 138 - .../jcajce/JcaX509v1CertificateBuilder.java | 31 - .../cert/jcajce/JcaX509v2CRLBuilder.java | 15 - .../jcajce/JcaX509v3CertificateBuilder.java | 54 - .../cert/jcajce/ProviderCertHelper.java | 30 - .../cert/ocsp/jcajce/JcaRespID.java | 19 - .../selector/jcajce/JcaSelectorConverter.java | 34 - .../jcajce/JcaX509CertSelectorConverter.java | 57 - .../JcaX509CertificateHolderSelector.java | 57 - .../cms/jcajce/JcaSelectorConverter.java | 54 - .../spongycastle/cms/jcajce/JcaSignerId.java | 36 - .../jcajce/JcaX509CertSelectorConverter.java | 24 - .../cms/jcajce/JceKeyAgreeRecipientId.java | 32 - .../cms/jcajce/JceKeyTransRecipientId.java | 30 - .../eac/jcajce/ProviderEACHelper.java | 23 - .../operator/jcajce/ProviderEACHelper.java | 23 - .../JcaAlgorithmParametersConverter.java | 44 - .../operator/jcajce/OperatorHelper.java | 470 --- .../JcaPKCS10CertificationRequestBuilder.java | 25 - .../tsp/cms/CMSTimeStampedData.java | 204 -- .../tsp/cms/CMSTimeStampedDataParser.java | 207 -- .../tsp/cms/CMSTimeStampedGenerator.java | 90 - .../JceKeyAgreeRecipientInfoGenerator.java | 215 -- .../eac/jcajce/JcaPublicKeyConverter.java | 141 - .../JcaAlgorithmParametersConverter.java | 44 - .../provider/asymmetric/dsa/DSASigner.java | 280 -- .../asymmetric/ecgost/SignatureSpi.java | 221 -- .../asymmetric/gost/SignatureSpi.java | 230 -- .../asymmetric/rsa/DigestSignatureSpi.java | 368 --- .../asymmetric/rsa/ISOSignatureSpi.java | 143 - .../provider/asymmetric/util/DSABase.java | 129 - .../asymmetric/x509/CertificateFactory.java | 397 --- .../asymmetric/x509/PKIXCertPath.java | 379 --- .../asymmetric/x509/SignatureUtil.java | 107 - .../jce/MultiCertStoreParameters.java | 51 - .../jce/netscape/NetscapeCertRequest.java | 296 -- .../jce/provider/AnnotatedException.java | 29 - .../jce/provider/BouncyCastleProvider.java | 274 -- .../BouncyCastleProviderConfiguration.java | 108 - .../jce/provider/CertStoreCollectionSpi.java | 104 - .../jce/provider/MultiCertStoreSpi.java | 85 - .../jce/provider/PKIXCertPathBuilderSpi.java | 365 --- .../provider/PKIXCertPathValidatorSpi.java | 2183 -------------- .../jce/provider/PKIXPolicyNode.java | 167 -- .../jce/provider/ProviderUtil.java | 47 - .../provider/RFC3280CertPathUtilities.java | 87 - .../jce/provider/X509CRLObject.java | 554 ---- .../jce/provider/X509CertificateObject.java | 856 ------ .../x509/AttributeCertificateHolder.java | 406 --- .../x509/AttributeCertificateIssuer.java | 212 -- .../x509/X509AttributeCertStoreSelector.java | 488 ---- .../x509/X509CRLStoreSelector.java | 26 - .../x509/X509CertStoreSelector.java | 26 - .../org/spongycastle/x509/X509Util.java | 397 --- .../x509/X509V1CertificateGenerator.java | 345 --- .../X509V2AttributeCertificateGenerator.java | 281 -- .../spongycastle/x509/X509V2CRLGenerator.java | 434 --- .../x509/X509V3CertificateGenerator.java | 495 ---- .../ExtCertPathBuilderException.java | 29 - .../ExtCertPathValidatorException.java | 29 - .../rsa/AlgorithmParametersSpi.java | 201 -- .../asymmetric/rsa/PSSSignatureSpi.java | 428 --- .../asymmetric/x509/CertificateFactory.java | 397 --- .../asymmetric/x509/PKIXCertPath.java | 379 --- .../asymmetric/x509/SignatureUtil.java | 134 - .../asymmetric/x509/X509CRLEntryObject.java | 293 -- .../asymmetric/x509/X509CRLObject.java | 556 ---- .../x509/X509CertificateObject.java | 858 ------ .../asymmetric/x509/X509SignatureUtil.java | 125 - .../keystore/pkcs12/PKCS12KeyStoreSpi.java | 1636 ----------- .../symmetric/util/BaseBlockCipher.java | 1031 ------- .../jcajce/util/ProviderJcaJceHelper.java | 106 - .../org/spongycastle/jce/ECKeyUtil.java | 229 -- .../jce/MultiCertStoreParameters.java | 51 - .../jce/PKCS10CertificationRequest.java | 583 ---- .../spongycastle/jce/cert/CRLSelector.java | 41 - .../org/spongycastle/jce/cert/CertPath.java | 296 -- .../jce/cert/CertPathBuilder.java | 255 -- .../jce/cert/CertPathBuilderException.java | 182 -- .../jce/cert/CertPathBuilderResult.java | 38 - .../jce/cert/CertPathBuilderSpi.java | 50 - .../jce/cert/CertPathParameters.java | 18 - .../jce/cert/CertPathValidator.java | 276 -- .../jce/cert/CertPathValidatorException.java | 271 -- .../jce/cert/CertPathValidatorResult.java | 22 - .../jce/cert/CertPathValidatorSpi.java | 59 - .../spongycastle/jce/cert/CertSelector.java | 41 - .../org/spongycastle/jce/cert/CertStore.java | 382 --- .../jce/cert/CertStoreException.java | 187 -- .../jce/cert/CertStoreParameters.java | 52 - .../spongycastle/jce/cert/CertStoreSpi.java | 104 - .../org/spongycastle/jce/cert/CertUtil.java | 556 ---- .../jce/cert/CertificateFactory.java | 183 -- .../jce/cert/CertificateFactorySpi.java | 99 - .../cert/CollectionCertStoreParameters.java | 124 - .../jce/cert/LDAPCertStoreParameters.java | 138 - .../jce/cert/PKIXBuilderParameters.java | 190 -- .../jce/cert/PKIXCertPathBuilderResult.java | 103 - .../jce/cert/PKIXCertPathChecker.java | 163 -- .../jce/cert/PKIXCertPathValidatorResult.java | 150 - .../spongycastle/jce/cert/PKIXParameters.java | 844 ------ .../org/spongycastle/jce/cert/PolicyNode.java | 107 - .../jce/cert/PolicyQualifierInfo.java | 196 -- .../spongycastle/jce/cert/TrustAnchor.java | 293 -- .../jce/cert/X509CRLSelector.java | 717 ----- .../jce/cert/X509CertSelector.java | 2469 ---------------- .../spongycastle/jce/cert/X509Extension.java | 12 - .../org/spongycastle/jce/cert/package.html | 5 - .../ExtCertPathBuilderException.java | 29 - .../ExtCertPathValidatorException.java | 30 - .../provider/CertPathValidatorUtilities.java | 1417 --------- .../jce/provider/CertStoreCollectionSpi.java | 104 - .../spongycastle/jce/provider/JCEPBEKey.java | 146 - .../jce/provider/JCESecretKeyFactory.java | 557 ---- .../jce/provider/JDKAlgorithmParameters.java | 643 ---- .../jce/provider/MultiCertStoreSpi.java | 85 - .../jce/provider/PKIXCRLUtil.java | 155 - .../jce/provider/PKIXCertPathBuilderSpi.java | 395 --- .../provider/PKIXCertPathValidatorSpi.java | 431 --- .../jce/provider/PKIXPolicyNode.java | 169 -- .../jce/provider/ProviderUtil.java | 72 - .../provider/RFC3280CertPathUtilities.java | 2582 ----------------- .../jce/provider/X509CRLEntryObject.java | 293 -- .../jce/provider/X509CRLObject.java | 556 ---- .../jce/provider/X509CertificateObject.java | 858 ------ .../jce/spec/PSSParameterSpec.java | 44 - .../x509/AttributeCertificateHolder.java | 406 --- .../x509/AttributeCertificateIssuer.java | 211 -- .../x509/ExtendedPKIXBuilderParameters.java | 210 -- .../x509/ExtendedPKIXParameters.java | 647 ----- .../x509/X509AttributeCertStoreSelector.java | 486 ---- .../x509/X509CRLStoreSelector.java | 330 --- .../x509/X509CertStoreSelector.java | 86 - .../org/spongycastle/x509/X509Util.java | 397 --- .../x509/X509V1CertificateGenerator.java | 341 --- .../spongycastle/x509/X509V2CRLGenerator.java | 430 --- .../x509/X509V3CertificateGenerator.java | 491 ---- .../asymmetric/ec/BCECPrivateKey.java | 385 --- .../provider/asymmetric/ec/BCECPublicKey.java | 376 --- .../asymmetric/ec/KeyAgreementSpi.java | 317 -- .../provider/asymmetric/ec/KeyFactorySpi.java | 200 -- .../asymmetric/ec/KeyPairGeneratorSpi.java | 259 -- .../provider/asymmetric/ec/SignatureSpi.java | 355 --- .../ecgost/BCECGOST3410PrivateKey.java | 359 --- .../ecgost/BCECGOST3410PublicKey.java | 454 --- .../asymmetric/ecgost/KeyFactorySpi.java | 128 - .../ecgost/KeyPairGeneratorSpi.java | 144 - .../asymmetric/ecgost/SignatureSpi.java | 219 -- .../asymmetric/elgamal/CipherSpi.java | 299 -- .../rsa/AlgorithmParametersSpi.java | 217 -- .../provider/asymmetric/rsa/CipherSpi.java | 509 ---- .../asymmetric/rsa/PSSSignatureSpi.java | 405 --- .../provider/asymmetric/util/DSABase.java | 128 - .../provider/asymmetric/util/ECUtil.java | 220 -- .../keystore/pkcs12/PKCS12KeyStoreSpi.java | 1637 ----------- .../spongycastle/jce/interfaces/ECKey.java | 22 - .../BouncyCastleProviderConfiguration.java | 166 -- .../provider/CertPathValidatorUtilities.java | 1439 --------- .../jce/provider/X509SignatureUtil.java | 125 - .../x509/X509CRLStoreSelector.java | 330 --- .../x509/X509CertStoreSelector.java | 86 - .../x509/util/LDAPStoreHelper.java | 1118 ------- 336 files changed, 77338 deletions(-) delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/lang/UnsupportedOperationException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/AlgorithmParameterGenerator.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/AlgorithmParameterGeneratorSpi.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/AlgorithmParameters.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/AlgorithmParametersSpi.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/GeneralSecurityException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/InvalidAlgorithmParameterException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/KeyFactory.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/KeyFactorySpi.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/KeyStore.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/KeyStoreException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/KeyStoreSpi.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/SecurityUtil.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/UnrecoverableKeyException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CRL.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CRLException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CRLSelector.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPath.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathBuilder.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathBuilderException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathBuilderResult.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathBuilderSpi.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathParameters.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathValidator.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathValidatorException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathValidatorResult.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathValidatorSpi.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertSelector.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertStore.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertStoreException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertStoreParameters.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertStoreSpi.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertUtil.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/Certificate.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateEncodingException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateExpiredException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateFactory.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateFactorySpi.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateNotYetValidException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateParsingException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CollectionCertStoreParameters.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/LDAPCertStoreParameters.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXBuilderParameters.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXCertPathBuilderResult.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXCertPathChecker.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXCertPathValidatorResult.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXParameters.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PolicyNode.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PolicyQualifierInfo.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/TrustAnchor.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509CRL.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509CRLEntry.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509CRLSelector.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509CertSelector.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509Certificate.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509Extension.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/interfaces/RSAMultiPrimePrivateCrtKey.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/interfaces/RSAPrivateCrtKey.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/interfaces/RSAPrivateKey.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/interfaces/RSAPublicKey.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/spec/AlgorithmParameterSpec.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/spec/DSAParameterSpec.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/spec/DSAPrivateKeySpec.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/spec/DSAPublicKeySpec.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/spec/EncodedKeySpec.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/spec/InvalidKeySpecException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/spec/InvalidParameterSpecException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/spec/KeySpec.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/spec/PKCS8EncodedKeySpec.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/spec/PSSParameterSpec.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAKeyGenParameterSpec.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAMultiPrimePrivateCrtKeySpec.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAOtherPrimeInfo.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAPrivateCrtKeySpec.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAPrivateKeySpec.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAPublicKeySpec.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/security/spec/X509EncodedKeySpec.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/util/AbstractCollection.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/util/AbstractList.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/util/AbstractMap.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/util/AbstractSet.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/util/ArrayList.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/util/Arrays.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/util/Collection.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/util/Collections.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/util/HashMap.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/util/HashSet.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/util/Iterator.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/util/List.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/util/ListIterator.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/util/Map.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/util/Set.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/java/util/Sublist.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/ASN1InputStream.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/ASN1StreamParser.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/DERApplicationSpecific.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/x500/style/BCStyle.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/x500/style/RFC4519Style.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/agreement/jpake/JPAKEParticipant.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/agreement/jpake/JPAKEPrimeOrderGroup.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/digests/SkeinEngine.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/encodings/PKCS1Encoding.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/engines/NullEngine.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/params/DSAParameterGenerationParameters.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/params/HKDFParameters.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/prng/BasicEntropySourceProvider.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/prng/SP800SecureRandomBuilder.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/signers/RSADigestSigner.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/tls/AbstractTlsContext.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/tls/DTLSReassembler.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/tls/DTLSReliableHandshake.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/tls/UDPTransport.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/i18n/LocalizedMessage.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/i18n/MissingEntryException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.2/java/security/interfaces/RSAMultiPrimePrivateCrtKey.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.2/java/security/spec/PSSParameterSpec.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.2/java/security/spec/RSAKeyGenParameterSpec.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.2/java/security/spec/RSAMultiPrimePrivateCrtKeySpec.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.2/java/security/spec/RSAOtherPrimeInfo.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.2/org/spongycastle/i18n/LocalizedMessage.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.2/org/spongycastle/i18n/MissingEntryException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.3/org/spongycastle/asn1/StreamUtil.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.3/org/spongycastle/crypto/tls/UDPTransport.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.3/org/spongycastle/i18n/LocalizedMessage.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.3/org/spongycastle/i18n/MissingEntryException.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.4/org/spongycastle/util/Integers.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.4/org/spongycastle/util/Shorts.java delete mode 100644 extern/spongycastle/core/src/main/jdk1.4/org/spongycastle/util/Times.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/cmp/GeneralPKIMessage.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/CertificateRequestMessage.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/FixedLengthMGF1Padder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/bc/BcFixedLengthMGF1Padder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/jcajce/CRMFHelper.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/jcajce/JceAsymmetricValueDecryptorGenerator.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/jcajce/JceCRMFEncryptorBuilder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/jcajce/JcePKMACValuesCalculator.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/jcajce/JcaCertStoreBuilder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/path/CertPathValidationException.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/selector/jcajce/JcaSelectorConverter.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/selector/jcajce/JcaX509CertSelectorConverter.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/CMSAbsentContent.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/CMSProcessableByteArray.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/CMSProcessableFile.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/CMSTypedStream.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/OriginatorInfoGenerator.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/RecipientId.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/SignerInfoGenerator.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/EnvelopedDataHelper.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JcaSelectorConverter.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JcaX509CertSelectorConverter.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JceCMSContentEncryptorBuilder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JceKeyAgreeRecipient.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JceKeyAgreeRecipientInfoGenerator.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JcePasswordRecipient.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JcePasswordRecipientInfoGenerator.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/ZlibExpanderProvider.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/openssl/jcajce/JceOpenSSLPKCS8DecryptorProviderBuilder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/openssl/jcajce/JceOpenSSLPKCS8EncryptorBuilder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/JcaContentSignerBuilder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/JcaContentVerifierProviderBuilder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/JceAsymmetricKeyUnwrapper.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/JceSymmetricKeyWrapper.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/OperatorHelper.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cert/crmf/jcajce/JceCRMFEncryptorBuilder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cert/jcajce/JcaAttrCertStore.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cms/bc/BcCMSContentEncryptorBuilder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cms/jcajce/JceCMSContentEncryptorBuilder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cms/jcajce/JceCMSMacCalculatorBuilder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/crmf/jcajce/JcaCertificateRequestMessage.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/crmf/jcajce/JcaCertificateRequestMessageBuilder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/crmf/jcajce/JcaPKIArchiveControlBuilder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaCertStoreBuilder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX500NameUtil.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX509ExtensionUtils.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX509v1CertificateBuilder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX509v2CRLBuilder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX509v3CertificateBuilder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/ProviderCertHelper.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/ocsp/jcajce/JcaRespID.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/selector/jcajce/JcaSelectorConverter.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/selector/jcajce/JcaX509CertSelectorConverter.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/selector/jcajce/JcaX509CertificateHolderSelector.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JcaSelectorConverter.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JcaSignerId.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JcaX509CertSelectorConverter.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JceKeyAgreeRecipientId.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JceKeyTransRecipientId.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/eac/jcajce/ProviderEACHelper.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/eac/operator/jcajce/ProviderEACHelper.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/operator/jcajce/JcaAlgorithmParametersConverter.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/operator/jcajce/OperatorHelper.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/pkcs/jcajce/JcaPKCS10CertificationRequestBuilder.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/tsp/cms/CMSTimeStampedData.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/tsp/cms/CMSTimeStampedDataParser.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/tsp/cms/CMSTimeStampedGenerator.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.4/org/spongycastle/cms/jcajce/JceKeyAgreeRecipientInfoGenerator.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.4/org/spongycastle/eac/jcajce/JcaPublicKeyConverter.java delete mode 100644 extern/spongycastle/pkix/src/main/jdk1.4/org/spongycastle/operator/jcajce/JcaAlgorithmParametersConverter.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/dsa/DSASigner.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/ecgost/SignatureSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/gost/SignatureSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/rsa/DigestSignatureSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/rsa/ISOSignatureSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/util/DSABase.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/x509/CertificateFactory.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/x509/PKIXCertPath.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/x509/SignatureUtil.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/MultiCertStoreParameters.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/netscape/NetscapeCertRequest.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/AnnotatedException.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/BouncyCastleProvider.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/BouncyCastleProviderConfiguration.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/CertStoreCollectionSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/MultiCertStoreSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/PKIXCertPathBuilderSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/PKIXCertPathValidatorSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/PKIXPolicyNode.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/ProviderUtil.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/RFC3280CertPathUtilities.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/X509CRLObject.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/X509CertificateObject.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/AttributeCertificateHolder.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/AttributeCertificateIssuer.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509AttributeCertStoreSelector.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509CRLStoreSelector.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509CertStoreSelector.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509Util.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509V1CertificateGenerator.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509V2AttributeCertificateGenerator.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509V2CRLGenerator.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509V3CertificateGenerator.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.2/org/spongycastle/jce/exception/ExtCertPathBuilderException.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.2/org/spongycastle/jce/exception/ExtCertPathValidatorException.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/rsa/AlgorithmParametersSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/rsa/PSSSignatureSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/CertificateFactory.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/PKIXCertPath.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/SignatureUtil.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/X509CRLEntryObject.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/X509CRLObject.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/X509CertificateObject.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/symmetric/util/BaseBlockCipher.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/util/ProviderJcaJceHelper.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/ECKeyUtil.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/MultiCertStoreParameters.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/PKCS10CertificationRequest.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CRLSelector.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPath.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathBuilder.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathBuilderException.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathBuilderResult.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathBuilderSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathParameters.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathValidator.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathValidatorException.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathValidatorResult.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathValidatorSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertSelector.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertStore.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertStoreException.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertStoreParameters.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertStoreSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertUtil.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertificateFactory.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertificateFactorySpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CollectionCertStoreParameters.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/LDAPCertStoreParameters.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXBuilderParameters.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXCertPathBuilderResult.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXCertPathChecker.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXCertPathValidatorResult.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXParameters.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PolicyNode.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PolicyQualifierInfo.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/TrustAnchor.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/X509CRLSelector.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/X509CertSelector.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/X509Extension.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/package.html delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/exception/ExtCertPathBuilderException.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/exception/ExtCertPathValidatorException.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/CertPathValidatorUtilities.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/CertStoreCollectionSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/JCEPBEKey.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/JCESecretKeyFactory.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/JDKAlgorithmParameters.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/MultiCertStoreSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/PKIXCRLUtil.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/PKIXCertPathBuilderSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/PKIXCertPathValidatorSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/PKIXPolicyNode.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/ProviderUtil.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/RFC3280CertPathUtilities.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/X509CRLEntryObject.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/X509CRLObject.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/X509CertificateObject.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/spec/PSSParameterSpec.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/AttributeCertificateHolder.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/AttributeCertificateIssuer.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/ExtendedPKIXBuilderParameters.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/ExtendedPKIXParameters.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509AttributeCertStoreSelector.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509CRLStoreSelector.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509CertStoreSelector.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509Util.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509V1CertificateGenerator.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509V2CRLGenerator.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509V3CertificateGenerator.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/BCECPrivateKey.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/BCECPublicKey.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/KeyAgreementSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/KeyFactorySpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/KeyPairGeneratorSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/SignatureSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/BCECGOST3410PrivateKey.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/BCECGOST3410PublicKey.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/KeyFactorySpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/KeyPairGeneratorSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/SignatureSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/elgamal/CipherSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/rsa/AlgorithmParametersSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/rsa/CipherSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/rsa/PSSSignatureSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/util/DSABase.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/util/ECUtil.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jce/interfaces/ECKey.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jce/provider/BouncyCastleProviderConfiguration.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jce/provider/CertPathValidatorUtilities.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jce/provider/X509SignatureUtil.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/x509/X509CRLStoreSelector.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/x509/X509CertStoreSelector.java delete mode 100644 extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/x509/util/LDAPStoreHelper.java diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/lang/UnsupportedOperationException.java b/extern/spongycastle/core/src/main/jdk1.1/java/lang/UnsupportedOperationException.java deleted file mode 100644 index 86529c82b..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/lang/UnsupportedOperationException.java +++ /dev/null @@ -1,14 +0,0 @@ - -package java.lang; - -public class UnsupportedOperationException extends RuntimeException -{ - public UnsupportedOperationException() - { - } - - public UnsupportedOperationException(String msg) - { - super(msg); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/AlgorithmParameterGenerator.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/AlgorithmParameterGenerator.java deleted file mode 100644 index 048108490..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/AlgorithmParameterGenerator.java +++ /dev/null @@ -1,96 +0,0 @@ -package java.security; - -import java.security.spec.AlgorithmParameterSpec; - -public class AlgorithmParameterGenerator -{ - AlgorithmParameterGeneratorSpi spi; - Provider provider; - String algorithm; - - protected AlgorithmParameterGenerator( - AlgorithmParameterGeneratorSpi paramGenSpi, - Provider provider, - String algorithm) - { - this.spi = paramGenSpi; - this.provider = provider; - this.algorithm = algorithm; - } - - public final AlgorithmParameters generateParameters() - { - return spi.engineGenerateParameters(); - } - - public final String getAlgorithm() - { - return algorithm; - } - - public static AlgorithmParameterGenerator getInstance(String algorithm) - throws NoSuchAlgorithmException - { - try - { - SecurityUtil.Implementation imp = SecurityUtil.getImplementation("AlgorithmParameterGenerator", algorithm, null); - - if (imp != null) - { - return new AlgorithmParameterGenerator((AlgorithmParameterGeneratorSpi)imp.getEngine(), imp.getProvider(), algorithm); - } - - throw new NoSuchAlgorithmException("can't find algorithm " + algorithm); - } - catch (NoSuchProviderException e) - { - throw new NoSuchAlgorithmException(algorithm + " not found"); - } - } - - public static AlgorithmParameterGenerator getInstance(String algorithm, String provider) - throws NoSuchAlgorithmException, NoSuchProviderException - { - SecurityUtil.Implementation imp = SecurityUtil.getImplementation("AlgorithmParameterGenerator", algorithm, provider); - - if (imp != null) - { - return new AlgorithmParameterGenerator((AlgorithmParameterGeneratorSpi)imp.getEngine(), imp.getProvider(), algorithm); - } - - throw new NoSuchAlgorithmException("can't find algorithm " + algorithm); - } - - public final Provider getProvider() - { - return provider; - } - - public final void init( - AlgorithmParameterSpec genParamSpec) - throws InvalidAlgorithmParameterException - { - spi.engineInit(genParamSpec, new SecureRandom()); - } - - public final void init( - AlgorithmParameterSpec genParamSpec, - SecureRandom random) - throws InvalidAlgorithmParameterException - { - spi.engineInit(genParamSpec, random); - } - - public final void init( - int size) - { - spi.engineInit(size, new SecureRandom()); - } - - public final void init( - int size, - SecureRandom random) - { - spi.engineInit(size, random); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/AlgorithmParameterGeneratorSpi.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/AlgorithmParameterGeneratorSpi.java deleted file mode 100644 index 446f53bdb..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/AlgorithmParameterGeneratorSpi.java +++ /dev/null @@ -1,16 +0,0 @@ -package java.security; - -import java.security.spec.AlgorithmParameterSpec; - -public abstract class AlgorithmParameterGeneratorSpi -{ - public AlgorithmParameterGeneratorSpi() - { - } - - protected abstract AlgorithmParameters engineGenerateParameters(); - - protected abstract void engineInit(AlgorithmParameterSpec genParamSpec, SecureRandom random) throws InvalidAlgorithmParameterException; - - protected abstract void engineInit(int size, SecureRandom random); -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/AlgorithmParameters.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/AlgorithmParameters.java deleted file mode 100644 index 14f2a5ad6..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/AlgorithmParameters.java +++ /dev/null @@ -1,103 +0,0 @@ - -package java.security; - -import java.io.IOException; -import java.security.spec.AlgorithmParameterSpec; -import java.security.spec.InvalidParameterSpecException; - -public class AlgorithmParameters extends Object -{ - private AlgorithmParametersSpi spi; - private Provider provider; - private String algorithm; - - protected AlgorithmParameters( - AlgorithmParametersSpi paramSpi, - Provider provider, - String algorithm) - { - this.spi = paramSpi; - this.provider = provider; - this.algorithm = algorithm; - } - - public final String getAlgorithm() - { - return algorithm; - } - - public final byte[] getEncoded() throws IOException - { - return spi.engineGetEncoded(); - } - - public final byte[] getEncoded(String format) throws IOException - { - return spi.engineGetEncoded(format); - } - - public static AlgorithmParameters getInstance(String algorithm) - throws NoSuchAlgorithmException - { - try - { - SecurityUtil.Implementation imp = SecurityUtil.getImplementation("AlgorithmParameters", algorithm, null); - - if (imp != null) - { - return new AlgorithmParameters((AlgorithmParametersSpi)imp.getEngine(), imp.getProvider(), algorithm); - } - - throw new NoSuchAlgorithmException("can't find algorithm " + algorithm); - } - catch (NoSuchProviderException e) - { - throw new NoSuchAlgorithmException(algorithm + " not found"); - } - } - - public static AlgorithmParameters getInstance(String algorithm, String provider) - throws NoSuchAlgorithmException, NoSuchProviderException - { - SecurityUtil.Implementation imp = SecurityUtil.getImplementation("AlgorithmParameters", algorithm, provider); - - if (imp != null) - { - return new AlgorithmParameters((AlgorithmParametersSpi)imp.getEngine(), imp.getProvider(), algorithm); - } - - throw new NoSuchAlgorithmException("can't find algorithm " + algorithm); - } - - public final AlgorithmParameterSpec getParameterSpec(Class paramSpec) - throws InvalidParameterSpecException - { - return spi.engineGetParameterSpec(paramSpec); - } - - public final Provider getProvider() - { - return provider; - } - - public final void init(AlgorithmParameterSpec paramSpec) - throws InvalidParameterSpecException - { - spi.engineInit(paramSpec); - } - - public final void init(byte[] params) throws IOException - { - spi.engineInit(params); - } - - public final void init(byte[] params, String format) throws IOException - { - spi.engineInit(params, format); - } - - public final String toString() - { - return spi.engineToString(); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/AlgorithmParametersSpi.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/AlgorithmParametersSpi.java deleted file mode 100644 index 59519a343..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/AlgorithmParametersSpi.java +++ /dev/null @@ -1,27 +0,0 @@ - -package java.security; - -import java.io.IOException; -import java.security.spec.AlgorithmParameterSpec; -import java.security.spec.InvalidParameterSpecException; - -public abstract class AlgorithmParametersSpi extends Object -{ - public AlgorithmParametersSpi() - { - } - - protected abstract byte[] engineGetEncoded() - throws IOException; - protected abstract byte[] engineGetEncoded(String format) - throws IOException; - protected abstract AlgorithmParameterSpec engineGetParameterSpec(Class paramSpec) - throws InvalidParameterSpecException; - protected abstract void engineInit(AlgorithmParameterSpec paramSpec) - throws InvalidParameterSpecException; - protected abstract void engineInit(byte[] params) - throws IOException; - protected abstract void engineInit(byte[] params, String format) - throws IOException; - protected abstract String engineToString(); -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/GeneralSecurityException.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/GeneralSecurityException.java deleted file mode 100644 index fb4a5f4d5..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/GeneralSecurityException.java +++ /dev/null @@ -1,14 +0,0 @@ - -package java.security; - -public class GeneralSecurityException extends Exception -{ - public GeneralSecurityException() - { - } - - public GeneralSecurityException(String msg) - { - super(msg); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/InvalidAlgorithmParameterException.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/InvalidAlgorithmParameterException.java deleted file mode 100644 index e56228c29..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/InvalidAlgorithmParameterException.java +++ /dev/null @@ -1,13 +0,0 @@ - -package java.security; - -public class InvalidAlgorithmParameterException extends GeneralSecurityException { - public InvalidAlgorithmParameterException() - { - } - - public InvalidAlgorithmParameterException(String msg) - { - super(msg); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/KeyFactory.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/KeyFactory.java deleted file mode 100644 index 320aac3f8..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/KeyFactory.java +++ /dev/null @@ -1,89 +0,0 @@ - -package java.security; - -import java.security.spec.InvalidKeySpecException; -import java.security.spec.KeySpec; - -public class KeyFactory extends Object -{ - private KeyFactorySpi keyFacSpi; - private Provider provider; - private String algorithm; - - protected KeyFactory( - KeyFactorySpi keyFacSpi, - Provider provider, - String algorithm) - { - this.keyFacSpi = keyFacSpi; - this.provider = provider; - this.algorithm = algorithm; - } - - public final PrivateKey generatePrivate(KeySpec keySpec) - throws InvalidKeySpecException - { - return keyFacSpi.engineGeneratePrivate(keySpec); - } - - public final PublicKey generatePublic(KeySpec keySpec) - throws InvalidKeySpecException - { - return keyFacSpi.engineGeneratePublic(keySpec); - } - - public final String getAlgorithm() - { - return algorithm; - } - - public static KeyFactory getInstance(String algorithm) - throws NoSuchAlgorithmException - { - try - { - SecurityUtil.Implementation imp = SecurityUtil.getImplementation("KeyFactory", algorithm, null); - - if (imp != null) - { - return new KeyFactory((KeyFactorySpi)imp.getEngine(), imp.getProvider(), algorithm); - } - - throw new NoSuchAlgorithmException("can't find algorithm " + algorithm); - } - catch (NoSuchProviderException e) - { - throw new NoSuchAlgorithmException(algorithm + " not found"); - } - } - - public static KeyFactory getInstance(String algorithm, String provider) - throws NoSuchAlgorithmException, NoSuchProviderException - { - SecurityUtil.Implementation imp = SecurityUtil.getImplementation("KeyFactory", algorithm, null); - - if (imp != null) - { - return new KeyFactory((KeyFactorySpi)imp.getEngine(), imp.getProvider(), algorithm); - } - - throw new NoSuchAlgorithmException("can't find algorithm " + algorithm); - } - - public final KeySpec getKeySpec(Key key, Class keySpec) - throws InvalidKeySpecException - { - return keyFacSpi.engineGetKeySpec(key, keySpec); - } - - public final Provider getProvider() - { - return provider; - } - - public final Key translateKey(Key key) - throws InvalidKeyException - { - return keyFacSpi.engineTranslateKey(key); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/KeyFactorySpi.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/KeyFactorySpi.java deleted file mode 100644 index 6d160e7cf..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/KeyFactorySpi.java +++ /dev/null @@ -1,24 +0,0 @@ - -package java.security; - -import java.security.spec.InvalidKeySpecException; -import java.security.spec.KeySpec; - -public abstract class KeyFactorySpi extends Object -{ - public KeyFactorySpi() - { - } - - protected abstract PrivateKey engineGeneratePrivate(KeySpec keySpec) - throws InvalidKeySpecException; - - protected abstract PublicKey engineGeneratePublic(KeySpec keySpec) - throws InvalidKeySpecException; - - protected abstract KeySpec engineGetKeySpec(Key key, Class keySpec) - throws InvalidKeySpecException; - - protected abstract Key engineTranslateKey(Key key) - throws InvalidKeyException; -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/KeyStore.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/KeyStore.java deleted file mode 100644 index 0ded759a6..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/KeyStore.java +++ /dev/null @@ -1,225 +0,0 @@ - -package java.security; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.util.Date; -import java.util.Enumeration; - -public class KeyStore extends Object -{ - private KeyStoreSpi keyStoreSpi; - private Provider provider; - private String type; - private boolean initialised; - - protected KeyStore( - KeyStoreSpi keyStoreSpi, - Provider provider, - String type) - { - this.keyStoreSpi = keyStoreSpi; - this.provider = provider; - this.type = type; - this.initialised = false; - } - - public final Enumeration aliases() throws KeyStoreException - { - if ( !initialised ) - throw new KeyStoreException("KeyStore not initialised."); - - return keyStoreSpi.engineAliases(); - } - - public final boolean containsAlias(String alias) throws KeyStoreException - { - if ( !initialised ) - throw new KeyStoreException("KeyStore not initialised."); - - return keyStoreSpi.engineContainsAlias(alias); - } - - public final void deleteEntry(String alias) throws KeyStoreException - { - if ( !initialised ) - throw new KeyStoreException("KeyStore not initialised."); - - keyStoreSpi.engineDeleteEntry(alias); - } - - public final Certificate getCertificate(String alias) - throws KeyStoreException - { - if ( !initialised ) - throw new KeyStoreException("KeyStore not initialised."); - - return keyStoreSpi.engineGetCertificate(alias); - } - - public final String getCertificateAlias(Certificate cert) - throws KeyStoreException - { - if ( !initialised ) - throw new KeyStoreException("KeyStore not initialised."); - - return keyStoreSpi.engineGetCertificateAlias(cert); - } - - public final Certificate[] getCertificateChain(String alias) - throws KeyStoreException - { - if ( !initialised ) - throw new KeyStoreException("KeyStore not initialised."); - - return keyStoreSpi.engineGetCertificateChain(alias); - } - - public final Date getCreationDate(String alias) throws KeyStoreException - { - if ( !initialised ) - throw new KeyStoreException("KeyStore not initialised."); - - return keyStoreSpi.engineGetCreationDate(alias); - } - - public static final String getDefaultType() - { - return "JKS"; - } - - public static KeyStore getInstance(String type) throws KeyStoreException - { - try - { - SecurityUtil.Implementation imp = SecurityUtil.getImplementation("KeyStore", type, null); - - if (imp != null) - { - return new KeyStore((KeyStoreSpi)imp.getEngine(), imp.getProvider(), type); - } - - throw new KeyStoreException("can't find type " + type); - } - catch (NoSuchProviderException e) - { - throw new KeyStoreException(type + " not found"); - } - } - - public static KeyStore getInstance(String type, String provider) - throws KeyStoreException, NoSuchProviderException - { - SecurityUtil.Implementation imp = SecurityUtil.getImplementation("KeyStore", type, provider); - - if (imp != null) - { - return new KeyStore((KeyStoreSpi)imp.getEngine(), imp.getProvider(), type); - } - - throw new KeyStoreException("can't find type " + type); - } - - public final Key getKey(String alias, char[] password) - throws KeyStoreException, NoSuchAlgorithmException, - UnrecoverableKeyException - { - if ( !initialised ) - throw new KeyStoreException("KeyStore not initialised."); - - return keyStoreSpi.engineGetKey(alias, password); - } - - public final Provider getProvider() - { - return provider; - } - - public final String getType() - { - return type; - } - - public final boolean isCertificateEntry(String alias) - throws KeyStoreException - { - if ( !initialised ) - throw new KeyStoreException("KeyStore not initialised."); - - return keyStoreSpi.engineIsCertificateEntry(alias); - } - - public final boolean isKeyEntry(String alias) throws KeyStoreException - { - if ( !initialised ) - throw new KeyStoreException("KeyStore not initialised."); - - return keyStoreSpi.engineIsKeyEntry(alias); - } - - public final void load( - InputStream stream, - char[] password) - throws IOException, NoSuchAlgorithmException, CertificateException - { - keyStoreSpi.engineLoad(stream, password); - initialised = true; - } - - public final void setCertificateEntry(String alias, Certificate cert) - throws KeyStoreException - { - if ( !initialised ) - throw new KeyStoreException("KeyStore not initialised."); - - keyStoreSpi.engineSetCertificateEntry(alias, cert); - } - - public final void setKeyEntry( - String alias, - Key key, - char[] password, - Certificate[] chain) - throws KeyStoreException - { - if ( !initialised ) - throw new KeyStoreException("KeyStore not initialised."); - - keyStoreSpi.engineSetKeyEntry(alias, key, password, chain); - } - - public final void setKeyEntry( - String alias, - byte[] key, - Certificate[] chain) - throws KeyStoreException - { - if ( !initialised ) - throw new KeyStoreException("KeyStore not initialised."); - - keyStoreSpi.engineSetKeyEntry(alias, key, chain); - } - - public final int size() throws KeyStoreException - { - if ( !initialised ) - throw new KeyStoreException("KeyStore not initialised."); - - return keyStoreSpi.engineSize(); - } - - public final void store( - OutputStream stream, - char[] password) - throws KeyStoreException, IOException, NoSuchAlgorithmException, - CertificateException - { - if ( !initialised ) - throw new KeyStoreException("KeyStore not initialised."); - - keyStoreSpi.engineStore(stream, password); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/KeyStoreException.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/KeyStoreException.java deleted file mode 100644 index 2e07503d2..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/KeyStoreException.java +++ /dev/null @@ -1,14 +0,0 @@ - -package java.security; - -public class KeyStoreException extends GeneralSecurityException -{ - public KeyStoreException() - { - } - - public KeyStoreException(String msg) - { - super(msg); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/KeyStoreSpi.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/KeyStoreSpi.java deleted file mode 100644 index 87c484528..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/KeyStoreSpi.java +++ /dev/null @@ -1,59 +0,0 @@ - -package java.security; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.util.Date; -import java.util.Enumeration; - -public abstract class KeyStoreSpi extends Object -{ - public KeyStoreSpi() - { - } - - public abstract Enumeration engineAliases(); - - public abstract boolean engineContainsAlias(String alias); - - public abstract void engineDeleteEntry(String alias) - throws KeyStoreException; - - public abstract Certificate engineGetCertificate(String alias); - - public abstract String engineGetCertificateAlias(Certificate cert); - - public abstract Certificate[] engineGetCertificateChain(String alias); - - public abstract Date engineGetCreationDate(String alias); - - public abstract Key engineGetKey(String alias, char[] password) - throws NoSuchAlgorithmException, UnrecoverableKeyException; - - public abstract boolean engineIsCertificateEntry(String alias); - - public abstract boolean engineIsKeyEntry(String alias); - - public abstract void engineLoad(InputStream stream, char[] password) - throws IOException, NoSuchAlgorithmException, CertificateException; - - public abstract void engineSetCertificateEntry( - String alias, Certificate cert) - throws KeyStoreException; - - public abstract void engineSetKeyEntry( - String alias, Key key, char[] password, Certificate[] chain) - throws KeyStoreException; - - public abstract void engineSetKeyEntry( - String alias, byte[] key, Certificate[] chain) - throws KeyStoreException; - - public abstract int engineSize(); - - public abstract void engineStore(OutputStream stream, char[] password) - throws IOException, NoSuchAlgorithmException, CertificateException; -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/SecurityUtil.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/SecurityUtil.java deleted file mode 100644 index 13c313cf6..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/SecurityUtil.java +++ /dev/null @@ -1,114 +0,0 @@ -package java.security; - - -class SecurityUtil -{ - static class Implementation - { - Object engine; - Provider provider; - - Implementation( - Object engine, - Provider provider) - { - this.engine = engine; - this.provider = provider; - } - - Object getEngine() - { - return engine; - } - - Provider getProvider() - { - return provider; - } - } - - /** - * see if we can find an algorithm (or its alias and what it represents) in - * the property table for the given provider. - * - * @return null if no algorithm found, an Implementation if it is. - */ - static private Implementation getImplementation( - String baseName, - String algorithm, - Provider prov) - { - String alias; - - while ((alias = prov.getProperty("Alg.Alias." + baseName + "." + algorithm)) != null) - { - algorithm = alias; - } - - String className = prov.getProperty(baseName + "." + algorithm); - - if (className != null) - { - try - { - return new Implementation(Class.forName(className).newInstance(), prov); - } - catch (ClassNotFoundException e) - { - throw new IllegalStateException( - "algorithm " + algorithm + " in provider " + prov.getName() + " but no class found!"); - } - catch (Exception e) - { - throw new IllegalStateException( - "algorithm " + algorithm + " in provider " + prov.getName() + " but class inaccessible!"); - } - } - - return null; - } - - /** - * return an implementation for a given algorithm/provider. - * If the provider is null, we grab the first avalaible who has the required algorithm. - * - * @return null if no algorithm found, an Implementation if it is. - * @exception NoSuchProviderException if a provider is specified and not found. - */ - static Implementation getImplementation( - String baseName, - String algorithm, - String provider) - throws NoSuchProviderException - { - if (provider == null) - { - Provider[] prov = Security.getProviders(); - - // - // search every provider looking for the algorithm we want. - // - for (int i = 0; i != prov.length; i++) - { - Implementation imp = getImplementation(baseName, algorithm, prov[i]); - if (imp != null) - { - return imp; - } - } - } - else - { - Provider prov = Security.getProvider(provider); - - if (prov == null) - { - throw new NoSuchProviderException("Provider " + provider + " not found"); - } - - return getImplementation(baseName, algorithm, prov); - } - - return null; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/UnrecoverableKeyException.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/UnrecoverableKeyException.java deleted file mode 100644 index 7a1294a1c..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/UnrecoverableKeyException.java +++ /dev/null @@ -1,14 +0,0 @@ - -package java.security; - -public class UnrecoverableKeyException extends GeneralSecurityException -{ - public UnrecoverableKeyException() - { - } - - public UnrecoverableKeyException(String msg) - { - super(msg); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CRL.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CRL.java deleted file mode 100644 index 2eb219e07..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CRL.java +++ /dev/null @@ -1,20 +0,0 @@ - -package java.security.cert; - -public abstract class CRL -{ - private String type; - - protected CRL(String type) - { - this.type = type; - } - - public final String getType() - { - return type; - } - - public abstract boolean isRevoked(Certificate cert); - public abstract String toString(); -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CRLException.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CRLException.java deleted file mode 100644 index f079b8beb..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CRLException.java +++ /dev/null @@ -1,16 +0,0 @@ - -package java.security.cert; - -import java.security.GeneralSecurityException; - -public class CRLException extends GeneralSecurityException -{ - public CRLException() - { - } - - public CRLException(String msg) - { - super(msg); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CRLSelector.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CRLSelector.java deleted file mode 100644 index 2e4ff616a..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CRLSelector.java +++ /dev/null @@ -1,39 +0,0 @@ -package java.security.cert; - -/** - * A selector that defines a set of criteria for selecting CRLs. - * Classes that implement this interface are often used to specify - * which CRLs should be retrieved from a CertStore.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this interface are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see CRL - * @see CertStore - * @see CertStore#getCRLs - **/ -public interface CRLSelector extends Cloneable -{ - /** - * Decides whether a CRL should be selected. - * - * @param crl the CRL to be checked - * - * @return true if the CRL should be selected, - * false otherwise - */ - public boolean match(CRL crl); - - /** - * Makes a copy of this CRLSelector. Changes to the - * copy will not affect the original and vice versa. - * - * @return a copy of this CRLSelector - */ - public Object clone(); -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPath.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPath.java deleted file mode 100644 index ceb5cd189..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPath.java +++ /dev/null @@ -1,283 +0,0 @@ -package java.security.cert; - -import java.io.ByteArrayInputStream; -import java.io.NotSerializableException; -import java.io.ObjectStreamException; -import java.io.Serializable; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -/** - * An immutable sequence of certificates (a certification path).
- *
- * This is an abstract class that defines the methods common to all - * CertPaths. Subclasses can handle different kinds of certificates - * (X.509, PGP, etc.).
- *
- * All CertPath objects have a type, a list of Certificates, and one - * or more supported encodings. Because the CertPath class is - * immutable, a CertPath cannot change in any externally visible way - * after being constructed. This stipulation applies to all public - * fields and methods of this class and any added or overridden by - * subclasses.
- *
- * The type is a String that identifies the type of Certificates in - * the certification path. For each certificate cert in a - * certification path certPath, - * cert.getType().equals(certPath.getType()) must be true.
- *
- * The list of Certificates is an ordered List of zero or more - * Certificates. This List and all of the Certificates contained in it - * must be immutable.
- *
- * Each CertPath object must support one or more encodings so that the - * object can be translated into a byte array for storage or - * transmission to other parties. Preferably, these encodings should - * be well-documented standards (such as PKCS#7). One of the encodings - * supported by a CertPath is considered the default encoding. This - * encoding is used if no encoding is explicitly requested (for the - * {@link #getEncoded()} method, for instance).
- *
- * All CertPath objects are also Serializable. CertPath objects are - * resolved into an alternate {@link CertPathRep} object during - * serialization. This allows a CertPath object to be serialized into - * an equivalent representation regardless of its underlying - * implementation.
- *
- * CertPath objects can be created with a CertificateFactory or they - * can be returned by other classes, such as a CertPathBuilder.
- *
- * By convention, X.509 CertPaths (consisting of X509Certificates), - * are ordered starting with the target certificate and ending with a - * certificate issued by the trust anchor. That is, the issuer of one - * certificate is the subject of the following one. The certificate - * representing the {@link TrustAnchor TrustAnchor} should not be included in the - * certification path. Unvalidated X.509 CertPaths may not follow - * these conventions. PKIX CertPathValidators will detect any - * departure from these conventions that cause the certification path - * to be invalid and throw a CertPathValidatorException.
- *
- * Concurrent Access
- *
- * All CertPath objects must be thread-safe. That is, multiple threads - * may concurrently invoke the methods defined in this class on a - * single CertPath object (or more than one) with no ill effects. This - * is also true for the List returned by CertPath.getCertificates.
- *
- * Requiring CertPath objects to be immutable and thread-safe allows - * them to be passed around to various pieces of code without worrying - * about coordinating access. Providing this thread-safety is - * generally not difficult, since the CertPath and List objects in - * question are immutable. - * - * @see CertificateFactory - * @see CertPathBuilder - */ -public abstract class CertPath extends Object implements Serializable -{ - private String type; - - /** - * Alternate CertPath class for serialization. - **/ - protected static class CertPathRep - implements Serializable - { - private String type; - private byte[] data; - - /** - * Creates a CertPathRep with the specified - * type and encoded form of a certification path. - * - * @param type the standard name of a CertPath - * @param typedata the encoded form of the certification - * path - **/ - protected CertPathRep(String type, byte[] data) - { - this.type = type; - this.data = data; - } - - /** - * Returns a CertPath constructed from the type and data. - * - * @return the resolved CertPath object - * @exception ObjectStreamException if a CertPath could not be constructed - **/ - protected Object readResolve() - throws ObjectStreamException - { - try { - ByteArrayInputStream inStream = new ByteArrayInputStream(data); - CertificateFactory cf = CertificateFactory.getInstance(type); - return cf.generateCertPath(inStream); - } catch ( CertificateException ce ) { - throw new NotSerializableException(" java.security.cert.CertPath: " + type); - } - } - } - - /** - * Creates a CertPath of the specified type. - * This constructor is protected because most users should use - * a CertificateFactory to create CertPaths. - * @param type the standard name of the type of Certificatesin this path - **/ - protected CertPath(String type) - { - this.type = type; - } - - /** - * Returns the type of Certificates in this certification - * path. This is the same string that would be returned by - * {@link Certificate#getType() cert.getType()} for all - * Certificates in the certification path. - * - * @return the type of Certificates in this certification path (never null) - **/ - public String getType() - { - return type; - } - - /** - * Returns an iteration of the encodings supported by this - * certification path, with the default encoding - * first. Attempts to modify the returned Iterator via its - * remove method result in an UnsupportedOperationException. - * - * @return an Iterator over the names of the supported encodings (as Strings) - **/ - public abstract Iterator getEncodings(); - - /** - * Compares this certification path for equality with the - * specified object. Two CertPaths are equal if and only if - * their types are equal and their certificate Lists (and by - * implication the Certificates in those Lists) are equal. A - * CertPath is never equal to an object that is not a - * CertPath.
- *
- * This algorithm is implemented by this method. If it is - * overridden, the behavior specified here must be maintained. - * - * @param other the object to test for equality with this - * certification path - * - * @return true if the specified object is equal to this - * certification path, false otherwise - * - * @see Object#hashCode() Object.hashCode() - **/ - public boolean equals(Object other) - { - if (!( other instanceof CertPath ) ) - return false; - - CertPath otherCertPath = (CertPath)other; - if ( ! getType().equals(otherCertPath.getType()) ) - return false; - return getCertificates().equals(otherCertPath.getCertificates()); - } - - /** - * Returns the hashcode for this certification path. The hash - * code of a certification path is defined to be the result of - * the following calculation: - *
-     *   hashCode = path.getType().hashCode();
-     *   hashCode = 31 * hashCode + path.getCertificates().hashCode();
-     * 
- * This ensures that path1.equals(path2) implies that - * path1.hashCode()==path2.hashCode() for any two - * certification paths, path1 and path2, as required by the - * general contract of Object.hashCode. - * - * @return The hashcode value for this certification path - * - * @see #equals(Object) - **/ - public int hashCode() - { - return getType().hashCode() * 31 + getCertificates().hashCode(); - } - - /** - * Returns a string representation of this certification - * path. This calls the toString method on each of the - * Certificates in the path. - * - * @return a string representation of this certification path - **/ - public String toString() - { - StringBuffer s = new StringBuffer(); - List certs = getCertificates(); - ListIterator iter = certs.listIterator(); - s.append('\n').append(getType()).append(" Cert Path: length = ").append(certs.size()).append("\n[\n"); - while ( iter.hasNext() ) { - s.append("=========================================================Certificate ").append(iter.nextIndex()).append('\n'); - s.append(iter.next()).append('\n'); - s.append("========================================================Certificate end\n\n\n"); - } - s.append("\n]"); - return s.toString(); - } - - /** - * Returns the encoded form of this certification path, using - * the default encoding. - * - * @return the encoded bytes - * - * @exception CertificateEncodingException if an encoding error occurs - **/ - public abstract byte[] getEncoded() - throws CertificateEncodingException; - - /** - * Returns the encoded form of this certification path, using - * the specified encoding. - * - * @param encoding the name of the encoding to use - * - * @return the encoded bytes - * - * @exception CertificateEncodingException if an encoding error - * occurs or the encoding requested is not supported - **/ - public abstract byte[] getEncoded(String encoding) - throws CertificateEncodingException; - - /** - * Returns the list of certificates in this certification - * path. The List returned must be immutable and thread-safe. - * - * @return an immutable List of Certificates (may be empty, but not null) - **/ - public abstract List getCertificates(); - - /** - * Replaces the CertPath to be serialized with a CertPathRep - * object. - * - * @return the CertPathRep to be serialized - * - * @exception ObjectStreamException if a CertPathRep object - * representing this certification path could not be created - **/ - protected Object writeReplace() - throws ObjectStreamException - { - try { - return new CertPathRep( getType(), getEncoded() ); - } catch ( CertificateException ce ) { - throw new NotSerializableException( " java.security.cert.CertPath: " + getType() ); - } - } -} - diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathBuilder.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathBuilder.java deleted file mode 100644 index b3adbf15f..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathBuilder.java +++ /dev/null @@ -1,243 +0,0 @@ -package java.security.cert; - -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.Security; - -/** - * A class for building certification paths (also known as certificate - * chains).
- *
- * This class uses a provider-based architecture, as described in the - * Java Cryptography Architecture. To create a - * CertPathBuilder, call one of the static - * getInstance methods, passing in the algorithm name of - * the CertPathBuilder desired and optionally the name of the provider - * desired.
- *
- * Once a CertPathBuilder object has been created, - * certification paths can be constructed by calling the - * {@link #build build} method and passing it an algorithm-specific set - * of parameters. If successful, the result (including the CertPath - * that was built) is returned in an object that implements the - * CertPathBuilderResult interface.
- *
- * Concurrent Access
- *
- * The static methods of this class are guaranteed to be - * thread-safe. Multiple threads may concurrently invoke the static - * methods defined in this class with no ill effects.
- *
- * However, this is not true for the non-static methods defined by - * this class. Unless otherwise documented by a specific provider, - * threads that need to access a single CertPathBuilder - * instance concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating a - * different CertPathBuilder instance need not - * synchronize.
- *
- * Uses {@link CertUtil CertUtil} to actualiy load the SPI classes. - * - * @see CertUtil - **/ -public class CertPathBuilder extends Object -{ - private CertPathBuilderSpi builderSpi; - private Provider provider; - private String algorithm; - - /** - * Creates a CertPathBuilder object of the given algorithm, and - * encapsulates the given provider implementation (SPI object) - * in it. - * - * @param builderSpi the provider implementation - * @param provider the provider - * @param algorithm the algorithm name - **/ - protected CertPathBuilder(CertPathBuilderSpi builderSpi, - Provider provider, - String algorithm) - { - this.builderSpi = builderSpi; - this.provider = provider; - this.algorithm = algorithm; - } - - /** - * Returns a CertPathBuilder object that implements the - * specified algorithm.
- *
- * If the default provider package provides an implementation - * of the specified CertPathBuilder algorithm, an instance of - * CertPathBuilder containing that implementation is - * returned. If the requested algorithm is not available in - * the default package, other packages are searched.
- *
- * @param algorithm the name of the requested CertPathBuilder algorithm - * - * @return a CertPathBuilder object that implements the - * specified algorithm - * - * @exception NoSuchAlgorithmException if the requested - * algorithm is not available in the default provider package - * or any of the other provider packages that were searched - **/ - public static CertPathBuilder getInstance(String algorithm) - throws NoSuchAlgorithmException - { - try { - CertUtil.Implementation imp = - CertUtil.getImplementation("CertPathBuilder", algorithm, (String)null); - if (imp != null) - { - return new CertPathBuilder((CertPathBuilderSpi)imp.getEngine(), - imp.getProvider(), algorithm); - } - } catch ( NoSuchProviderException ex ) {} - throw new NoSuchAlgorithmException("can't find type " + algorithm); - } - - /** - * Returns a CertPathBuilder object that implements the - * specified algorithm, as supplied by the specified provider. - * - * @param algorithm the name of the requested CertPathBuilder - * algorithm - * @param provider the name of the provider - * - * @return a CertPathBuilder object that implements the - * specified algorithm, as supplied by the specified provider - * - * @exception NoSuchAlgorithmException if the requested algorithm - * is not available from the specified provider - * @exception NoSuchProviderException if the provider has not - * been configured - * @exception IllegalArgumentException if the provider is null - **/ - public static CertPathBuilder getInstance(String algorithm, - String provider) - throws NoSuchAlgorithmException, - NoSuchProviderException - { - if ( provider == null ) - throw new IllegalArgumentException("provider must be non-null"); - CertUtil.Implementation imp = - CertUtil.getImplementation("CertPathBuilder", algorithm, provider); - - if (imp != null) - { - return new CertPathBuilder((CertPathBuilderSpi)imp.getEngine(), - imp.getProvider(), algorithm); - } - throw new NoSuchAlgorithmException("can't find type " + algorithm); - } - - /** - * Returns a CertPathBuilder object that implements the - * specified algorithm, as supplied by the specified - * provider. Note: the provider doesn't have to be registered. - * - * @param algorithm the name of the requested CertPathBuilder - * algorithm - * @param provider the provider - * @return a CertPathBuilder object that implements the - * specified algorithm, as supplied by the specified provider - * - * @exception NoSuchAlgorithmException if the requested algorithm - * is not available from the specified provider - * @exception IllegalArgumentException if the provider is null. - **/ - public static CertPathBuilder getInstance(String algorithm, - Provider provider) - throws NoSuchAlgorithmException - { - if ( provider == null ) - throw new IllegalArgumentException("provider must be non-null"); - CertUtil.Implementation imp = - CertUtil.getImplementation("CertPathBuilder", algorithm, provider); - - if (imp != null) - { - return new CertPathBuilder((CertPathBuilderSpi)imp.getEngine(), - provider, algorithm); - } - throw new NoSuchAlgorithmException("can't find type " + algorithm); - } - - /** - * Returns the provider of this CertPathBuilder. - * - * @return the provider of this CertPathBuilder - **/ - public final Provider getProvider() - { - return provider; - } - - /** - * Returns the name of the algorithm of this - * CertPathBuilder. - * - * @return the name of the algorithm of this CertPathBuilder - **/ - public final String getAlgorithm() - { - return algorithm; - } - - /** - * Attempts to build a certification path using the specified algorithm - * parameter set. - * - * @param params the algorithm parameters - * - * @return the result of the build algorithm - * - * @exception CertPathBuilderException if the builder is unable to construct - * a certification path that satisfies the specified parameters - * @exception InvalidAlgorithmParameterException if the specified parameters * are inappropriate for this CertPathBuilder - */ - public final CertPathBuilderResult build(CertPathParameters params) - throws CertPathBuilderException, - InvalidAlgorithmParameterException - { - return builderSpi.engineBuild(params); - } - - - /** - * Returns the default CertPathBuilder type as specified in - * the Java security properties file, or the string "PKIX" - * if no such property exists. The Java security properties file is - * located in the file named <JAVA_HOME>/lib/security/java.security, - * where <JAVA_HOME> refers to the directory where the SDK was - * installed.
- *
- * The default CertPathBuilder type can be used by - * applications that do not want to use a hard-coded type when calling one - * of the getInstance methods, and want to provide a default - * type in case a user does not specify its own.
- *
- * The default CertPathBuilder type can be changed by - * setting the value of the "certpathbuilder.type" security property - * (in the Java security properties file) to the desired type. - * - * @return the default CertPathBuilder type as specified - * in the Java security properties file, or the string "PKIX" - * if no such property exists. - */ - public static final String getDefaultType() - { - String defaulttype = null; - defaulttype = Security.getProperty("certpathbuilder.type"); - - if ( defaulttype == null || defaulttype.length() <= 0 ) - return "PKIX"; - else - return defaulttype; - } -} - diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathBuilderException.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathBuilderException.java deleted file mode 100644 index 13b60891e..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathBuilderException.java +++ /dev/null @@ -1,182 +0,0 @@ -package java.security.cert; - -import java.io.PrintStream; -import java.io.PrintWriter; -import java.security.GeneralSecurityException; - -/** - * An exception indicating one of a variety of problems encountered - * when building a certification path with a - * CertPathBuilder.
- *
- * A CertPathBuilderException provides support for - * wrapping exceptions. The {@link #getCause() getCause} method - * returns the throwable, if any, that caused this exception to be - * thrown.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are - * not thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see CertPathBuilder - **/ -public class CertPathBuilderException extends GeneralSecurityException -{ - private Throwable cause; - - /** - * Creates a CertPathBuilderException with null - * as its detail message. - */ - public CertPathBuilderException() - { - } - - /** - * Creates a CertPathBuilderException with the given detail - * message. The detail message is a String that describes - * this particular exception in more detail. - * - * @param msg - * the detail message - */ - public CertPathBuilderException(String message) - { - super(message); - } - - /** - * Creates a CertPathBuilderException that wraps the - * specified throwable. This allows any exception to be converted into a - * CertPathBuilderException, while retaining information - * about the wrapped exception, which may be useful for debugging. The - * detail message is set to - * (cause==null ? null : cause.toString()) (which typically - * contains the class and detail message of cause). - * - * @param cause - * the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, and - * indicates that the cause is nonexistent or unknown.) - */ - public CertPathBuilderException(String message, Throwable cause) - { - super(message); - this.cause = cause; - } - - /** - * Creates a CertPathBuilderException with the specified - * detail message and cause. - * - * @param msg - * the detail message - * @param cause - * the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, and - * indicates that the cause is nonexistent or unknown.) - */ - public CertPathBuilderException(Throwable cause) - { - this.cause = cause; - } - - /** - * Returns the internal (wrapped) cause, or null if the cause is nonexistent - * or unknown. - * - * @return the cause of this throwable or null if the cause - * is nonexistent or unknown. - */ - public Throwable getCause() - { - return cause; - } - - /** - * Returns the detail message for this CertPathBuilderException. - * - * @return the detail message, or null if neither the message - * nor internal cause were specified - */ - public String getMessage() - { - String message = super.getMessage(); - - if (message == null && cause == null) - { - return null; - } - - if (cause != null) - { - return cause.getMessage(); - } - - return message; - } - - /** - * Returns a string describing this exception, including a description of - * the internal (wrapped) cause if there is one. - * - * @return a string representation of this - * CertPathBuilderException - */ - public String toString() - { - String message = getMessage(); - if (message == null) - { - return ""; - } - - return message; - } - - /** - * Prints a stack trace to System.err, including the - * backtrace of the cause, if any. - */ - public void printStackTrace() - { - printStackTrace(System.err); - } - - /** - * Prints a stack trace to a PrintStream, including the - * backtrace of the cause, if any. - * - * @param ps - * the PrintStream to use for output - */ - public void printStackTrace(PrintStream ps) - { - super.printStackTrace(ps); - if (getCause() != null) - { - getCause().printStackTrace(ps); - } - } - - /** - * Prints a stack trace to a PrintWriter, including the - * backtrace of the cause, if any. - * - * @param ps - * the PrintWriter to use for output - */ - public void printStackTrace(PrintWriter pw) - { - super.printStackTrace(pw); - if (getCause() != null) - { - getCause().printStackTrace(pw); - } - } -} - diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathBuilderResult.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathBuilderResult.java deleted file mode 100644 index c0482bc4e..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathBuilderResult.java +++ /dev/null @@ -1,38 +0,0 @@ -package java.security.cert; - -/** - * A specification of the result of a certification path builder algorithm. - * All results returned by the {@link CertPathBuilder#build CertPathBuilder.build} method - * must implement this interface.
- *
- * At a minimum, a CertPathBuilderResult contains the CertPath built by the - * CertPathBuilder instance. Implementations of this interface may add methods - * to return implementation or algorithm specific information, such as - * debugging information or certification path validation results.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this interface are not - * thread-safe. Multiple threads that need to access a single object - * concurrently should synchronize amongst themselves and provide the - * necessary locking. Multiple threads each manipulating separate objects - * need not synchronize. - **/ -public interface CertPathBuilderResult extends Cloneable -{ - /** - * Returns the built certification path. - * - * @return the certification path (never null) - */ - public CertPath getCertPath(); - - /** - * Makes a copy of this CertPathBuilderResult. - * Changes to the copy will not affect the original and vice - * versa. - * - * @return a copy of this CertPathBuilderResult - */ - public Object clone(); -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathBuilderSpi.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathBuilderSpi.java deleted file mode 100644 index be044fa30..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathBuilderSpi.java +++ /dev/null @@ -1,50 +0,0 @@ -package java.security.cert; - -import java.security.InvalidAlgorithmParameterException; - -/** - * The Service Provider Interface (SPI) for the CertPathBuilder - * class. All CertPathBuilder implementations must include a class - * (the SPI class) that extends this class (CertPathBuilderSpi) and - * implements all of its methods. In general, instances of this class - * should only be accessed through the CertPathBuilder class. For - * details, see the Java Cryptography Architecture.
- *
- * Concurrent Access
- *
- * Instances of this class need not be protected against concurrent - * access from multiple threads. Threads that need to access a single - * CertPathBuilderSpi instance concurrently should synchronize amongst - * themselves and provide the necessary locking before calling the - * wrapping CertPathBuilder object.
- *
- * However, implementations of CertPathBuilderSpi may still encounter - * concurrency issues, since multiple threads each manipulating a - * different CertPathBuilderSpi instance need not synchronize. - **/ -public abstract class CertPathBuilderSpi - extends Object -{ - /** - * The default constructor. - */ - public CertPathBuilderSpi() {} - - /** - * Attempts to build a certification path using the specified - * algorithm parameter set. - * - * @param params the algorithm parameters - * - * @return the result of the build algorithm - * - * @exception CertPathBuilderException if the builder is unable - * to construct a certification path that satisfies the - * specified - * @exception parametersInvalidAlgorithmParameterException if the - * specified parameters are inappropriate for this CertPathBuilder - */ - public abstract CertPathBuilderResult engineBuild( CertPathParameters params ) - throws CertPathBuilderException, - InvalidAlgorithmParameterException; -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathParameters.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathParameters.java deleted file mode 100644 index caff291a8..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathParameters.java +++ /dev/null @@ -1,18 +0,0 @@ -package java.security.cert; - -/** - * A specification of certification path algorithm parameters. The purpose - * of this interface is to group (and provide type safety for) all CertPath - * parameter specifications. All CertPath parameter specifications must - * implement this interface. - **/ -public interface CertPathParameters extends Cloneable -{ - /** - * Makes a copy of this CertPathParameters. Changes to the - * copy will not affect the original and vice versa. - * - * @return a copy of this CertPathParameters - **/ - public Object clone(); -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathValidator.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathValidator.java deleted file mode 100644 index aaddbf0e5..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathValidator.java +++ /dev/null @@ -1,250 +0,0 @@ -package java.security.cert; - -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.Security; - -/** - * A class for validating certification paths (also known as certificate - * chains).
- *
- * This class uses a provider-based architecture, as described in the Java - * Cryptography Architecture. To create a CertPathValidator, - * call one of the static getInstance methods, passing in the - * algorithm name of the CertPathValidator desired and - * optionally the name of the provider desired.
- *
- * Once a CertPathValidator object has been created, it can - * be used to validate certification paths by calling the {@link #validate - * validate} method and passing it the CertPath to be validated - * and an algorithm-specific set of parameters. If successful, the result is - * returned in an object that implements the - * CertPathValidatorResult interface.
- *
- * Concurrent Access
- *
- * The static methods of this class are guaranteed to be thread-safe. - * Multiple threads may concurrently invoke the static methods defined in - * this class with no ill effects.
- *
- * However, this is not true for the non-static methods defined by this class. - * Unless otherwise documented by a specific provider, threads that need to - * access a single CertPathValidator instance concurrently should - * synchronize amongst themselves and provide the necessary locking. Multiple - * threads each manipulating a different CertPathValidator - * instance need not synchronize.
- *
- * Uses {@link CertUtil CertUtil} to actualiy load the SPI classes. - * - * @see CertPath - * @see CertUtil - **/ -public class CertPathValidator extends Object -{ - private CertPathValidatorSpi validatorSpi; - private Provider provider; - private String algorithm; - - /** - * Creates a CertPathValidator object of the given algorithm, - * and encapsulates the given provider implementation (SPI object) in it. - * - * @param validatorSpi the provider implementation - * @param provider the provider - * @param algorithm the algorithm name - */ - protected CertPathValidator( CertPathValidatorSpi validatorSpi, - Provider provider, - String algorithm) - { - this.validatorSpi = validatorSpi; - this.provider = provider; - this.algorithm = algorithm; - } - - /** - * Returns a CertPathValidator object that implements the - * specified algorithm.
- *
- * If the default provider package provides an implementation of the - * specified CertPathValidator algorithm, an instance of - * CertPathValidator containing that implementation is - * returned. If the requested algorithm is not available in the default - * package, other packages are searched. - * - * @param algorithm the name of the requested CertPathValidator - * algorithm - * - * @return a CertPathValidator object that implements the - * specified algorithm - * - * @exception NoSuchAlgorithmException if the requested algorithm - * is not available in the default provider package or any of the other - * provider packages that were searched - */ - public static CertPathValidator getInstance(String algorithm) - throws NoSuchAlgorithmException - { - try { - CertUtil.Implementation imp = - CertUtil.getImplementation("CertPathValidator", algorithm, (String)null ); - if (imp != null) - { - return new CertPathValidator((CertPathValidatorSpi)imp.getEngine(), imp.getProvider(), algorithm); - } - } catch (NoSuchProviderException ex ) {} - throw new NoSuchAlgorithmException("can't find algorithm " + algorithm); - } - - /** - * Returns a CertPathValidator object that implements the - * specified algorithm, as supplied by the specified provider. - * - * @param algorithm the name of the requested CertPathValidator - * algorithm - * @param provider the name of the provider - * - * @return a CertPathValidator object that implements the - * specified algorithm, as supplied by the specified provider - * - * @exception NoSuchAlgorithmException if the requested algorithm - * is not available from the specified provider - * @exception NoSuchProviderException if the provider has not been - * configured - * @exception IllegalArgumentException if the provider is - * null - */ - public static CertPathValidator getInstance(String algorithm, - String provider) - throws NoSuchAlgorithmException, - NoSuchProviderException - { - if ( provider == null ) - throw new IllegalArgumentException("provider must be non-null"); - - CertUtil.Implementation imp = CertUtil.getImplementation("CertPathValidator", algorithm, provider ); - if (imp != null) - { - return new CertPathValidator((CertPathValidatorSpi)imp.getEngine(), imp.getProvider(), algorithm); - } - throw new NoSuchAlgorithmException("can't find algorithm " + algorithm); - } - - /** - * Returns a CertPathValidator object that implements the - * specified algorithm, as supplied by the specified provider. - * Note: the provider doesn't have to be registered. - * - * @param algorithm the name of the requested - * CertPathValidator algorithm - * @param provider the provider - * - * @return a CertPathValidator object that implements the - * specified algorithm, as supplied by the specified provider - * - * @exception NoSuchAlgorithmException if the requested algorithm - * is not available from the specified provider - * @exception IllegalArgumentException if the provider is - * null - */ - public static CertPathValidator getInstance(String algorithm, - Provider provider) - throws NoSuchAlgorithmException - { - if ( provider == null ) - throw new IllegalArgumentException("provider must be non-null"); - - CertUtil.Implementation imp = CertUtil.getImplementation("CertPathValidator", algorithm, provider ); - if (imp != null) - { - return new CertPathValidator((CertPathValidatorSpi)imp.getEngine(), provider, algorithm); - } - throw new NoSuchAlgorithmException("can't find algorithm " + algorithm); - } - - /** - * Returns the Provider of this - * CertPathValidator. - * - * @return the Provider of this CertPathValidator - */ - public final Provider getProvider() - { - return provider; - } - - /** - * Returns the algorithm name of this CertPathValidator. - * - * @return the algorithm name of this CertPathValidator - */ - public final String getAlgorithm() - { - return algorithm; - } - - /** - * Validates the specified certification path using the specified - * algorithm parameter set.
- *
- * The CertPath specified must be of a type that is - * supported by the validation algorithm, otherwise an - * InvalidAlgorithmParameterException will be thrown. For - * example, a CertPathValidator that implements the PKIX - * algorithm validates CertPath objects of type X.509. - * - * @param certPath the CertPath to be validated - * @param params the algorithm parameters - * - * @return the result of the validation algorithm - * - * @exception CertPathValidatorException if the CertPath - * does not validate - * @exception InvalidAlgorithmParameterException if the specified - * parameters or the type of the specified CertPath are - * inappropriate for this CertPathValidator - */ - public final CertPathValidatorResult validate( CertPath certPath, - CertPathParameters params) - throws CertPathValidatorException, - InvalidAlgorithmParameterException - { - return validatorSpi.engineValidate( certPath, params ); - } - - - /** - * Returns the default CertPathValidator type as specified in - * the Java security properties file, or the string "PKIX" - * if no such property exists. The Java security properties file is - * located in the file named <JAVA_HOME>/lib/security/java.security, - * where <JAVA_HOME> refers to the directory where the SDK was - * installed.
- *
- * The default CertPathValidator type can be used by - * applications that do not want to use a hard-coded type when calling one - * of the getInstance methods, and want to provide a default - * type in case a user does not specify its own.
- *
- * The default CertPathValidator type can be changed by - * setting the value of the "certpathvalidator.type" security property - * (in the Java security properties file) to the desired type. - * - * @return the default CertPathValidator type as specified - * in the Java security properties file, or the string "PKIX" - * if no such property exists. - */ - public static final String getDefaultType() - { - String defaulttype = null; - defaulttype = Security.getProperty("certpathvalidator.type"); - - if ( defaulttype == null || defaulttype.length() <= 0 ) - return "PKIX"; - else - return defaulttype; - } -} - diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathValidatorException.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathValidatorException.java deleted file mode 100644 index 2088ab1a4..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathValidatorException.java +++ /dev/null @@ -1,248 +0,0 @@ -package java.security.cert; - -import java.io.PrintStream; -import java.io.PrintWriter; -import java.security.GeneralSecurityException; - -/** - * An exception indicating one of a variety of problems encountered when - * validating a certification path.
- *
- * A CertPathValidatorException provides support for wrapping - * exceptions. The {@link #getCause getCause} method returns the throwable, - * if any, that caused this exception to be thrown.
- *
- * A CertPathValidatorException may also include the - * certification path that was being validated when the exception was thrown - * and the index of the certificate in the certification path that caused the - * exception to be thrown. Use the {@link #getCertPath getCertPath} and - * {@link #getIndex getIndex} methods to retrieve this information.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see CertPathValidator - **/ -public class CertPathValidatorException extends GeneralSecurityException -{ - private Throwable cause; - private CertPath certPath; - private int index = -1; - - /** - * Creates a CertPathValidatorException with - * no detail message. - */ - public CertPathValidatorException() - { - super(); - } - - /** - * Creates a CertPathValidatorException with the given - * detail message. A detail message is a String that - * describes this particular exception. - * - * @param messag the detail message - */ - public CertPathValidatorException(String message) - { - super(message); - } - - /** - * Creates a CertPathValidatorException with the specified - * detail message and cause. - * - * @param msg the detail message - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or unknown.) - */ - public CertPathValidatorException(String message, Throwable cause) - { - super(message); - this.cause = cause; - } - - /** - * Creates a CertPathValidatorException with the specified - * detail message, cause, certification path, and index. - * - * @param msg the detail message (or null if none) - * @param cause the cause (or null if none) - * @param certPath the certification path that was in the process of - * being validated when the error was encountered - * @param index the index of the certificate in the certification path - * that caused the error (or -1 if not applicable). Note that - * the list of certificates in a CertPath is zero based. - * - * @exception IndexOutOfBoundsException if the index is out of range - * (index < -1 || (certPath != null && index >= - * certPath.getCertificates().size()) - * @exception IllegalArgumentException if certPath is - * null and index is not -1 - */ - public CertPathValidatorException(String message, Throwable cause, CertPath certPath, int index) - { - super( message ); - - if ( certPath == null && index != -1 ) - throw new IllegalArgumentException( "certPath = null and index != -1" ); - if ( index < -1 || ( certPath != null && index >= certPath.getCertificates().size() ) ) - throw new IndexOutOfBoundsException( " index < -1 or out of bound of certPath.getCertificates()" ); - - this.cause = cause; - this.certPath = certPath; - this.index = index; - } - - /** - * Creates a CertPathValidatorException that wraps the - * specified throwable. This allows any exception to be converted into a - * CertPathValidatorException, while retaining information - * about the wrapped exception, which may be useful for debugging. The - * detail message is set to (cause==null ? null : cause.toString() - * ) (which typically contains the class and detail message of - * cause). - * - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or unknown.) - */ - public CertPathValidatorException(Throwable cause) - { - this.cause = cause; - } - - /** - * Returns the detail message for this - * CertPathValidatorException. - * - * @return the detail message, or null if neither the message - * nor cause were specified - */ - public String getMessage() - { - String message = super.getMessage(); - - if ( message == null && cause == null ) - return null; - - StringBuffer s = new StringBuffer(); - if ( message != null ) - { - s.append(message).append('\n'); - } - if ( cause != null ) - { - s.append("Cause:\n").append(cause.getMessage()).append('\n'); - } - return s.toString(); - } - - /** - * Returns the certification path that was being validated when - * the exception was thrown. - * - * @return the CertPath that was being validated when - * the exception was thrown (or null if not specified) - */ - public CertPath getCertPath() - { - return certPath; - } - - /** - * Returns the index of the certificate in the certification path - * that caused the exception to be thrown. Note that the list of - * certificates in a CertPath is zero based. If no - * index has been set, -1 is returned. - * - * @return the index that has been set, or -1 if none has been set - */ - public int getIndex() - { - return index; - } - - /** - * Returns the cause of this CertPathValidatorException or - * null if the cause is nonexistent or unknown. - * - * @return the cause of this throwable or null if the cause - * is nonexistent or unknown. - */ - public Throwable getCause() - { - return cause; - } - - /** - * Returns a string describing this exception, including a description - * of the internal (wrapped) cause if there is one. - * - * @return a string representation of this - * CertPathValidatorException - */ - public String toString() - { - StringBuffer sb = new StringBuffer(); - String s = getMessage(); - if ( s != null ) - { - sb.append( s ); - } - if ( getIndex() >= 0 ) - { - sb.append("index in certpath: ").append(getIndex()).append('\n'); - sb.append(getCertPath()); - } - return sb.toString(); - } - - /** - * Prints a stack trace to System.err, including the backtrace - * of the cause, if any. - */ - public void printStackTrace() - { - printStackTrace(System.err); - } - - /** - * Prints a stack trace to a PrintStream, including the - * backtrace of the cause, if any. - * - * @param ps the PrintStream to use for output - */ - public void printStackTrace(PrintStream ps) - { - super.printStackTrace(ps); - if ( getCause() != null ) - { - getCause().printStackTrace(ps); - } - } - - /** - * Prints a stack trace to a PrintWriter, including the - * backtrace of the cause, if any. - * - * @param pw the PrintWriter to use for output - */ - public void printStackTrace(PrintWriter pw) - { - super.printStackTrace(pw); - if ( getCause() != null ) - { - getCause().printStackTrace(pw); - } - } -} - diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathValidatorResult.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathValidatorResult.java deleted file mode 100644 index ec09641d5..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathValidatorResult.java +++ /dev/null @@ -1,22 +0,0 @@ -package java.security.cert; - -/** - * A specification of the result of a certification path validator algorithm.
- *
- * The purpose of this interface is to group (and provide type safety - * for) all certification path validator results. All results returned - * by the {@link CertPathValidator#validate CertPathValidator.validate} - * method must implement this interface. - * - * @see CertPathValidator - **/ -public interface CertPathValidatorResult extends Cloneable -{ - /** - * Makes a copy of this CertPathValidatorResult. Changes to the - * copy will not affect the original and vice versa. - * - * @return a copy of this CertPathValidatorResult - */ - public Object clone(); -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathValidatorSpi.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathValidatorSpi.java deleted file mode 100644 index c70bc47fc..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertPathValidatorSpi.java +++ /dev/null @@ -1,59 +0,0 @@ -package java.security.cert; - -import java.security.InvalidAlgorithmParameterException; - -/** - * - * The Service Provider Interface (SPI) - * for the {@link CertPathValidator CertPathValidator} class. All - * CertPathValidator implementations must include a class (the - * SPI class) that extends this class (CertPathValidatorSpi) - * and implements all of its methods. In general, instances of this class - * should only be accessed through the CertPathValidator class. - * For details, see the Java Cryptography Architecture.
- *
- * Concurrent Access
- *
- * Instances of this class need not be protected against concurrent - * access from multiple threads. Threads that need to access a single - * CertPathValidatorSpi instance concurrently should synchronize - * amongst themselves and provide the necessary locking before calling the - * wrapping CertPathValidator object.
- *
- * However, implementations of CertPathValidatorSpi may still - * encounter concurrency issues, since multiple threads each - * manipulating a different CertPathValidatorSpi instance need not - * synchronize. - **/ -public abstract class CertPathValidatorSpi extends Object -{ - /** - * The default constructor. - */ - public CertPathValidatorSpi() {} - - /** - * Validates the specified certification path using the specified - * algorithm parameter set.
- *
- * The CertPath specified must be of a type that is - * supported by the validation algorithm, otherwise an - * InvalidAlgorithmParameterException will be thrown. For - * example, a CertPathValidator that implements the PKIX - * algorithm validates CertPath objects of type X.509. - * - * @param certPath the CertPath to be validated - * @param params the algorithm parameters - * - * @return the result of the validation algorithm - * - * @exception CertPathValidatorException if the CertPath - * does not validate - * @exception InvalidAlgorithmParameterException if the specified - * parameters or the type of the specified CertPath are - * inappropriate for this CertPathValidator - */ - public abstract CertPathValidatorResult engineValidate(CertPath certPath, CertPathParameters params) - throws CertPathValidatorException, - InvalidAlgorithmParameterException; -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertSelector.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertSelector.java deleted file mode 100644 index 31bf97448..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertSelector.java +++ /dev/null @@ -1,39 +0,0 @@ -package java.security.cert; - -/** - * A selector that defines a set of criteria for selecting - * Certificates. Classes that implement this interface - * are often used to specify which Certificates should - * be retrieved from a CertStore.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this interface are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see Certificate - * @see CertStore - * @see CertStore#getCertificates - */ -public interface CertSelector extends Cloneable -{ - /** - * Decides whether a Certificate should be selected. - * - * @param cert the Certificate to be checked - * @return true if the Certificate - * should be selected, false otherwise - */ - public boolean match(Certificate cert); - - /** - * Makes a copy of this CertSelector. Changes to the - * copy will not affect the original and vice versa. - * - * @return a copy of this CertSelector - */ - public Object clone(); -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertStore.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertStore.java deleted file mode 100644 index 0e2c6d2f7..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertStore.java +++ /dev/null @@ -1,352 +0,0 @@ -package java.security.cert; - -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.Security; -import java.util.Collection; - -/** - * A class for retrieving Certificates and CRLs - * from a repository.
- *
- * This class uses a provider-based architecture, as described in the - * Java Cryptography Architecture. - * To create a CertStore, call one of the static - * getInstance methods, passing in the type of - * CertStore desired, any applicable initialization parameters - * and optionally the name of the provider desired.
- *
- * Once the CertStore has been created, it can be used to - * retrieve Certificates and CRLs by calling its - * {@link #getCertificates(CertSelector selector) getCertificates} and - * {@link #getCRLs(CRLSelector selector) getCRLs} methods.
- *
- * Unlike a {@link java.security.KeyStore KeyStore}, which provides access - * to a cache of private keys and trusted certificates, a - * CertStore is designed to provide access to a potentially - * vast repository of untrusted certificates and CRLs. For example, an LDAP - * implementation of CertStore provides access to certificates - * and CRLs stored in one or more directories using the LDAP protocol and the - * schema as defined in the RFC service attribute. See Appendix A in the - * Java Certification Path API Programmer's Guide for more information about - * standard CertStore types.
- *
- * Concurrent Access
- *
- * All public methods of CertStore objects must be thread-safe. - * That is, multiple threads may concurrently invoke these methods on a - * single CertStore object (or more than one) with no - * ill effects. This allows a CertPathBuilder to search for a - * CRL while simultaneously searching for further certificates, for instance.
- *
- * The static methods of this class are also guaranteed to be thread-safe. - * Multiple threads may concurrently invoke the static methods defined in - * this class with no ill effects.
- *
- * Uses {@link CertUtil CertUtil} to actualiy load the SPI classes. - * - * @see CertUtil - **/ -public class CertStore extends Object -{ - private CertStoreSpi storeSpi; - private Provider provider; - private String type; - private CertStoreParameters params; - - /** - * Creates a CertStore object of the given type, and - * encapsulates the given provider implementation (SPI object) in it. - * - * @param storeSpi the provider implementation - * @param provider the provider - * @param type the type - * @param params the initialization parameters (may be null) - */ - protected CertStore( CertStoreSpi storeSpi, - Provider provider, - String type, - CertStoreParameters params ) - { - this.storeSpi = storeSpi; - this.provider = provider; - this.type = type; - this.params = params; - } - - /** - * Returns a Collection of Certificates that - * match the specified selector. If no Certificates - * match the selector, an empty Collection will be returned.
- *
- * For some CertStore types, the resulting - * Collection may not contain all of the - * Certificates that match the selector. For instance, - * an LDAP CertStore may not search all entries in the - * directory. Instead, it may just search entries that are likely to - * contain the Certificates it is looking for.
- *
- * Some CertStore implementations (especially LDAP - * CertStores) may throw a CertStoreException - * unless a non-null CertSelector is provided that - * includes specific criteria that can be used to find the certificates. - * Issuer and/or subject names are especially useful criteria. - * - * @param selector A CertSelector used to select which - * Certificates should be returned. Specify null - * to return all Certificates (if supported). - * - * @return A Collection of Certificates that - * match the specified selector (never null) - * @exception CertStoreException if an exception occurs - */ - public final Collection getCertificates( CertSelector selector ) - throws CertStoreException - { - return storeSpi.engineGetCertificates( selector ); - } - - /** - * Returns a Collection of CRLs that - * match the specified selector. If no CRLs - * match the selector, an empty Collection will be returned.
- *
- * For some CertStore types, the resulting - * Collection may not contain all of the - * CRLs that match the selector. For instance, - * an LDAP CertStore may not search all entries in the - * directory. Instead, it may just search entries that are likely to - * contain the CRLs it is looking for.
- *
- * Some CertStore implementations (especially LDAP - * CertStores) may throw a CertStoreException - * unless a non-null CRLSelector is provided that - * includes specific criteria that can be used to find the CRLs. - * Issuer names and/or the certificate to be checked are especially useful. - * - * @param selector A CRLSelector used to select which - * CRLs should be returned. Specify null - * to return all CRLs (if supported). - * - * @return A Collection of CRLs that - * match the specified selector (never null) - * - * @exception CertStoreException if an exception occurs - */ - public final Collection getCRLs( CRLSelector selector ) - throws CertStoreException - { - return storeSpi.engineGetCRLs( selector ); - } - - /** - * Returns a CertStore object that implements the specified - * CertStore type and is initialized with the specified - * parameters.
- *
- * If the default provider package provides an implementation - * of the specified CertStore type, an instance of - * CertStore containing that implementation is returned. - * If the requested type is not available in the default package, other - * packages are searched.
- *
- * The CertStore that is returned is initialized with the - * specified CertStoreParameters. The type of parameters - * needed may vary between different types of CertStores. - * Note that the specified CertStoreParameters object is - * cloned. - * - * @param type the name of the requested CertStore type - * @param params the initialization parameters (may be null) - * - * @return a CertStore object that implements the specified - * CertStore type - * - * @exception NoSuchAlgorithmException if the requested type is not - * available in the default provider package or any of the other provider - * packages that were searched - * @exception InvalidAlgorithmParameterException if the specified - * initialization parameters are inappropriate for this - * CertStore - */ - public static CertStore getInstance( String type, - CertStoreParameters params) - throws InvalidAlgorithmParameterException, - NoSuchAlgorithmException - { - try { - CertUtil.Implementation imp = - CertUtil.getImplementation( "CertStore", type, (String)null, - new Class[] { CertStoreParameters.class }, - new Object[] { params } ); - if (imp != null) - { - return new CertStore((CertStoreSpi)imp.getEngine(), imp.getProvider(), type, params ); - } - } catch ( NoSuchProviderException ex ) {} - throw new NoSuchAlgorithmException("can't find type " + type); - } - - /** - * Returns a CertStore object that implements the specified - * CertStore type, as supplied by the specified provider - * and initialized with the specified parameters.
- *
- * The CertStore that is returned is initialized with the - * specified CertStoreParameters. The type of parameters - * needed may vary between different types of CertStores. - * Note that the specified CertStoreParameters object is - * cloned. - * - * @param type the requested CertStore type - * @param params the initialization parameters (may be null) - * @param provider the name of the provider - * - * @return a CertStore object that implements the - * specified type, as supplied by the specified provider - * - * @exception NoSuchAlgorithmException if the requested type is not - * available from the specified provider - * @exception InvalidAlgorithmParameterException if the specified - * initialization parameters are inappropriate for this - * CertStore - * @exception NoSuchProviderException if the provider has not been configured - * @exception IllegalArgumentException if the provider is - * null - */ - public static CertStore getInstance( String type, - CertStoreParameters params, - String provider) - throws InvalidAlgorithmParameterException, - NoSuchAlgorithmException, - NoSuchProviderException, - IllegalArgumentException - { - if ( provider == null ) - throw new IllegalArgumentException( "provider must be non-null" ); - - CertUtil.Implementation imp = - CertUtil.getImplementation( "CertStore", type, provider, - new Class[] { CertStoreParameters.class }, - new Object[] { params } ); - if (imp != null) - { - return new CertStore((CertStoreSpi)imp.getEngine(), imp.getProvider(), type, params ); - } - throw new NoSuchAlgorithmException("can't find type " + type); - } - - /** - * Returns a CertStore object that implements the specified - * CertStore type, as supplied by the specified provider and - * initialized with the specified parameters. - * Note: the provider doesn't have to be registered.
- *
- * The CertStore that is returned is initialized with the - * specified CertStoreParameters. The type of parameters - * needed may vary between different types of CertStores. - * Note that the specified CertStoreParameters object is - * cloned. - * - * @param type the requested CertStore type - * @param params the initialization parameters (may be null) - * @param provider the provider - * - * @return a CertStore object that implements the - * specified type, as supplied by the specified provider - * - * @exception NoSuchAlgorithmException if the requested type is not - * available from the specified provider - * @exception InvalidAlgorithmParameterException if the specified - * initialization parameters are inappropriate for this - * CertStore - * @exception IllegalArgumentException if the provider is - * null - */ - public static CertStore getInstance( String type, - CertStoreParameters params, - Provider provider ) - throws NoSuchAlgorithmException, - InvalidAlgorithmParameterException, - IllegalArgumentException - { - if ( provider == null ) - throw new IllegalArgumentException( "provider must be non-null" ); - CertUtil.Implementation imp = - CertUtil.getImplementation( "CertStore", type, provider, - new Class[] { CertStoreParameters.class }, - new Object[] { params } ); - if (imp != null) - { - return new CertStore((CertStoreSpi)imp.getEngine(), provider, type, params ); - } - throw new NoSuchAlgorithmException("can't find type " + type); - } - - /** - * Returns the parameters used to initialize this CertStore. - * Note that the CertStoreParameters object is cloned before - * it is returned. - * - * @return the parameters used to initialize this CertStore - * (may be null) - */ - public final CertStoreParameters getCertStoreParameters() - { - return params; - } - - /** - * Returns the type of this CertStore. - * - * @return the type of this CertStore - */ - public final String getType() - { - return type; - } - - /** - * Returns the provider of this CertStore. - * - * @return the provider of this CertStore - */ - public final Provider getProvider() - { - return provider; - } - - /** - * Returns the default CertStore type as specified in the - * Java security properties file, or the string "LDAP" if no - * such property exists. The Java security properties file is located in - * the file named <JAVA_HOME>/lib/security/java.security, where - * <JAVA_HOME> refers to the directory where the SDK was installed.
- *
- * The default CertStore type can be used by applications - * that do not want to use a hard-coded type when calling one of the - * getInstance methods, and want to provide a default - * CertStore type in case a user does not specify its own.
- *
- * The default CertStore type can be changed by setting - * the value of the "certstore.type" security property (in the Java - * security properties file) to the desired type. - * - * @return the default CertStore type as specified in the - * Java security properties file, or the string "LDAP" - * if no such property exists. - */ - public static final String getDefaultType() - { - String defaulttype = null; - defaulttype = Security.getProperty("certstore.type"); - - if ( defaulttype == null || defaulttype.length() <= 0 ) - return "LDAP"; - else - return defaulttype; - } -} - diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertStoreException.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertStoreException.java deleted file mode 100644 index a15bc3df6..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertStoreException.java +++ /dev/null @@ -1,172 +0,0 @@ -package java.security.cert; - -import java.io.PrintStream; -import java.io.PrintWriter; -import java.security.GeneralSecurityException; - -/** - * An exception indicating one of a variety of problems retrieving - * certificates and CRLs from a CertStore.
- *
- * A CertStoreException provides support for wrapping - * exceptions. The {@link #getCause getCause} method returns the throwable, - * if any, that caused this exception to be thrown.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see CertStore - **/ -public class CertStoreException extends GeneralSecurityException -{ - private Throwable cause; - - /** - * Creates a CertStoreException with null as - * its detail message. - */ - public CertStoreException() - { - super(); - } - - /** - * Creates a CertStoreException with the given detail - * message. A detail message is a String that describes this - * particular exception. - * - * @param messag the detail message - */ - public CertStoreException(String message) - { - super(message); - } - - /** - * Creates a CertStoreException with the specified detail - * message and cause. - * - * @param messag the detail message - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or unknown.) - */ - public CertStoreException(String message, Throwable cause) - { - super(message); - this.cause = cause; - } - - /** - * Creates a CertStoreException that wraps the specified - * throwable. This allows any exception to be converted into a - * CertStoreException, while retaining information about the - * cause, which may be useful for debugging. The detail message is - * set to (cause==null ? null : cause.toString()) (which - * typically contains the class and detail message of cause). - * - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or unknown.) - */ - public CertStoreException(Throwable cause) - { - this.cause = cause; - } - - /** - * Returns the detail message for this CertStoreException. - * - * @return the detail message, or null if neither the message - * nor cause were specified - */ - public String getMessage() - { - String message = super.getMessage(); - - if ( message == null && cause == null ) - return null; - - StringBuffer s = new StringBuffer(); - if ( message != null ) - { - s.append(message).append('\n'); - } - if ( cause != null ) - { - s.append("Cause:\n").append(cause.getMessage()); - } - return s.toString(); - } - - /** - * Returns the cause of this CertStoreException or - * null if the cause is nonexistent or unknown. - * - * @return the cause of this throwable or null if the cause - * is nonexistent or unknown. - */ - public Throwable getCause() - { - return cause; - } - - /** - * Returns a string describing this exception, including a description - * of the internal (wrapped) cause if there is one. - * - * @return a string representation of this - * CertStoreException - */ - public String toString() - { - String message = getMessage(); - if ( message == null ) - return ""; - - return message; - } - - /** - * Prints a stack trace to System.err, including the backtrace - * of the cause, if any. - */ - public void printStackTrace() { - printStackTrace(System.err); - } - - /** - * Prints a stack trace to a PrintStream, including the - * backtrace of the cause, if any. - * - * @param ps the PrintStream to use for output - */ - public void printStackTrace(PrintStream ps) { - super.printStackTrace(ps); - if ( cause != null ) { - cause.printStackTrace(ps); - } - } - - /** - * Prints a stack trace to a PrintWriter, including the - * backtrace of the cause, if any. - * - * @param pw the PrintWriter to use for output - */ - public void printStackTrace(PrintWriter pw) { - if ( cause != null ) { - cause.printStackTrace(pw); - } - super.printStackTrace(pw); - if ( cause != null ) { - cause.printStackTrace(pw); - } - } -} - diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertStoreParameters.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertStoreParameters.java deleted file mode 100644 index 58a70b372..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertStoreParameters.java +++ /dev/null @@ -1,52 +0,0 @@ -package java.security.cert; - -/** - * A specification of CertStore parameters.
- *
- * The purpose of this interface is to group (and provide type safety for) - * all CertStore parameter specifications. All - * CertStore parameter specifications must implement this - * interface.
- *
- * Typically, a CertStoreParameters object is passed as a parameter - * to one of the {@link CertStore#getInstance CertStore.getInstance} methods. - * The getInstance method returns a CertStore that - * is used for retrieving Certificates and CRLs. The - * CertStore that is returned is initialized with the specified - * parameters. The type of parameters needed may vary between different types - * of CertStores. - * - * @see CertStore#getInstance - **/ -public interface CertStoreParameters extends Cloneable -{ - /** - * Makes a copy of this CertStoreParameters.
- *
- * The precise meaning of "copy" may depend on the class of - * the CertStoreParameters object. A typical implementation - * performs a "deep copy" of this object, but this is not an absolute - * requirement. Some implementations may perform a "shallow copy" of some - * or all of the fields of this object.
- *
- * Note that the CertStore.getInstance methods make a copy - * of the specified CertStoreParameters. A deep copy - * implementation of clone is safer and more robust, as it - * prevents the caller from corrupting a shared CertStore by - * subsequently modifying the contents of its initialization parameters. - * However, a shallow copy implementation of clone is more - * appropriate for applications that need to hold a reference to a - * parameter contained in the CertStoreParameters. For example, - * a shallow copy clone allows an application to release the resources of - * a particular CertStore initialization parameter immediately, - * rather than waiting for the garbage collection mechanism. This should - * be done with the utmost care, since the CertStore may still - * be in use by other threads.
- *
- * Each subclass should state the precise behavior of this method so - * that users and developers know what to expect. - * - * @return a copy of this CertStoreParameters - */ - public Object clone(); -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertStoreSpi.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertStoreSpi.java deleted file mode 100644 index b92cf4aa5..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertStoreSpi.java +++ /dev/null @@ -1,104 +0,0 @@ -package java.security.cert; - -import java.security.InvalidAlgorithmParameterException; -import java.util.Collection; - -/** - * The Service Provider Interface (SPI) - * for the {@link CertStore CertStore} class. All CertStore - * implementations must include a class (the SPI class) that extends - * this class (CertStoreSpi), provides a constructor with - * a single argument of type CertStoreParameters, and implements - * all of its methods. In general, instances of this class should only be - * accessed through the CertStore class. - * For details, see the Java Cryptography Architecture.
- *
- * Concurrent Access
- *
- * The public methods of all CertStoreSpi objects must be - * thread-safe. That is, multiple threads may concurrently invoke these - * methods on a single CertStoreSpi object (or more than one) - * with no ill effects. This allows a CertPathBuilder to search - * for a CRL while simultaneously searching for further certificates, for - * instance.
- *
- * Simple CertStoreSpi implementations will probably ensure - * thread safety by adding a synchronized keyword to their - * engineGetCertificates and engineGetCRLs methods. - * More sophisticated ones may allow truly concurrent access. - **/ -public abstract class CertStoreSpi - extends Object -{ - - /** - * The sole constructor. - * - * @param params the initialization parameters (may be null) - * @exception InvalidAlgorithmParameterException if the initialization - * parameters are inappropriate for this CertStoreSpi - */ - public CertStoreSpi( CertStoreParameters params ) - throws InvalidAlgorithmParameterException {} - - /** - * Returns a Collection of Certificates that - * match the specified selector. If no Certificates - * match the selector, an empty Collection will be returned.
- *
- * For some CertStore types, the resulting - * Collection may not contain all of the - * Certificates that match the selector. For instance, - * an LDAP CertStore may not search all entries in the - * directory. Instead, it may just search entries that are likely to - * contain the Certificates it is looking for.
- *
- * Some CertStore implementations (especially LDAP - * CertStores) may throw a CertStoreException - * unless a non-null CertSelector is provided that includes - * specific criteria that can be used to find the certificates. Issuer - * and/or subject names are especially useful criteria. - * - * @param selector A CertSelector used to select which - * Certificates should be returned. Specify null - * to return all Certificates (if supported). - * - * @return A Collection of Certificates that - * match the specified selector (never null) - * - * @exception CertStoreException if an exception occurs - */ - public abstract Collection engineGetCertificates( CertSelector selector ) - throws CertStoreException; - - /** - * Returns a Collection of CRLs that - * match the specified selector. If no CRLs - * match the selector, an empty Collection will be returned.
- *
- * For some CertStore types, the resulting - * Collection may not contain all of the - * CRLs that match the selector. For instance, - * an LDAP CertStore may not search all entries in the - * directory. Instead, it may just search entries that are likely to - * contain the CRLs it is looking for.
- *
- * Some CertStore implementations (especially LDAP - * CertStores) may throw a CertStoreException - * unless a non-null CRLSelector is provided that includes - * specific criteria that can be used to find the CRLs. Issuer names - * and/or the certificate to be checked are especially useful. - * - * @param selector A CRLSelector used to select which - * CRLs should be returned. Specify null - * to return all CRLs (if supported). - * - * @return A Collection of CRLs that - * match the specified selector (never null) - * - * @exception CertStoreException if an exception occurs - */ - public abstract Collection engineGetCRLs( CRLSelector selector ) - throws CertStoreException; -} - diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertUtil.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertUtil.java deleted file mode 100644 index 216a8d8e4..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertUtil.java +++ /dev/null @@ -1,556 +0,0 @@ -package java.security.cert; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.Security; - -import org.spongycastle.asn1.ASN1Object; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DERIA5String; -import org.spongycastle.asn1.DEROutputStream; -import org.spongycastle.asn1.OIDTokenizer; -import org.spongycastle.asn1.x509.X509Name; -import org.spongycastle.util.Strings; - -class CertUtil -{ - static class Implementation - { - Object engine; - Provider provider; - - Implementation( - Object engine, - Provider provider) - { - this.engine = engine; - this.provider = provider; - } - - Object getEngine() - { - return engine; - } - - Provider getProvider() - { - return provider; - } - } - - /** - * see if we can find an algorithm (or its alias and what it represents) in - * the property table for the given provider. - * - * @return null if no algorithm found, an Implementation if it is. - */ - static Implementation getImplementation( - String baseName, - String algorithm, - Provider prov) - { - if (prov == null) - { - Provider[] provider = Security.getProviders(); - - // - // search every provider looking for the algorithm we want. - // - for (int i = 0; i != provider.length; i++) - { - Implementation imp = getImplementation(baseName, algorithm, provider[i]); - if (imp != null) - { - return imp; - } - } - - return null; - } - - String alias; - - while ((alias = prov.getProperty("Alg.Alias." + baseName + "." + algorithm)) != null) - { - algorithm = alias; - } - - String className = prov.getProperty(baseName + "." + algorithm); - - if (className != null) - { - try - { - return new Implementation(Class.forName(className).newInstance(), prov); - } - catch (ClassNotFoundException e) - { - throw new IllegalStateException( - "algorithm " + algorithm + " in provider " + prov.getName() + " but no class found!"); - } - catch (Exception e) - { - throw new IllegalStateException( - "algorithm " + algorithm + " in provider " + prov.getName() + " but class inaccessible: " + e.toString()); - } - } - - return null; - } - - /** - * return an implementation for a given algorithm/provider. - * If the provider is null, we grab the first avalaible who has the required algorithm. - * - * @return null if no algorithm found, an Implementation if it is. - * @exception NoSuchProviderException if a provider is specified and not found. - */ - static Implementation getImplementation( - String baseName, - String algorithm, - String provider) - throws NoSuchProviderException - { - if (provider == null) - { - Provider[] prov = Security.getProviders(); - - // - // search every provider looking for the algorithm we want. - // - for (int i = 0; i != prov.length; i++) - { - Implementation imp = getImplementation(baseName, algorithm, prov[i]); - if (imp != null) - { - return imp; - } - } - } - else - { - Provider prov = Security.getProvider(provider); - - if (prov == null) - { - throw new NoSuchProviderException("Provider " + provider + " not found"); - } - - return getImplementation(baseName, algorithm, prov); - } - - return null; - } - - /** - * see if we can find an algorithm (or its alias and what it represents) in - * the property table for the given provider. - * - * @return null if no algorithm found, an Implementation if it is. - */ - static Implementation getImplementation(String baseName, String algorithm, - Provider prov, Class[] ctorparamtype, Object[] ctorparam) - throws InvalidAlgorithmParameterException - { - String alias; - - while ((alias = prov.getProperty("Alg.Alias." + baseName + "." - + algorithm)) != null) - { - algorithm = alias; - } - - String className = prov.getProperty(baseName + "." + algorithm); - - if (className != null) - { - try - { - return new Implementation(Class.forName(className) - .getConstructor(ctorparamtype).newInstance(ctorparam), - prov); - } - catch (ClassNotFoundException e) - { - throw new IllegalStateException("algorithm " + algorithm - + " in provider " + prov.getName() - + " but no class found!"); - } - catch (Exception e) - { - if (e instanceof InvalidAlgorithmParameterException) - { - throw (InvalidAlgorithmParameterException)e; - } - - throw new IllegalStateException("algorithm " + algorithm - + " in provider " + prov.getName() - + " but class inaccessible!"); - } - } - - return null; - } - - /** - * return an implementation for a given algorithm/provider. If the provider - * is null, we grab the first avalaible who has the required algorithm. - * - * @return null if no algorithm found, an Implementation if it is. - * - * @exception NoSuchProviderException - * if a provider is specified and not found. - */ - static Implementation getImplementation(String baseName, String algorithm, - String provider, Class[] ctorparamtype, Object[] ctorparam) - throws NoSuchProviderException, InvalidAlgorithmParameterException - { - if (provider == null) - { - Provider[] prov = Security.getProviders(); - - // - // search every provider looking for the algorithm we want. - // - for (int i = 0; i != prov.length; i++) - { - Implementation imp = getImplementation(baseName, algorithm, - prov[i], ctorparamtype, ctorparam); - if (imp != null) - { - return imp; - } - } - } - else - { - Provider prov = Security.getProvider(provider); - - if (prov == null) - { - throw new NoSuchProviderException("Provider " + provider - + " not found"); - } - - return getImplementation(baseName, algorithm, prov, ctorparamtype, - ctorparam); - } - - return null; - } - - static byte[] parseGeneralName(int type, String data) throws IOException - { - byte[] encoded = null; - - switch (type) - { - case 0: - throw new IOException( - "unable to parse OtherName String representation"); - case 1: - encoded = parseRfc822(data.trim()); - break; - case 2: - encoded = parseDNSName(data.trim()); - break; - case 3: - throw new IOException( - "unable to parse ORAddress String representation"); - case 4: - encoded = parseX509Name(data.trim()); - break; - case 5: - throw new IOException( - "unable to parse EDIPartyName String representation"); - case 6: - encoded = parseURI(data.trim()); - break; - case 7: - encoded = parseIP(data.trim()); - break; - case 8: - encoded = parseOID(data.trim()); - break; - default: - throw new IOException( - "unable to parse unkown type String representation"); - } - return encoded; - } - - /** - * Check the format of an OID.
- * Throw an IOException if the first component is not 0, 1 or 2 or the - * second component is greater than 39.
- *
- * User {@link org.spongycastle.asn1.OIDTokenizer OIDTokenizer} - * - * @param the - * OID to be checked. - * - * @exception IOException - * if the first component is not 0, 1 or 2 or the second - * component is greater than 39. - */ - static byte[] parseOID(String oid) throws IOException - { - OIDTokenizer tokenizer = new OIDTokenizer(oid); - String token; - if (!tokenizer.hasMoreTokens()) - { - throw new IOException("OID contains no tokens"); - } - token = tokenizer.nextToken(); - if (token == null) - { - throw new IOException("OID contains no tokens"); - } - try - { - int test = (Integer.valueOf(token)).intValue(); - if (test < 0 || test > 2) - { - throw new IOException("first token is not >= 0 and <=2"); - } - if (!tokenizer.hasMoreTokens()) - { - throw new IOException("OID contains only one token"); - } - token = tokenizer.nextToken(); - if (token == null) - { - throw new IOException("OID contains only one token"); - } - test = (Integer.valueOf(token)).intValue(); - if (test < 0 || test > 39) - { - throw new IOException("secon token is not >= 0 and <=39"); - } - } - catch (NumberFormatException ex) - { - throw new IOException("token: " + token + ": " + ex.toString()); - } - ASN1Object derData = new ASN1ObjectIdentifier(oid); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - DEROutputStream derOutStream = new DEROutputStream(outStream); - derOutStream.writeObject(derData); - derOutStream.close(); - return outStream.toByteArray(); - } - - /** - * Parse the given IPv4 or IPv6 into DER encoded byte array representation. - * - * @param the - * IP in well known String format - * - * @return the IP as byte array - * - * @exception IOException - * if the String could not be parsed - */ - private static byte[] parseIP(String data) throws IOException - { - byte[] encoded = parseIPv4(data); - - if (encoded == null) - { - encoded = parseIPv6(data); - } - - if (encoded == null) - { - throw new IOException( - "unable to parse IP to DER encoded byte array"); - } - - return encoded; - } - - /** - * Parse the given IPv4 into DER encoded byte array representation. - * - * @param the - * IP in well known String format - * - * @return the IP as byte array or null if not parseable - */ - private static byte[] parseIPv4(String data) - { - if (data.length() == 0) - { - return null; - } - - int octet; - int octets = 0; - byte[] dst = new byte[4]; - - int pos = 0; - int start = 0; - while (start < data.length() - && (pos = data.indexOf('.', start)) > start && pos - start > 3) - { - try - { - octet = (Integer.valueOf(data.substring(start, pos - start))) - .intValue(); - } - catch (NumberFormatException ex) - { - return null; - } - if (octet < 0 || octet > 255) - { - return null; - } - dst[octets++] = (byte)(octet & 0xff); - - start = pos + 1; - } - - if (octets < 4) - { - return null; - } - - return dst; - } - - /** - * Parse the given IPv6 into DER encoded byte array representation.
- *
- * TODO: implement this - * - * @param the - * IP in well known String format - * - * @return the IP as byte array or null if not parseable - */ - private static byte[] parseIPv6(String data) - { - return null; - } - - /** - * Parse the given URI into DER encoded byte array representation. - * - * @param the - * URI in well known String format - * - * @return the URI as byte array - * - * @exception IOException - * if the String could not be parsed - */ - private static byte[] parseURI(String data) throws IOException - { - // TODO do parsing test - ASN1Object derData = new DERIA5String(data); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - DEROutputStream derOutStream = new DEROutputStream(outStream); - derOutStream.writeObject(derData); - derOutStream.close(); - return outStream.toByteArray(); - } - - /** - * Parse the given rfc822 addr-spec into DER encoded byte array - * representation. - * - * @param the - * rfc822 addr-spec in well known String format - * - * @return the rfc822 addr-spec as byte array - * - * @exception IOException - * if the String could not be parsed - */ - private static byte[] parseRfc822(String data) throws IOException - { - int tmpInt = data.indexOf('@'); - if (tmpInt < 0 || tmpInt >= data.length() - 1) - { - throw new IOException("wrong format of rfc822Name:" + data); - } - // TODO more test for illegal charateers - ASN1Object derData = new DERIA5String(data); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - DEROutputStream derOutStream = new DEROutputStream(outStream); - derOutStream.writeObject(derData); - derOutStream.close(); - return outStream.toByteArray(); - } - - /** - * Parse the given DNS name into DER encoded byte array representation. The - * String must be in den preffered name syntax as defined in RFC 1034. - * - * @param the - * DNS name in well known String format - * - * @return the DNS name as byte array - * - * @exception IOException - * if the String could not be parsed - */ - private static byte[] parseDNSName(String data) throws IOException - { - // TODO more test for illegal charateers - ASN1Object derData = new DERIA5String(data); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - DEROutputStream derOutStream = new DEROutputStream(outStream); - derOutStream.writeObject(derData); - derOutStream.close(); - return outStream.toByteArray(); - } - - /** - * Parse the given X.509 name into DER encoded byte array representation. - * - * @param the - * X.509 name in well known String format - * - * @return the X.509 name as byte array - * - * @exception IOException - * if the String could not be parsed - */ - private static byte[] parseX509Name(String data) throws IOException - { - // TODO more test for illegal charateers - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - DEROutputStream derOutStream = new DEROutputStream(outStream); - derOutStream.writeObject(new X509Name(trimX509Name(data))); - derOutStream.close(); - return outStream.toByteArray(); - } - - /** - * Returns the given name converted to upper case and all multi spaces squezed - * to one space. - **/ - static String trimX509Name(String name) - { - String data = Strings.toUpperCase(name.trim()); - int pos; - while ((pos = data.indexOf(" ")) >= 0) - { - data = data.substring(0, pos) + data.substring(pos + 1); - } - while ((pos = data.indexOf(" =")) >= 0) - { - data = data.substring(0, pos) + data.substring(pos + 1); - } - while ((pos = data.indexOf("= ")) >= 0) - { - data = data.substring(0, pos + 1) + data.substring(pos + 2); - } - return data; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/Certificate.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/Certificate.java deleted file mode 100644 index 201e209a3..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/Certificate.java +++ /dev/null @@ -1,80 +0,0 @@ - -package java.security.cert; - -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PublicKey; -import java.security.SignatureException; - -public abstract class Certificate extends Object -{ - private String type; - - protected Certificate(String type) - { - this.type = type; - } - - public boolean equals(Object other) - { - if ( !(other instanceof Certificate) ) - return false; - - if ( other == this ) - return true; - - try - { - byte[] enc1 = getEncoded(); - byte[] enc2 = ((Certificate)other).getEncoded(); - - return MessageDigest.isEqual(enc1, enc2); - } - catch (CertificateEncodingException e) - { - return false; - } - } - - public final String getType() - { - return type; - } - - // XXX - public int hashCode() - { - try - { - byte[] enc1 = getEncoded(); - int hc = 0; - for (int i = 0; i < enc1.length; i++) - { - hc += enc1[i]; - } - - return hc; - } - catch (CertificateEncodingException e) - { - return 0; - } - } - - public abstract byte[] getEncoded() - throws CertificateEncodingException; - - public abstract PublicKey getPublicKey(); - - public abstract String toString(); - - public abstract void verify(PublicKey key) - throws CertificateException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException; - - public abstract void verify(PublicKey key, String sigProvider) - throws CertificateException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException; -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateEncodingException.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateEncodingException.java deleted file mode 100644 index 47545a5c0..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateEncodingException.java +++ /dev/null @@ -1,14 +0,0 @@ - -package java.security.cert; - -public class CertificateEncodingException extends CertificateException -{ - public CertificateEncodingException() - { - } - - public CertificateEncodingException(String msg) - { - super(msg); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateException.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateException.java deleted file mode 100644 index 644c6249f..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateException.java +++ /dev/null @@ -1,16 +0,0 @@ - -package java.security.cert; - -import java.security.GeneralSecurityException; - -public class CertificateException extends GeneralSecurityException -{ - public CertificateException() - { - } - - public CertificateException(String msg) - { - super(msg); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateExpiredException.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateExpiredException.java deleted file mode 100644 index 1a9062aa2..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateExpiredException.java +++ /dev/null @@ -1,14 +0,0 @@ - -package java.security.cert; - -public class CertificateExpiredException extends CertificateException -{ - public CertificateExpiredException() - { - } - - public CertificateExpiredException(String msg) - { - super(msg); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateFactory.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateFactory.java deleted file mode 100644 index e86cd3a03..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateFactory.java +++ /dev/null @@ -1,183 +0,0 @@ - -package java.security.cert; - -import java.io.InputStream; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -/** - * Uses {@link CertUtil CertUtil} to actualiy load the SPI classes. - * - * @see CertUtil - **/ -public class CertificateFactory -{ - private CertificateFactorySpi certFacSpi; - private Provider provider; - private String type; - - protected CertificateFactory( - CertificateFactorySpi certFacSpi, - Provider provider, - String type) - { - this.certFacSpi = certFacSpi; - this.provider = provider; - this.type = type; - } - - public final CRL generateCRL(InputStream inStream) - throws CRLException - { - return certFacSpi.engineGenerateCRL(inStream); - } - - public final Collection generateCRLs(InputStream inStream) - throws CRLException - { - return certFacSpi.engineGenerateCRLs(inStream); - } - - public final Certificate generateCertificate(InputStream inStream) - throws CertificateException - { - return certFacSpi.engineGenerateCertificate(inStream); - } - - public final /*Sk13 Vector*/ Collection generateCertificates(InputStream inStream) - throws CertificateException - { - return certFacSpi.engineGenerateCertificates(inStream); - } - - /** - * Returns an iteration of the CertPath encodings supported - * by this certificate factory, with the default encoding first. See - * Appendix A in the - * Java Certification Path API Programmer's Guide for information about - * standard encoding names and their formats.
- *
- * Attempts to modify the returned Iterator via its - * remove method result in an - * UnsupportedOperationException. - * - * @return an Iterator over the names of the supported - * CertPath encodings (as Strings) - */ - public final Iterator getCertPathEncodings() - { - return certFacSpi.engineGetCertPathEncodings(); - } - - /** - * Generates a CertPath object and initializes it with - * the data read from the InputStream inStream. The data - * is assumed to be in the default encoding. The name of the default - * encoding is the first element of the Iterator returned by - * the {@link #getCertPathEncodings getCertPathEncodings} method. - * - * @param inStream an InputStream containing the data - * - * @return a CertPath initialized with the data from the - * InputStream - * - * @exception CertificateException if an exception occurs while decoding - */ - public final CertPath generateCertPath(InputStream inStream) - throws CertificateException - { - return certFacSpi.engineGenerateCertPath(inStream); - } - - /** - * Generates a CertPath object and initializes it with - * the data read from the InputStream inStream. The data - * is assumed to be in the specified encoding. See Appendix A in the - * - * Java Certification Path API Programmer's Guide - * for information about standard encoding names and their formats. - * - * @param inStream an InputStream containing the data - * @param encoding the encoding used for the data - * - * @return a CertPath initialized with the data from the - * InputStream - * - * @exception CertificateException if an exception occurs while decoding or - * the encoding requested is not supported - */ - public final CertPath generateCertPath(InputStream inStream, String encoding) - throws CertificateException - { - return certFacSpi.engineGenerateCertPath(inStream, encoding); - } - - /** - * Generates a CertPath object and initializes it with - * a List of Certificates.
- *
- * The certificates supplied must be of a type supported by the - * CertificateFactory. They will be copied out of the supplied - * List object. - * - * @param certificates a List of Certificates - * - * @return a CertPath initialized with the supplied list of - * certificates - * - * @exception CertificateException if an exception occurs - */ - public final CertPath generateCertPath(List certificates) - throws CertificateException - { - return certFacSpi.engineGenerateCertPath( certificates ); - } - - public static final CertificateFactory getInstance(String type) - throws CertificateException - { - try - { - CertUtil.Implementation imp = CertUtil.getImplementation("CertificateFactory", type, (String)null); - - if (imp != null) - { - return new CertificateFactory((CertificateFactorySpi)imp.getEngine(), imp.getProvider(), type); - } - - throw new CertificateException("can't find type " + type); - } - catch (NoSuchProviderException e) - { - throw new CertificateException(type + " not found"); - } - } - - public static final CertificateFactory getInstance( - String type, - String provider) - throws CertificateException, NoSuchProviderException - { - CertUtil.Implementation imp = CertUtil.getImplementation("CertificateFactory", type, provider); - - if (imp != null) - { - return new CertificateFactory((CertificateFactorySpi)imp.getEngine(), imp.getProvider(), type); - } - - throw new CertificateException("can't find type " + type); - } - - public final Provider getProvider() - { - return provider; - } - - public final String getType() - { - return type; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateFactorySpi.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateFactorySpi.java deleted file mode 100644 index 8cc06fc2e..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateFactorySpi.java +++ /dev/null @@ -1,111 +0,0 @@ - -package java.security.cert; - -import java.io.InputStream; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -public abstract class CertificateFactorySpi -{ - public CertificateFactorySpi() - { - } - - public abstract CRL engineGenerateCRL(InputStream inStream) - throws CRLException; - - public abstract Collection engineGenerateCRLs(InputStream inStream) - throws CRLException; - - public abstract Certificate engineGenerateCertificate(InputStream inStream) - throws CertificateException; - - public abstract /*SK13 Vector*/ Collection engineGenerateCertificates(InputStream inStream) - throws CertificateException; - - /** - * Returns an iteration of the CertPath encodings supported - * by this certificate factory, with the default encoding first. See - * Appendix A in the - * Java Certification Path API Programmer's Guide - * for information about standard encoding names.
- *
- * Attempts to modify the returned Iterator via its - * remove method result in an - * UnsupportedOperationException.
- *
- * This method was added to version 1.4 of the Java 2 Platform - * Standard Edition. In order to maintain backwards compatibility with - * existing service providers, this method cannot be abstract - * and by default throws an UnsupportedOperationException. - * - * @return an Iterator over the names of the supported - * CertPath encodings (as Strings) - * - * @exception UnsupportedOperationException if the method is not supported - */ - public abstract Iterator engineGetCertPathEncodings(); - - /** - * Generates a CertPath object and initializes it with - * the data read from the InputStream inStream. The data - * is assumed to be in the default encoding. - * - * @param inStream an InputStream containing the data - * - * @return a CertPath initialized with the data from the - * InputStream - * - * @exception CertificateException if an exception occurs while decoding - */ - public abstract CertPath engineGenerateCertPath(InputStream inStream) - throws CertificateException; - - /** - * Generates a CertPath object and initializes it with - * the data read from the InputStream inStream. The data - * is assumed to be in the specified encoding.
- *
- * This method was added to version 1.4 of the Java 2 Platform - * Standard Edition. In order to maintain backwards compatibility with - * existing service providers, this method cannot be abstract - * and by default throws an UnsupportedOperationException. - * - * @param inStream an InputStream containing the data - * @param encoding the encoding used for the data - * - * @return a CertPath initialized with the data from the - * InputStream - * - * @exception CertificateException if an exception occurs while decoding or - * the encoding requested is not supported - * @exception UnsupportedOperationException if the method is not supported - */ - public abstract CertPath engineGenerateCertPath(InputStream inStream, String encoding) - throws CertificateException; - - /** - * Generates a CertPath object and initializes it with - * a List of Certificates.
- *
- * The certificates supplied must be of a type supported by the - * CertificateFactory. They will be copied out of the supplied - * List object.
- *
- * This method was added to version 1.4 of the Java 2 Platform - * Standard Edition. In order to maintain backwards compatibility with - * existing service providers, this method cannot be abstract - * and by default throws an UnsupportedOperationException. - * - * @param certificates a List of Certificates - * - * @return a CertPath initialized with the supplied list of - * certificates - * - * @exception CertificateException if an exception occurs - * @exception UnsupportedOperationException if the method is not supported - */ - public abstract CertPath engineGenerateCertPath(List certificates) - throws CertificateException; -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateNotYetValidException.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateNotYetValidException.java deleted file mode 100644 index ec8d46a3e..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateNotYetValidException.java +++ /dev/null @@ -1,14 +0,0 @@ - -package java.security.cert; - -public class CertificateNotYetValidException extends CertificateException -{ - public CertificateNotYetValidException() - { - } - - public CertificateNotYetValidException(String msg) - { - super(msg); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateParsingException.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateParsingException.java deleted file mode 100644 index a9f18aae0..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CertificateParsingException.java +++ /dev/null @@ -1,14 +0,0 @@ - -package java.security.cert; - -public class CertificateParsingException extends CertificateException -{ - public CertificateParsingException() - { - } - - public CertificateParsingException(String msg) - { - super(msg); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CollectionCertStoreParameters.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CollectionCertStoreParameters.java deleted file mode 100644 index 7c31e7b51..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/CollectionCertStoreParameters.java +++ /dev/null @@ -1,117 +0,0 @@ -package java.security.cert; - -import java.util.ArrayList; -import java.util.Collection; - -/** - * Parameters used as input for the Collection CertStore - * algorithm.
- *
- * This class is used to provide necessary configuration parameters - * to implementations of the Collection CertStore - * algorithm. The only parameter included in this class is the - * Collection from which the CertStore will - * retrieve certificates and CRLs.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see java.util.Collection - * @see CertStore - **/ -public class CollectionCertStoreParameters implements CertStoreParameters -{ - private Collection collection; - - /** - * Creates an instance of CollectionCertStoreParameters - * which will allow certificates and CRLs to be retrieved from the - * specified Collection. If the specified - * Collection contains an object that is not a - * Certificate or CRL, that object will be - * ignored by the Collection CertStore.
- *
- * The Collection is not copied. Instead, a - * reference is used. This allows the caller to subsequently add or - * remove Certificates or CRLs from the - * Collection, thus changing the set of - * Certificates or CRLs available to the - * Collection CertStore. The Collection CertStore - * will not modify the contents of the Collection.
- *
- * If the Collection will be modified by one thread while - * another thread is calling a method of a Collection CertStore - * that has been initialized with this Collection, the - * Collection must have fail-fast iterators. - * - * @param collection a Collection of - * Certificates and CRLs - * - * @exception NullPointerException if collection is - * null - */ - public CollectionCertStoreParameters(Collection collection) - { - if ( collection == null ) - throw new NullPointerException("collection must be non-null"); - this.collection = collection; - } - - /** - * Creates an instance of CollectionCertStoreParameters with - * the an empty Collection. - */ - public CollectionCertStoreParameters() - { - collection = new ArrayList(); - } - - /** - * Returns the Collection from which Certificates - * and CRLs are retrieved. This is not a copy of the - * Collection, it is a reference. This allows the caller to - * subsequently add or remove Certificates or - * CRLs from the Collection. - * - * @return the Collection (never null) - */ - public Collection getCollection() - { - return collection; - } - - /** - * Returns a copy of this object. Note that only a reference to the - * Collection is copied, and not the contents. - * - * @return the copy - */ - public Object clone() - { - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - /* Cannot happen */ - throw new InternalError(e.toString()); - } - } - - /** - * Returns a formatted string describing the parameters. - * - * @return a formatted string describing the parameters - */ - public String toString() - { - StringBuffer s = new StringBuffer(); - s.append("CollectionCertStoreParameters: [\n collections:\n"); - s.append( getCollection()); - s.append("\n]" ); - return s.toString(); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/LDAPCertStoreParameters.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/LDAPCertStoreParameters.java deleted file mode 100644 index 2e4669975..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/LDAPCertStoreParameters.java +++ /dev/null @@ -1,130 +0,0 @@ -package java.security.cert; - -/** - * Parameters used as input for the LDAP CertStore algorithm.
- *
- * This class is used to provide necessary configuration parameters (server - * name and port number) to implementations of the LDAP CertStore - * algorithm.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see CertStore - **/ -public class LDAPCertStoreParameters implements CertStoreParameters -{ - private static final int LDAP_DEFAULT_PORT = 389; - - /** - * the port number of the LDAP server - */ - private String serverName; - - /** - * the DNS name of the LDAP server - */ - private int port; - - /** - * Creates an instance of LDAPCertStoreParameters with the - * default parameter values (server name "localhost", port 389). - */ - public LDAPCertStoreParameters() - { - this("localhost", LDAP_DEFAULT_PORT); - } - - /** - * Creates an instance of LDAPCertStoreParameters with the - * specified server name and a default port of 389. - * - * @param serverName the DNS name of the LDAP server - * - * @exception NullPointerException if serverName is - * null - */ - public LDAPCertStoreParameters(String serverName) - { - this(serverName, LDAP_DEFAULT_PORT); - } - - /** - * Creates an instance of LDAPCertStoreParameters with the - * specified parameter values. - * - * @param serverName the DNS name of the LDAP server - * @param port the port number of the LDAP server - * - * @exception NullPointerException if serverName is - * null - */ - public LDAPCertStoreParameters(String serverName, int port) - { - if (serverName == null) - throw new NullPointerException("serverName must be non-null"); - this.serverName = serverName; - this.port = port; - } - - /** - * Returns the DNS name of the LDAP server. - * - * @return the name (not null) - */ - public String getServerName() - { - return serverName; - } - - /** - * Returns the port number of the LDAP server. - * - * @return the port number - */ - public int getPort() - { - return port; - } - - /** - * Returns a copy of this object. Changes to the copy will not affect - * the original and vice versa.
- *
- * Note: this method currently performs a shallow copy of the object - * (simply calls Object.clone()). This may be changed in a - * future revision to perform a deep copy if new parameters are added - * that should not be shared. - * - * @return the copy - */ - public Object clone() - { - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - /* Cannot happen */ - throw new InternalError(e.toString()); - } - } - - /** - * Returns a formatted string describing the parameters. - * - * @return a formatted string describing the parameters - */ - public String toString() - { - StringBuffer sb = new StringBuffer(); - sb.append("LDAPCertStoreParameters: [\n"); - sb.append(" serverName: ").append(serverName).append('\n'); - sb.append(" port: ").append(port).append('\n'); - sb.append(']'); - return sb.toString(); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXBuilderParameters.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXBuilderParameters.java deleted file mode 100644 index b4f7aceb9..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXBuilderParameters.java +++ /dev/null @@ -1,179 +0,0 @@ -package java.security.cert; - -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidParameterException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.util.Set; - -/** - * Parameters used as input for the PKIX CertPathBuilder - * algorithm.
- *
- * A PKIX CertPathBuilder uses these parameters to {@link - * CertPathBuilder#build build} a CertPath which has been - * validated according to the PKIX certification path validation algorithm.
- *
- * To instantiate a PKIXBuilderParameters object, an - * application must specify one or more most-trusted CAs as defined by - * the PKIX certification path validation algorithm. The most-trusted CA - * can be specified using one of two constructors. An application - * can call {@link #PKIXBuilderParameters(Set, CertSelector) - * PKIXBuilderParameters(Set, CertSelector)}, specifying a - * Set of TrustAnchor objects, each of which - * identifies a most-trusted CA. Alternatively, an application can call - * {@link #PKIXBuilderParameters(KeyStore, CertSelector) - * PKIXBuilderParameters(KeyStore, CertSelector)}, specifying a - * KeyStore instance containing trusted certificate entries, each - * of which will be considered as a most-trusted CA.
- *
- * In addition, an application must specify constraints on the target - * certificate that the CertPathBuilder will attempt - * to build a path to. The constraints are specified as a - * CertSelector object. These constraints should provide the - * CertPathBuilder with enough search criteria to find the target - * certificate. Minimal criteria for an X509Certificate usually - * include the subject name and/or one or more subject alternative names. - * If enough criteria is not specified, the CertPathBuilder - * may throw a CertPathBuilderException.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see CertPathBuilder - **/ -public class PKIXBuilderParameters extends PKIXParameters -{ - private int maxPathLength = 5; - - /** - * Creates an instance of PKIXBuilderParameters with - * the specified Set of most-trusted CAs. - * Each element of the set is a {@link TrustAnchor TrustAnchor}.
- *
- * Note that the Set is copied to protect against - * subsequent modifications. - * - * @param trustAnchors a Set of TrustAnchors - * @param targetConstraints a CertSelector specifying the - * constraints on the target certificate - * - * @exception InvalidAlgorithmParameterException if trustAnchors - * is empty (trustAnchors.isEmpty() == true) - * @exception NullPointerException if trustAnchors is - * null - * @exception ClassCastException if any of the elements of - * trustAnchors are not of type - * java.security.cert.TrustAnchor - */ - public PKIXBuilderParameters( - Set trustAnchors, - CertSelector targetConstraints) - throws InvalidAlgorithmParameterException - { - super( trustAnchors ); - setTargetCertConstraints( targetConstraints ); - } - - /** - * Creates an instance of PKIXBuilderParameters that - * populates the set of most-trusted CAs from the trusted - * certificate entries contained in the specified KeyStore. - * Only keystore entries that contain trusted X509Certificates - * are considered; all other certificate types are ignored. - * - * @param keystore a KeyStore from which the set of - * most-trusted CAs will be populated - * @param targetConstraints a CertSelector specifying the - * constraints on the target certificate - * - * @exception KeyStoreException if keystore has not been - * initialized - * @exception InvalidAlgorithmParameterException if keystore does - * not contain at least one trusted certificate entry - * @exception NullPointerException if keystore is - * null - */ - public PKIXBuilderParameters(KeyStore keystore, - CertSelector targetConstraints) - throws KeyStoreException, - InvalidAlgorithmParameterException - { - super( keystore ); - setTargetCertConstraints( targetConstraints ); - } - - /** - * Sets the value of the maximum number of non-self-issued intermediate - * certificates that may exist in a certification path. A certificate - * is self-issued if the DNs that appear in the subject and issuer - * fields are identical and are not empty. Note that the last certificate - * in a certification path is not an intermediate certificate, and is not - * included in this limit. Usually the last certificate is an end entity - * certificate, but it can be a CA certificate. A PKIX - * CertPathBuilder instance must not build - * paths longer than the length specified.
- *
- * A value of 0 implies that the path can only contain - * a single certificate. A value of -1 implies that the - * path length is unconstrained (i.e. there is no maximum). - * The default maximum path length, if not specified, is 5. - * Setting a value less than -1 will cause an exception to be thrown.
- *
- * If any of the CA certificates contain the - * BasicConstraintsExtension, the value of the - * pathLenConstraint field of the extension overrides - * the maximum path length parameter whenever the result is a - * certification path of smaller length. - * - * @param maxPathLength the maximum number of non-self-issued intermediate - * certificates that may exist in a certification path - * - * @exception InvalidParameterException if maxPathLength is set - * to a value less than -1 - * - * @see #getMaxPathLength - */ - public void setMaxPathLength(int maxPathLength) - { - if ( maxPathLength < -1 ) - throw new InvalidParameterException("the maximum path length parameter can not be less than -1"); - this.maxPathLength = maxPathLength; - } - - /** - * Returns the value of the maximum number of intermediate non-self-issued - * certificates that may exist in a certification path. See - * the {@link #setMaxPathLength} method for more details. - * - * @return the maximum number of non-self-issued intermediate certificates - * that may exist in a certification path, or -1 if there is no limit - * - * @see #setMaxPathLength - */ - public int getMaxPathLength() - { - return maxPathLength; - } - - /** - * Returns a formatted string describing the parameters. - * - * @return a formatted string describing the parameters - */ - public String toString() - { - StringBuffer s = new StringBuffer(); - s.append( "PKIXBuilderParameters [\n" ); - s.append( super.toString() ); - s.append( " Maximum Path Length: " ); - s.append( getMaxPathLength() ); - s.append( "\n]\n" ); - return s.toString(); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXCertPathBuilderResult.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXCertPathBuilderResult.java deleted file mode 100644 index 2ac791826..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXCertPathBuilderResult.java +++ /dev/null @@ -1,93 +0,0 @@ -package java.security.cert; - -import java.security.PublicKey; - -/** - * This class represents the successful result of the PKIX certification - * path builder algorithm. All certification paths that are built and - * returned using this algorithm are also validated according to the PKIX - * certification path validation algorithm.
- *
- * Instances of PKIXCertPathBuilderResult are returned by - * the build method of CertPathBuilder - * objects implementing the PKIX algorithm.
- *
- * All PKIXCertPathBuilderResult objects contain the - * certification path constructed by the build algorithm, the - * valid policy tree and subject public key resulting from the build - * algorithm, and a TrustAnchor describing the certification - * authority (CA) that served as a trust anchor for the certification path.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see CertPathBuilderResult - * - **/ -public class PKIXCertPathBuilderResult extends PKIXCertPathValidatorResult - implements CertPathBuilderResult -{ - private CertPath certPath; - - /** - * Creates an instance of PKIXCertPathBuilderResult - * containing the specified parameters. - * - * @param certPath the validated CertPath - * @param trustAnchor a TrustAnchor describing the CA that - * served as a trust anchor for the certification path - * @param policyTree the immutable valid policy tree, or null - * if there are no valid policies - * @param subjectPublicKey the public key of the subject - * - * @exception NullPointerException if the certPath, - * trustAnchor or subjectPublicKey parameters - * are null - */ - public PKIXCertPathBuilderResult(CertPath certPath, TrustAnchor trustAnchor, - PolicyNode policyTree, PublicKey subjectPublicKey) - { - super(trustAnchor, policyTree, subjectPublicKey); - if ( certPath == null ) - throw new NullPointerException( "certPath must be non-null" ); - this.certPath = certPath; - } - - /** - * Returns the built and validated certification path. The - * CertPath object does not include the trust anchor. - * Instead, use the {@link #getTrustAnchor() getTrustAnchor()} method to - * obtain the TrustAnchor that served as the trust anchor - * for the certification path. - * - * @return the built and validated CertPath (never - * null) - */ - public CertPath getCertPath() - { - return certPath; - } - - /** - * Return a printable representation of this - * PKIXCertPathBuilderResult. - * - * @return a String describing the contents of this - * PKIXCertPathBuilderResult - */ - public String toString() - { - StringBuffer s = new StringBuffer(); - s.append( "PKIXCertPathBuilderResult: [\n" ); - s.append( " Certification Path: ").append(getCertPath()).append('\n' ); - s.append( " Trust Anchor: ").append(getTrustAnchor()).append('\n' ); - s.append( " Policy Tree: ").append(getPolicyTree()).append('\n' ); - s.append( " Subject Public Key: ").append(getPublicKey()).append("\n]"); - return s.toString(); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXCertPathChecker.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXCertPathChecker.java deleted file mode 100644 index 14dec8060..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXCertPathChecker.java +++ /dev/null @@ -1,155 +0,0 @@ -package java.security.cert; - -import java.util.Collection; -import java.util.Set; - -/** - * An abstract class that performs one or more checks on an - * X509Certificate.
- *
- * A concrete implementation of the PKIXCertPathChecker class - * can be created to extend the PKIX certification path validation algorithm. - * For example, an implementation may check for and process a critical private - * extension of each certificate in a certification path.
- *
- * Instances of PKIXCertPathChecker are passed as parameters - * using the {@link PKIXParameters#setCertPathCheckers setCertPathCheckers} - * or {@link PKIXParameters#addCertPathChecker addCertPathChecker} methods - * of the PKIXParameters and PKIXBuilderParameters - * class. Each of the PKIXCertPathCheckers {@link #check check} - * methods will be called, in turn, for each certificate processed by a PKIX - * CertPathValidator or CertPathBuilder - * implementation.
- *
- * A PKIXCertPathChecker may be called multiple times on - * successive certificates in a certification path. Concrete subclasses - * are expected to maintain any internal state that may be necessary to - * check successive certificates. The {@link #init init} method is used - * to initialize the internal state of the checker so that the certificates - * of a new certification path may be checked. A stateful implementation - * must override the {@link #clone clone} method if necessary in - * order to allow a PKIX CertPathBuilder to efficiently - * backtrack and try other paths. In these situations, the - * CertPathBuilder is able to restore prior path validation - * states by restoring the cloned PKIXCertPathCheckers.
- *
- * The order in which the certificates are presented to the - * PKIXCertPathChecker may be either in the forward direction - * (from target to most-trusted CA) or in the reverse direction (from - * most-trusted CA to target). A PKIXCertPathChecker implementation - * must support reverse checking (the ability to perform its checks when - * it is presented with certificates in the reverse direction) and may - * support forward checking (the ability to perform its checks when it is - * presented with certificates in the forward direction). The - * {@link #isForwardCheckingSupported isForwardCheckingSupported} method - * indicates whether forward checking is supported.
- *
- * Additional input parameters required for executing the check may be - * specified through constructors of concrete implementations of this class.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see PKIXParameters - * @see PKIXBuilderParameters - **/ -public abstract class PKIXCertPathChecker implements Cloneable -{ - - /** - * Default constructor. - */ - protected PKIXCertPathChecker() {} - - /** - * Initializes the internal state of this PKIXCertPathChecker. - *

- * The forward flag specifies the order that - * certificates will be passed to the {@link #check check} method - * (forward or reverse). A PKIXCertPathChecker must - * support reverse checking and may support forward checking. - * - * @param forward the order that certificates are presented to - * the check method. If true, certificates - * are presented from target to most-trusted CA (forward); if - * false, from most-trusted CA to target (reverse). - * @exception CertPathValidatorException if this - * PKIXCertPathChecker is unable to check certificates in - * the specified order; it should never be thrown if the forward flag - * is false since reverse checking must be supported - */ - public abstract void init(boolean forward) - throws CertPathValidatorException; - - /** - * Indicates if forward checking is supported. Forward checking refers - * to the ability of the PKIXCertPathChecker to perform - * its checks when certificates are presented to the check - * method in the forward direction (from target to most-trusted CA). - * - * @return true if forward checking is supported, - * false otherwise - */ - public abstract boolean isForwardCheckingSupported(); - - /** - * Returns an immutable Set of X.509 certificate extensions - * that this PKIXCertPathChecker supports (i.e. recognizes, is - * able to process), or null if no extensions are supported. - *

- * Each element of the set is a String representing the - * Object Identifier (OID) of the X.509 extension that is supported. - * The OID is represented by a set of nonnegative integers separated by - * periods. - *

- * All X.509 certificate extensions that a PKIXCertPathChecker - * might possibly be able to process should be included in the set. - * - * @return an immutable Set of X.509 extension OIDs (in - * String format) supported by this - * PKIXCertPathChecker, or null if no - * extensions are supported - */ - public abstract Set getSupportedExtensions(); - - /** - * Performs the check(s) on the specified certificate using its internal - * state and removes any critical extensions that it processes from the - * specified collection of OID strings that represent the unresolved - * critical extensions. The certificates are presented in the order - * specified by the init method. - * - * @param cert the Certificate to be checked - * @param unresolvedCritExts a Collection of OID strings - * representing the current set of unresolved critical extensions - * @exception CertPathValidatorException if the specified certificate does - * not pass the check - */ - public abstract void check( - Certificate cert, - Collection unresolvedCritExts) - throws CertPathValidatorException; - - /** - * Returns a clone of this object. Calls the Object.clone() - * method. - * All subclasses which maintain state must support and - * override this method, if necessary. - * - * @return a copy of this PKIXCertPathChecker - */ - public Object clone() - { - try { - return super.clone(); - } catch ( CloneNotSupportedException ex ) { - /* Cannot happen */ - throw new InternalError( ex.toString() ); - } - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXCertPathValidatorResult.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXCertPathValidatorResult.java deleted file mode 100644 index 8ffa25555..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXCertPathValidatorResult.java +++ /dev/null @@ -1,136 +0,0 @@ -package java.security.cert; - -import java.security.PublicKey; - -/** - * This class represents the successful result of the PKIX certification - * path validation algorithm.
- *
- * Instances of PKIXCertPathValidatorResult are returned by the - * {@link CertPathValidator#validate validate} method of - * CertPathValidator objects implementing the PKIX algorithm.
- *
- * All PKIXCertPathValidatorResult objects contain the - * valid policy tree and subject public key resulting from the - * validation algorithm, as well as a TrustAnchor describing - * the certification authority (CA) that served as a trust anchor for the - * certification path.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see CertPathValidatorResult - **/ -public class PKIXCertPathValidatorResult implements CertPathValidatorResult -{ - private TrustAnchor trustAnchor; - private PolicyNode policyTree; - private PublicKey subjectPublicKey; - - /** - * Creates an instance of PKIXCertPathValidatorResult - * containing the specified parameters. - * - * @param trustAnchor a TrustAnchor describing the CA that - * served as a trust anchor for the certification path - * @param policyTree the immutable valid policy tree, or null - * if there are no valid policies - * @param subjectPublicKey the public key of the subject - * - * @exception NullPointerException if the subjectPublicKey or - * trustAnchor parameters are null - */ - public PKIXCertPathValidatorResult(TrustAnchor trustAnchor, - PolicyNode policyTree, - PublicKey subjectPublicKey) - { - if ( subjectPublicKey == null ) - throw new NullPointerException( "subjectPublicKey must be non-null" ); - if ( trustAnchor == null ) - throw new NullPointerException( "trustAnchor must be non-null" ); - - this.trustAnchor = trustAnchor; - this.policyTree = policyTree; - this.subjectPublicKey = subjectPublicKey; - } - - /** - * Returns the TrustAnchor describing the CA that served - * as a trust anchor for the certification path. - * - * @return the TrustAnchor (never null) - */ - public TrustAnchor getTrustAnchor() - { - return trustAnchor; - } - - /** - * Returns the root node of the valid policy tree resulting from the - * PKIX certification path validation algorithm. The - * PolicyNode object that is returned and any objects that - * it returns through public methods are immutable.
- *
- * Most applications will not need to examine the valid policy tree. - * They can achieve their policy processing goals by setting the - * policy-related parameters in PKIXParameters. However, more - * sophisticated applications, especially those that process policy - * qualifiers, may need to traverse the valid policy tree using the - * {@link PolicyNode#getParent PolicyNode.getParent} and - * {@link PolicyNode#getChildren PolicyNode.getChildren} methods. - * - * @return the root node of the valid policy tree, or null - * if there are no valid policies - */ - public PolicyNode getPolicyTree() - { - return policyTree; - } - - /** - * Returns the public key of the subject (target) of the certification - * path, including any inherited public key parameters if applicable. - * - * @return the public key of the subject (never null) - */ - public PublicKey getPublicKey() - { - return subjectPublicKey; - } - - /** - * Returns a copy of this object. - * - * @return the copy - */ - public Object clone() - { - try { - return super.clone(); - } catch ( CloneNotSupportedException ex ) { - throw new InternalError( ex.toString() ); - } - } - - /** - * Return a printable representation of this - * PKIXCertPathValidatorResult. - * - * @return a String describing the contents of this - * PKIXCertPathValidatorResult - */ - public String toString() - { - StringBuffer s = new StringBuffer(); - s.append( "PKIXCertPathValidatorResult: [ \n" ); - s.append( " Trust Anchor: ").append(getTrustAnchor()).append('\n' ); - s.append( " Policy Tree: ").append(getPolicyTree()).append('\n' ); - s.append( " Subject Public Key: ").append(getPublicKey()).append("\n]" ); - return s.toString(); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXParameters.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXParameters.java deleted file mode 100644 index 3c55d7e49..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PKIXParameters.java +++ /dev/null @@ -1,770 +0,0 @@ -package java.security.cert; - -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -/** - * Parameters used as input for the PKIX CertPathValidator algorithm.
- *
- * A PKIX CertPathValidator uses these parameters to validate a - * CertPath according to the PKIX certification path validation - * algorithm.
- *
- * To instantiate a PKIXParameters object, an application must specify - * one or more most-trusted CAs as defined by the PKIX certification - * path validation algorithm. The most-trusted CAs can be specified - * using one of two constructors. An application can call - * {@link #PKIXParameters(Set)}, specifying a Set of TrustAnchor objects, each - * of which identify a most-trusted CA. Alternatively, an application - * can call {@link #PKIXParameters(KeyStore)}, specifying a KeyStore instance - * containing trusted certificate entries, each of which will be - * considered as a most-trusted CA.
- *
- * Once a PKIXParameters object has been created, other parameters can - * be specified (by calling {@link #setInitialPolicies} or {@link #setDate}, for - * instance) and then the PKIXParameters is passed along with the - * CertPath to be validated to {@link CertPathValidator#validate}.
- *
- * Any parameter that is not set (or is set to null) will be set to the - * default value for that parameter. The default value for the date - * parameter is null, which indicates the current time when the path is - * validated. The default for the remaining parameters is the least - * constrained.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are - * not thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see CertPathValidator - **/ -public class PKIXParameters implements CertPathParameters { - private Set trustAnchors; - private Set initialPolicies = new HashSet(); - private List certStores = new ArrayList(); - private CertSelector certSelector; - private List certPathCheckers = new ArrayList(); - private boolean revocationEnabled = true; - private boolean explicitPolicyRequired = false; - private boolean policyMappingInhibited = false; - private boolean anyPolicyInhibited = false; - private boolean policyQualifiersRejected = true; - private Date date; - private String sigProvider; - - /** - * Creates an instance of PKIXParameters with the specified - * Set of most-trusted CAs. Each element of the set is a - * TrustAnchor.
- *
- * Note that the Set is copied to protect against subsequent - * modifications. - * - * @param trustAnchors a Set of TrustAnchors - * - * @exception InvalidAlgorithmParameterException if the - * specified Set is empty (trustAnchors.isEmpty() == true) - * @exception NullPointerException if the specified Set is null - * @exception ClassCastException if any of the elements in the - * Set are not of type - * java.security.cert.TrustAnchor - **/ - public PKIXParameters(Set trustAnchors) - throws InvalidAlgorithmParameterException - { - setTrustAnchors( trustAnchors ); - } - - /** - * Creates an instance of PKIXParameters that populates the - * set of most-trusted CAs from the trusted certificate - * entries contained in the specified KeyStore. Only keystore - * entries that contain trusted X509Certificates are - * considered; all other certificate types are ignored. - * - * @param keystore a KeyStore from which the set of - * most-trusted CAs will be populated - * - * @exception KeyStoreException if the keystore has not been - * initialized - * @exception InvalidAlgorithmParameterException if the keystore - * does not contain at least one trusted certificate entry - * @exception NullPointerException if the keystore is null - **/ - public PKIXParameters(KeyStore keystore) - throws KeyStoreException, - InvalidAlgorithmParameterException - { - if ( keystore == null ) - throw new NullPointerException( "the keystore parameter must be non-null" ); - - Set trustAnchors = new HashSet(); - String alias; - Certificate cert; - Enumeration enum = keystore.aliases(); - while ( enum.hasMoreElements() ) { - alias = (String)enum.nextElement(); - if ( keystore.isCertificateEntry( alias ) ) { - cert = keystore.getCertificate( alias ); - if ( cert instanceof X509Certificate ) - trustAnchors.add( new TrustAnchor( (X509Certificate)cert, null ) ); - } - } - setTrustAnchors( trustAnchors ); - } - - /** - * Returns an immutable Set of the most-trusted CAs. - * - * @return an immutable Set of - * TrustAnchors (never null) - * - * @see #setTrustAnchors - **/ - public Set getTrustAnchors() - { - return Collections.unmodifiableSet(trustAnchors); - } - - /** - * Sets the Set of most-trusted CAs.
- *
- * Note that the Set is copied to protect against subsequent - * modifications.
- *
- * @param trustAnchors a Set of TrustAnchors - * - * @exception InvalidAlgorithmParameterException if the specified Set is empty (trustAnchors.isEmpty() == true) - * @exception NullPointerException if the specified Set is null - * @exception ClassCastException if any of the elements in - * the set are not of type java.security.cert.TrustAnchor - * - * @see #getTrustAnchors - **/ - public void setTrustAnchors(Set trustAnchors) - throws InvalidAlgorithmParameterException - { - if ( trustAnchors == null ) - throw new NullPointerException("the trustAnchors parameter must be non-null"); - if ( trustAnchors.isEmpty() ) - throw new InvalidAlgorithmParameterException("the trustAnchors parameter must be non-empty"); - - Iterator iter = trustAnchors.iterator(); - TrustAnchor obj; - this.trustAnchors = new HashSet(); - while( iter.hasNext() ) { - obj = (TrustAnchor)iter.next(); - if ( obj != null ) { - this .trustAnchors.add( obj ); - } - } - } - - /** - * Returns an immutable Set of initial policy identifiers (OID - * strings), indicating that any one of these policies would - * be acceptable to the certificate user for the purposes of - * certification path processing. The default return value is - * an empty Set, which is interpreted as meaning that any - * policy would be acceptable. - * - * @return an immutable Set of initial policy - * OIDs in String format, or an empty Set (implying any policy - * is acceptable). Never returns null. - * - * @see #setInitialPolicies(java.util.Set) - **/ - public Set getInitialPolicies() - { - Set returnSet = initialPolicies; - if ( initialPolicies == null ) - returnSet = new HashSet(); - - return Collections.unmodifiableSet( returnSet ); - } - - /** - * Sets the Set of initial policy identifiers (OID strings), - * indicating that any one of these policies would be - * acceptable to the certificate user for the purposes of - * certification path processing. By default, any policy is - * acceptable (i.e. all policies), so a user that wants to - * allow any policy as acceptable does not need to call this - * method, or can call it with an empty Set (or null).
- *
- * Note that the Set is copied to protect against subsequent - * modifications.
- *
- * @param initialPolicies a Set of initial policy OIDs in String format (or null) - * - * @exception ClassCastException if any of the elements in the - * set are not of type String - * - * @see #getInitialPolicies() - **/ - public void setInitialPolicies(Set initialPolicies) - { - if ( initialPolicies == null || initialPolicies.isEmpty() ) - { - this.initialPolicies = null; - } - else - { - Iterator iter = initialPolicies.iterator(); - this.initialPolicies = new HashSet(); - String obj; - while ( iter.hasNext() ) - { - obj = (String)iter.next(); - if ( obj != null ) { - this.initialPolicies.add( obj ); - } - } - } - } - - /** - * Sets the list of CertStores to be used in finding - * certificates and CRLs. May be null, in which case no - * CertStores will be used. The first CertStores in the list - * may be preferred to those that appear later.
- *
- * Note that the List is copied to protect against subsequent - * modifications.
- *
- * @param stores a List of CertStores (or null) - * - * @exception ClassCastException if any of the elements in the - * list are not of type java.security.cert.CertStore - * - * @see #getCertStores() - **/ - public void setCertStores(List stores) - { - certStores = new ArrayList(); - if ( stores != null && ! stores.isEmpty() ) - { - Iterator iter = stores.iterator(); - CertStore obj; - while ( iter.hasNext() ) - { - obj = (CertStore)iter.next(); - if ( obj != null ) - { - certStores.add( obj ); - } - } - } - } - - /** - * Adds a CertStore to the end of the list of CertStores used - * in finding certificates and CRLs. - * - * @param store the CertStore to add. If - * nullnull) - * - * @see #setCertStores(java.util.List) - **/ - public List getCertStores() - { - return Collections.unmodifiableList(certStores); - } - - /** - * Sets the RevocationEnabled flag. If this flag is true, the default - * revocation checking mechanism of the underlying PKIX service provider - * will be used. If this flag is false, the default revocation checking - * mechanism will be disabled (not used).
- *
- * When a PKIXParameters object is created, this flag is set - * to true. This setting reflects the most common strategy for checking - * revocation, since each service provider must support revocation - * checking to be PKIX compliant. Sophisticated applications should set - * this flag to false when it is not practical to use a PKIX service - * provider's default revocation checking mechanism or when an alternative - * revocation checking mechanism is to be substituted (by also calling the - * {@link #addCertPathChecker addCertPathChecker} or {@link - * #setCertPathCheckers setCertPathCheckers} methods). - * - * @param val the new value of the RevocationEnabled flag - **/ - public void setRevocationEnabled(boolean val) - { - revocationEnabled = val; - } - - /** - * Checks the RevocationEnabled flag. If this flag is true, - * the default revocation checking mechanism of the underlying - * PKIX service provider will be used. If this flag is false, - * the default revocation checking mechanism will be disabled - * (not used). See the setRevocationEnabled method for more - * details on setting the value of this flag. - * - * @return the current value of the RevocationEnabled flag - **/ - public boolean isRevocationEnabled() - { - return revocationEnabled; - } - - /** - * Sets the ExplicitPolicyRequired flag. If this flag is true, - * an acceptable policy needs to be explicitly identified in - * every certificate. By default, the ExplicitPolicyRequired - * flag is false. - * - * @param val true if explicit policy is to be required, false - * otherwise - **/ - public void setExplicitPolicyRequired(boolean val) - { - explicitPolicyRequired = val; - } - - /** - * Checks if explicit policy is required. If this flag is - * true, an acceptable policy needs to be explicitly - * identified in every certificate. By default, the - * ExplicitPolicyRequired flag is false. - * - * @return true if explicit policy is required, false otherwise - **/ - public boolean isExplicitPolicyRequired() - { - return explicitPolicyRequired; - } - - /** - * Sets the PolicyMappingInhibited flag. If this flag is true, - * policy mapping is inhibited. By default, policy mapping is - * not inhibited (the flag is false). - * - * @param val true if policy mapping is to be inhibited, false otherwise - **/ - public void setPolicyMappingInhibited(boolean val) - { - policyMappingInhibited = val; - } - - /** - * Checks if policy mapping is inhibited. If this flag is - * true, policy mapping is inhibited. By default, policy - * mapping is not inhibited (the flag is false). - * - * @return true if policy mapping is inhibited, false otherwise - **/ - public boolean isPolicyMappingInhibited() - { - return policyMappingInhibited; - } - - /** - * Sets state to determine if the any policy OID should be - * processed if it is included in a certificate. By default, - * the any policy OID is not inhibited ({@link #isAnyPolicyInhibited()} - * returns false). - * - * @return val - true if the any policy OID is to be inhibited, false otherwise - **/ - public void setAnyPolicyInhibited(boolean val) - { - anyPolicyInhibited = val; - } - - /** - * Checks whether the any policy OID should be processed if it - * is included in a certificate. - * - * @return true if the any policy OID is inhibited, false otherwise - **/ - public boolean isAnyPolicyInhibited() - { - return anyPolicyInhibited; - } - - /** - * Sets the PolicyQualifiersRejected flag. If this flag is - * true, certificates that include policy qualifiers in a - * certificate policies extension that is marked critical are - * rejected. If the flag is false, certificates are not - * rejected on this basis.
- *
- * When a PKIXParameters object is created, this flag is set - * to true. This setting reflects the most common (and - * simplest) strategy for processing policy - * qualifiers. Applications that want to use a more - * sophisticated policy must set this flag to false.
- *
- * Note that the PKIX certification path validation algorithm - * specifies that any policy qualifier in a certificate - * policies extension that is marked critical must be - * processed and validated. Otherwise the certification path - * must be rejected. If the policyQualifiersRejected flag is - * set to false, it is up to the application to validate all - * policy qualifiers in this manner in order to be PKIX - * compliant. - * - * @param qualifiersRejected the new value of the PolicyQualifiersRejected flag - * - * @see #getPolicyQualifiersRejected() - * @see PolicyQualifierInfo - **/ - public void setPolicyQualifiersRejected(boolean qualifiersRejected) - { - policyQualifiersRejected = qualifiersRejected; - } - - /** - * Gets the PolicyQualifiersRejected flag. If this flag is - * true, certificates that include policy qualifiers in a - * certificate policies extension that is marked critical are - * rejected. If the flag is false, certificates are not - * rejected on this basis.
- *
- * When a PKIXParameters object is created, this flag is set to - * true. This setting reflects the most common (and simplest) - * strategy for processing policy qualifiers. Applications that - * want to use a more sophisticated policy must set this flag - * to false. - * - * @return the current value of the PolicyQualifiersRejected flag - * - * @see #setPolicyQualifiersRejected(boolean) - **/ - public boolean getPolicyQualifiersRejected() - { - return policyQualifiersRejected; - } - - /** - * Returns the time for which the validity of the - * certification path should be determined. If null, the - * current time is used.
- *
- * Note that the Date returned is copied to protect against - * subsequent modifications. - * - * @return the Date, or null if not set - * - * @see #setDate(java.util.Date) - **/ - public Date getDate() - { - if ( date == null ) - return null; - - return new Date( date.getTime() ); - } - - /** - * Sets the time for which the validity of the certification - * path should be determined. If null, the current time is - * used.
- *
- * Note that the Date supplied here is copied to protect - * against subsequent modifications. - * - * @param date the Date, or null for the current time - * - * @see #getDate() - **/ - public void setDate(Date date) - { - if ( date == null ) - this.date = null; - else - this.date = new Date( date.getTime() ); - } - - /** - * Sets a List of additional certification path checkers. If - * the specified List contains an object that is not a - * PKIXCertPathChecker, it is ignored.
- *
- * Each PKIXCertPathChecker specified implements additional - * checks on a certificate. Typically, these are checks to - * process and verify private extensions contained in - * certificates. Each PKIXCertPathChecker should be - * instantiated with any initialization parameters needed to - * execute the check.
- *
- * This method allows sophisticated applications to extend a - * PKIX CertPathValidator or CertPathBuilder. Each of the - * specified PKIXCertPathCheckers will be called, in turn, by - * a PKIX CertPathValidator or CertPathBuilder for each - * certificate processed or validated.
- *
- * Regardless of whether these additional PKIXCertPathCheckers - * are set, a PKIX CertPathValidator or CertPathBuilder must - * perform all of the required PKIX checks on each - * certificate. The one exception to this rule is if the - * RevocationEnabled flag is set to false (see the - * {@link #setRevocationEnabled(boolean) setRevocationEnabled} method).
- *
- * Note that the List supplied here is copied and each - * PKIXCertPathChecker in the list is cloned to protect against - * subsequent modifications. - * - * @param checkers a List of PKIXCertPathCheckers. May be - * null, in which case no additional checkers will be used. - * @exception ClassCastException if any of the elements in the - * list are not of type - * java.security.cert.PKIXCertPathChecker - * @see #getCertPathCheckers() - **/ - public void setCertPathCheckers(List checkers) - { - certPathCheckers = new ArrayList(); - if ( checkers == null ) - return; - Iterator iter = checkers.iterator(); - while ( iter.hasNext() ) - certPathCheckers.add( (PKIXCertPathChecker)((PKIXCertPathChecker)iter.next()).clone() ); - } - - /** - * Returns the List of certification path checkers. The - * returned List is immutable, and each PKIXCertPathChecker in - * the List is cloned to protect against subsequent - * modifications. - * - * @return an immutable List of PKIXCertPathCheckers (may be empty, but not null) - * - * @see #setCertPathCheckers(java.util.List) - **/ - public List getCertPathCheckers() - { - List checkers = new ArrayList(); - Iterator iter = certPathCheckers.iterator(); - while ( iter.hasNext() ) - { - checkers.add( (PKIXCertPathChecker)((PKIXCertPathChecker)iter.next()).clone() ); - } - return Collections.unmodifiableList(checkers); - } - - /** - * Adds a PKIXCertPathChecker to the list of certification - * path checkers. See the {@link #setCertPathCheckers} method for more - * details.
- *
- * Note that the PKIXCertPathChecker is cloned to protect - * against subsequent modifications. - * - * @param checker a PKIXCertPathChecker to add - * to the list of checks. If null, the checker is - * ignored (not added to list). - **/ - public void addCertPathChecker( PKIXCertPathChecker checker ) - { - if ( checker != null ) - { - certPathCheckers.add( checker.clone() ); - } - } - - /** - * Returns the signature provider's name, or null if not set. - * - * @return the signature provider's name (or null) - * - * @see #setSigProvider(java.lang.String) - **/ - public String getSigProvider() - { - return sigProvider; - } - - /** - * Sets the signature provider's name. The specified provider - * will be preferred when creating Signature objects. If null - * or not set, the first provider found supporting the - * algorithm will be used. - * - * @param sigProvider the signature provider's name (or null) - * - * @see #getSigProvider() - **/ - public void setSigProvider(String sigProvider) - { - this.sigProvider = sigProvider; - } - - /** - * Returns the required constraints on the target - * certificate. The constraints are returned as an instance of - * CertSelector. If null, no constraints are defined.
- *
- * Note that the CertSelector returned is cloned to protect - * against subsequent modifications. - * - * @return a CertSelector specifying the constraints on the target certificate (or null) - * - * @see #setTargetCertConstraints(java.security.cert.CertSelector) - **/ - public CertSelector getTargetCertConstraints() - { - if ( certSelector == null ) - return null; - - return (CertSelector)certSelector.clone(); - } - - /** - * Sets the required constraints on the target - * certificate. The constraints are specified as an instance - * of CertSelector. If null, no constraints are defined.
- *
- * Note that the CertSelector specified is cloned to protect - * against subsequent modifications. - * - * @param selector a CertSelector specifying the constraints - * on the target certificate (or null) - * - * @see #getTargetCertConstraints() - **/ - public void setTargetCertConstraints(CertSelector selector) - { - if ( selector == null ) - certSelector = null; - else - certSelector = (CertSelector)selector.clone(); - } - - /** - * Makes a copy of this PKIXParameters object. Changes to the - * copy will not affect the original and vice versa. - * - * @return a copy of this PKIXParameters object - **/ - public Object clone() - { - try { - PKIXParameters obj = (PKIXParameters)super.clone(); - obj.certStores = new ArrayList( certStores ); - Iterator iter = certPathCheckers.iterator(); - obj.certPathCheckers = new ArrayList(); - while ( iter.hasNext() ) - { - obj.certPathCheckers.add( ((PKIXCertPathChecker)iter.next()).clone() ); - } - if ( initialPolicies != null ) - { - obj.initialPolicies = new HashSet( initialPolicies ); - } - if ( trustAnchors != null ) - { - obj.trustAnchors = new HashSet( trustAnchors ); - } - if ( certSelector != null ) - { - obj.certSelector = (CertSelector)certSelector.clone(); - } - return obj; - } catch ( CloneNotSupportedException ex ) { - throw new InternalError(); - } - } - - /** - * Returns a formatted string describing the parameters. - * - * @return a formatted string describing the parameters. - **/ - public String toString() - { - StringBuffer s = new StringBuffer(); - s.append("[\n"); - if ( trustAnchors != null ) - { - s.append(" Trust Anchors: ").append(trustAnchors).append('\n'); - } - if ( initialPolicies != null ) - { - if ( initialPolicies.isEmpty() ) - { - s.append(" Initial Policy OIDs: any\n" ); - } - else - { - s.append(" Initial Policy OIDs: [").append(initialPolicies).append("]\n"); - } - } - s.append(" Validity Date: "); - if ( date != null ) - s.append(date); - else - s.append("null"); - s.append('\n'); - - s.append(" Signature Provider: "); - if ( sigProvider != null ) - s.append(sigProvider); - else - s.append("null"); - s.append('\n'); - - s.append(" Default Revocation Enabled: "); - s.append(revocationEnabled); - s.append('\n' ); - - s.append(" Explicit Policy Required: "); - s.append(explicitPolicyRequired); - s.append('\n'); - - s.append(" Policy Mapping Inhibited: "); - s.append(policyMappingInhibited); - s.append('\n'); - - s.append(" Any Policy Inhibited: "); - s.append(anyPolicyInhibited); - s.append('\n'); - - s.append(" Policy Qualifiers Rejected: "); - s.append(policyQualifiersRejected); - s.append('\n'); - - s.append(" Target Cert Constraints: "); - s.append(certSelector); - s.append('\n'); - - s.append(" Certification Path Checkers: ["); - s.append(certPathCheckers); - s.append( "}\n"); - - s.append(" CertStores: ["); - s.append(certStores); - s.append("}\n"); - - s.append("]\n"); - - return s.toString(); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PolicyNode.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PolicyNode.java deleted file mode 100644 index cdae45205..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PolicyNode.java +++ /dev/null @@ -1,107 +0,0 @@ -package java.security.cert; - -import java.util.Iterator; -import java.util.Set; - -/** - * An immutable valid policy tree node as defined by the PKIX certification - * path validation algorithm.
- *
- * One of the outputs of the PKIX certification path validation - * algorithm is a valid policy tree, which includes the policies that - * were determined to be valid, how this determination was reached, - * and any policy qualifiers encountered. This tree is of depth - * n, where n is the length of the certification - * path that has been validated.
- *
- * Most applications will not need to examine the valid policy tree. - * They can achieve their policy processing goals by setting the - * policy-related parameters in PKIXParameters. However, - * the valid policy tree is available for more sophisticated applications, - * especially those that process policy qualifiers.
- *
- * {@link PKIXCertPathValidatorResult#getPolicyTree() - * PKIXCertPathValidatorResult.getPolicyTree} returns the root node of the - * valid policy tree. The tree can be traversed using the - * {@link #getChildren getChildren} and {@link #getParent getParent} methods. - * Data about a particular node can be retrieved using other methods of - * PolicyNode.
- *
- * Concurrent Access
- *
- * All PolicyNode objects must be immutable and - * thread-safe. Multiple threads may concurrently invoke the methods defined - * in this class on a single PolicyNode object (or more than one) - * with no ill effects. This stipulation applies to all public fields and - * methods of this class and any added or overridden by subclasses. - **/ -public interface PolicyNode -{ - - /** - * Returns the parent of this node, or null if this is the - * root node. - * - * @return the parent of this node, or null if this is the - * root node - */ - public PolicyNode getParent(); - - /** - * Returns an iterator over the children of this node. Any attempts to - * modify the children of this node through the - * Iterator's remove method must throw an - * UnsupportedOperationException. - * - * @return an iterator over the children of this node - */ - public Iterator getChildren(); - - /** - * Returns the depth of this node in the valid policy tree. - * - * @return the depth of this node (0 for the root node, 1 for its - * children, and so on) - */ - public int getDepth(); - - /** - * Returns the valid policy represented by this node. - * - * @return the String OID of the valid policy - * represented by this node, or the special value "any-policy". For - * the root node, this method always returns the special value "any-policy". - */ - public String getValidPolicy(); - - /** - * Returns the set of policy qualifiers associated with the - * valid policy represented by this node. - * - * @return an immutable Set of - * PolicyQualifierInfos. For the root node, this - * is always an empty Set. - */ - public Set getPolicyQualifiers(); - - /** - * Returns the set of expected policies that would satisfy this - * node's valid policy in the next certificate to be processed. - * - * @return an immutable Set of expected policy - * String OIDs, or an immutable Set with - * the single special value "any-policy". For the root node, this method - * always returns a Set with the single value "any-policy". - */ - public Set getExpectedPolicies(); - - /** - * Returns the criticality indicator of the certificate policy extension - * in the most recently processed certificate. - * - * @return true if extension marked critical, - * false otherwise. For the root node, false - * is always returned. - */ - public boolean isCritical(); -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PolicyQualifierInfo.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PolicyQualifierInfo.java deleted file mode 100644 index a17f49bf4..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/PolicyQualifierInfo.java +++ /dev/null @@ -1,196 +0,0 @@ -package java.security.cert; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Object; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.DEROutputStream; -import org.spongycastle.asn1.util.ASN1Dump; - -/** - * An immutable policy qualifier represented by the ASN.1 PolicyQualifierInfo - * structure.
- *
- * The ASN.1 definition is as follows:
- *
- * - *

- *    PolicyQualifierInfo ::= SEQUENCE {
- *         policyQualifierId       PolicyQualifierId,
- *         qualifier               ANY DEFINED BY policyQualifierId }
- * 
- * - *
- *
- * A certificate policies extension, if present in an X.509 version 3 - * certificate, contains a sequence of one or more policy information terms, - * each of which consists of an object identifier (OID) and optional qualifiers. - * In an end-entity certificate, these policy information terms indicate the - * policy under which the certificate has been issued and the purposes for which - * the certificate may be used. In a CA certificate, these policy information - * terms limit the set of policies for certification paths which include this - * certificate.
- *
- * A Set of PolicyQualifierInfo objects are - * returned by the - * {@link PolicyNode#getPolicyQualifiers PolicyNode.getPolicyQualifiers} method. - * This allows applications with specific policy requirements to process and - * validate each policy qualifier. Applications that need to process policy - * qualifiers should explicitly set the policyQualifiersRejected - * flag to false (by calling the - * {@link PKIXParameters#setPolicyQualifiersRejected - * PKIXParameters.setPolicyQualifiersRejected} method) before validating a - * certification path.
- *
- * Note that the PKIX certification path validation algorithm specifies that any - * policy qualifier in a certificate policies extension that is marked critical - * must be processed and validated. Otherwise the certification path must be - * rejected. If the policyQualifiersRejected flag is set to - * false, it is up to the application to validate all policy qualifiers in this - * manner in order to be PKIX compliant.
- *
- * Concurrent Access
- *
- * All PolicyQualifierInfo objects must be immutable and - * thread-safe. That is, multiple threads may concurrently invoke the methods - * defined in this class on a single PolicyQualifierInfo object - * (or more than one) with no ill effects. Requiring - * PolicyQualifierInfo objects to be immutable and thread-safe - * allows them to be passed around to various pieces of code without worrying - * about coordinating access.
- *
- * Uses {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Sequence ASN1Sequence}, - * {@link org.spongycastle.asn1.ASN1ObjectIdentifier ASN1ObjectIdentifier}, - * {@link org.spongycastle.asn1.DEROutputStream DEROutputStream}, - * {@link org.spongycastle.asn1.ASN1Object ASN1Object} - */ -public final class PolicyQualifierInfo -{ - private String id; - - private byte[] encoded; - - private byte[] qualifier; - - /** - * Creates an instance of PolicyQualifierInfo from the - * encoded bytes. The encoded byte array is copied on construction.
- *
- * Uses {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Sequence ASN1Sequence}, - * {@link org.spongycastle.asn1.ASN1ObjectIdentifier ASN1ObjectIdentifier} and - * {@link org.spongycastle.asn1.DEROutputStream DEROutputStream} - * - * @param encoded - * a byte array containing the qualifier in DER encoding - * - * @exception IOException - * thrown if the byte array does not represent a valid and - * parsable policy qualifier - */ - public PolicyQualifierInfo(byte[] encoded) throws IOException - { - this.encoded = (byte[])encoded.clone(); - try - { - ByteArrayInputStream inStream = new ByteArrayInputStream( - this.encoded); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Sequence obj = (ASN1Sequence)derInStream.readObject(); - id = ((ASN1ObjectIdentifier)obj.getObjectAt(0)).getId(); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - DEROutputStream derOutStream = new DEROutputStream(outStream); - - derOutStream.writeObject(obj.getObjectAt(1)); - derOutStream.close(); - - qualifier = outStream.toByteArray(); - } - catch (Exception ex) - { - throw new IOException("parsing exception : " + ex.toString()); - } - } - - /** - * Returns the policyQualifierId field of this - * PolicyQualifierInfo. The policyQualifierId - * is an Object Identifier (OID) represented by a set of nonnegative - * integers separated by periods. - * - * @return the OID (never null) - */ - public String getPolicyQualifierId() - { - return id; - } - - /** - * Returns the ASN.1 DER encoded form of this - * PolicyQualifierInfo. - * - * @return the ASN.1 DER encoded bytes (never null). Note - * that a copy is returned, so the data is cloned each time this - * method is called. - */ - public byte[] getEncoded() - { - return (byte[])encoded.clone(); - } - - /** - * Returns the ASN.1 DER encoded form of the qualifier field - * of this PolicyQualifierInfo. - * - * @return the ASN.1 DER encoded bytes of the qualifier - * field. Note that a copy is returned, so the data is cloned each - * time this method is called. - */ - public byte[] getPolicyQualifier() - { - if (qualifier == null) - { - return null; - } - - return (byte[])qualifier.clone(); - } - - /** - * Return a printable representation of this - * PolicyQualifierInfo.
- *
- * Uses {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Object ASN1Object} - * - * @return a String describing the contents of this - * PolicyQualifierInfo - */ - public String toString() - { - StringBuffer s = new StringBuffer(); - s.append("PolicyQualifierInfo: [\n"); - s.append("qualifierID: ").append(id).append('\n'); - try - { - ByteArrayInputStream inStream = new ByteArrayInputStream(qualifier); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); - s - .append(" qualifier:\n").append(ASN1Dump.dumpAsString(derObject)) - .append('\n'); - } - catch (IOException ex) - { - s.append(ex.getMessage()); - } - s.append("qualifier: ").append(id).append('\n'); - s.append(']'); - return s.toString(); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/TrustAnchor.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/TrustAnchor.java deleted file mode 100644 index f139a742c..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/TrustAnchor.java +++ /dev/null @@ -1,293 +0,0 @@ -package java.security.cert; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.security.PublicKey; -import java.security.cert.X509Certificate; - -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Object; -import org.spongycastle.asn1.ASN1Sequence; - -/** - * A trust anchor or most-trusted Certification Authority (CA).
- *
- * This class represents a "most-trusted CA", which is used as a trust anchor - * for validating X.509 certification paths. A most-trusted CA includes the - * public key of the CA, the CA's name, and any constraints upon the set of - * paths which may be validated using this key. These parameters can be - * specified in the form of a trusted X509Certificate or as individual - * parameters.
- *
- * Concurrent Access
- *
- * All TrustAnchor objects must be immutable and thread-safe. That is, multiple - * threads may concurrently invoke the methods defined in this class on a - * single TrustAnchor object (or more than one) with no ill effects. Requiring - * TrustAnchor objects to be immutable and thread-safe allows them to be passed - * around to various pieces of code without worrying about coordinating access. - * This stipulation applies to all public fields and methods of this class and - * any added or overridden by subclasses.
- *
- * TODO: implement better nameConstraints testing. - **/ -public class TrustAnchor -{ - private X509Certificate trustCert = null; - - private PublicKey trustPublicKey = null; - - private String trustName = null; - - private byte[] nameConstraints = null; - - /** - * Creates an instance of TrustAnchor with the specified X509Certificate and - * optional name constraints, which are intended to be used as additional - * constraints when validating an X.509 certification path.
- *
- * The name constraints are specified as a byte array. This byte array - * should contain the DER encoded form of the name constraints, as they - * would appear in the NameConstraints structure defined in RFC 2459 and - * X.509. The ASN.1 definition of this structure appears below.
- *
- * - *
-     *   NameConstraints ::= SEQUENCE {
-     *        permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
-     *        excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
-     * 
-     *   GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
-     * 
-     *   GeneralSubtree ::= SEQUENCE {
-     *        base                    GeneralName,
-     *        minimum         [0]     BaseDistance DEFAULT 0,
-     *        maximum         [1]     BaseDistance OPTIONAL }
-     * 
-     *   BaseDistance ::= INTEGER (0..MAX)
-     * 
-     *   GeneralName ::= CHOICE {
-     *        otherName                       [0]     OtherName,
-     *        rfc822Name                      [1]     IA5String,
-     *        dNSName                         [2]     IA5String,
-     *        x400Address                     [3]     ORAddress,
-     *        directoryName                   [4]     Name,
-     *        ediPartyName                    [5]     EDIPartyName,
-     *        uniformResourceIdentifier       [6]     IA5String,
-     *        iPAddress                       [7]     OCTET STRING,
-     *        registeredID                    [8]     OBJECT IDENTIFIER}
-     * 
- * - *
- *
- * Note that the name constraints byte array supplied is cloned to protect - * against subsequent modifications. - * - * @param trustedCert - * a trusted X509Certificate - * @param nameConstraints - * a byte array containing the ASN.1 DER encoding of a - * NameConstraints extension to be used for checking name - * constraints. Only the value of the extension is included, not - * the OID or criticality flag. Specify null to omit the - * parameter. - * - * @exception IllegalArgumentException - * if the name constraints cannot be decoded - * @exception NullPointerException - * if the specified X509Certificate is null - */ - public TrustAnchor(X509Certificate trustedCert, byte[] nameConstraints) - { - if (trustedCert == null) - { - throw new NullPointerException("trustedCert must be non-null"); - } - - this.trustCert = trustedCert; - if (nameConstraints != null) - { - this.nameConstraints = (byte[])nameConstraints.clone(); - checkNameConstraints(this.nameConstraints); - } - } - - /** - * Creates an instance of TrustAnchor where the most-trusted - * CA is specified as a distinguished name and public key. Name constraints - * are an optional parameter, and are intended to be used as additional - * constraints when validating an X.509 certification path. - * - * The name constraints are specified as a byte array. This byte array - * contains the DER encoded form of the name constraints, as they would - * appear in the NameConstraints structure defined in RFC 2459 and X.509. - * The ASN.1 notation for this structure is supplied in the documentation - * for {@link #TrustAnchor(X509Certificate trustedCert, byte[] - * nameConstraints) TrustAnchor(X509Certificate trustedCert, byte[] - * nameConstraints) }. - * - * Note that the name constraints byte array supplied here is cloned to - * protect against subsequent modifications. - * - * @param caName - * the X.500 distinguished name of the most-trusted CA in RFC - * 2253 String format - * @param pubKey - * the public key of the most-trusted CA - * @param nameConstraints - * a byte array containing the ASN.1 DER encoding of a - * NameConstraints extension to be used for checking name - * constraints. Only the value of the extension is included, not - * the OID or criticality flag. Specify null to omit the - * parameter. - * - * @exception IllegalArgumentException - * if the specified caName parameter is empty (caName.length() == 0) - * or incorrectly formatted or the name constraints cannot be - * decoded - * @exception NullPointerException - * if the specified caName or pubKey parameter is null - */ - public TrustAnchor(String caName, PublicKey pubKey, byte[] nameConstraints) - { - if (caName == null) - { - throw new NullPointerException("caName must be non-null"); - } - if (pubKey == null) - { - throw new NullPointerException("pubKey must be non-null"); - } - if (caName.length() == 0) - { - throw new IllegalArgumentException( - "caName can not be an empty string"); - } - - this.trustName = caName; - this.trustPublicKey = pubKey; - if (nameConstraints != null) - { - this.nameConstraints = (byte[])nameConstraints.clone(); - checkNameConstraints(this.nameConstraints); - } - } - - /** - * Returns the most-trusted CA certificate. - * - * @return a trusted X509Certificate or null - * if the trust anchor was not specified as a trusted certificate - */ - public final X509Certificate getTrustedCert() - { - return trustCert; - } - - /** - * Returns the name of the most-trusted CA in RFC 2253 String format. - * - * @return the X.500 distinguished name of the most-trusted CA, or - * null if the trust anchor was not specified as a - * trusted public key and name pair - */ - public final String getCAName() - { - return trustName; - } - - /** - * Returns the public key of the most-trusted CA. - * - * @return the public key of the most-trusted CA, or null if the trust - * anchor was not specified as a trusted public key and name pair - */ - public final PublicKey getCAPublicKey() - { - return trustPublicKey; - } - - /** - * Returns the name constraints parameter. The specified name constraints - * are associated with this trust anchor and are intended to be used as - * additional constraints when validating an X.509 certification path.
- *
- * The name constraints are returned as a byte array. This byte array - * contains the DER encoded form of the name constraints, as they would - * appear in the NameConstraints structure defined in RFC 2459 and X.509. - * The ASN.1 notation for this structure is supplied in the documentation - * for TrustAnchor(X509Certificate trustedCert, byte[] - * nameConstraints).
- *
- * Note that the byte array returned is cloned to protect against subsequent - * modifications. - * - * @return a byte array containing the ASN.1 DER encoding of a - * NameConstraints extension used for checking name constraints, or - * null if not set. - */ - public final byte[] getNameConstraints() - { - return (byte[])nameConstraints.clone(); - } - - /** - * Returns a formatted string describing the TrustAnchor. - * - * @return a formatted string describing the TrustAnchor - */ - public String toString() - { - StringBuffer sb = new StringBuffer(); - sb.append("[\n"); - if (getCAPublicKey() != null) - { - sb.append(" Trusted CA Public Key: ").append(getCAPublicKey()).append('\n'); - sb.append(" Trusted CA Issuer Name: ").append(getCAName()).append('\n'); - } - else - { - sb.append(" Trusted CA cert: ").append(getTrustedCert()).append('\n'); - } - if (nameConstraints != null) - { - sb.append(" Name Constraints: ").append(nameConstraints).append('\n'); - } - return sb.toString(); - } - - /** - * Check given DER encoded nameConstraints for correct decoding. Currently - * only basic DER decoding test.
- *
- * TODO: implement more testing. - * - * @param data - * the DER encoded nameConstrains to be checked or - * null - * @exception IllegalArgumentException - * if the check failed. - */ - private void checkNameConstraints(byte[] data) - { - if (data != null) - { - try - { - ByteArrayInputStream inStream = new ByteArrayInputStream(data); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); - if (!(derObject instanceof ASN1Sequence)) - { - throw new IllegalArgumentException( - "nameConstraints parameter decoding error"); - } - } - catch (IOException ex) - { - throw new IllegalArgumentException( - "nameConstraints parameter decoding error: " + ex); - } - } - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509CRL.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509CRL.java deleted file mode 100644 index cf65ed0b6..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509CRL.java +++ /dev/null @@ -1,77 +0,0 @@ - -package java.security.cert; - -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Principal; -import java.security.PublicKey; -import java.security.SignatureException; -import java.util.Date; -import java.util.Set; - -public abstract class X509CRL extends CRL implements X509Extension -{ - protected X509CRL() - { - super("X.509"); - } - - public boolean equals(Object other) - { - if ( this == other ) - return true; - - if ( !(other instanceof X509CRL) ) - return false; - - try - { - byte[] enc1 = getEncoded(); - byte[] enc2 = ((X509CRL)other).getEncoded(); - - return MessageDigest.isEqual(enc1, enc2); - } - catch (CRLException e) - { - return false; - } - } - - public int hashCode() - { - int hashcode = 0; - - try - { - byte[] encoded = getEncoded(); - for (int i = 1; i < encoded.length; i++) - { - hashcode += encoded[i] * i; - } - } - catch (CRLException ce) - { - return(hashcode); - } - - return(hashcode); - } - - public abstract byte[] getEncoded() throws CRLException; - public abstract Principal getIssuerDN(); - public abstract Date getNextUpdate(); - public abstract X509CRLEntry getRevokedCertificate(BigInteger serialNumber); - public abstract Set getRevokedCertificates(); - public abstract String getSigAlgName(); - public abstract String getSigAlgOID(); - public abstract byte[] getSigAlgParams(); - public abstract byte[] getSignature(); - public abstract byte[] getTBSCertList() throws CRLException; - public abstract Date getThisUpdate(); - public abstract int getVersion(); - public abstract void verify(PublicKey key) throws CRLException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException; - public abstract void verify(PublicKey key, String sigProvider) throws CRLException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException; -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509CRLEntry.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509CRLEntry.java deleted file mode 100644 index bb0d78074..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509CRLEntry.java +++ /dev/null @@ -1,56 +0,0 @@ - -package java.security.cert; - -import java.math.BigInteger; -import java.security.MessageDigest; -import java.util.Date; - -public abstract class X509CRLEntry implements X509Extension -{ - public boolean equals(Object other) - { - if ( this == other ) - return true; - - if ( !(other instanceof X509CRLEntry) ) - return false; - - try - { - byte[] enc1 = getEncoded(); - byte[] enc2 = ((X509CRLEntry)other).getEncoded(); - - return MessageDigest.isEqual(enc1, enc2); - } - catch (CRLException e) - { - return false; - } - } - - public int hashCode() - { - int hashcode = 0; - - try - { - byte[] encoded = getEncoded(); - for (int i = 1; i < encoded.length; i++) - { - hashcode += encoded[i] * i; - } - } - catch (CRLException ce) - { - return(hashcode); - } - - return(hashcode); - } - - public abstract byte[] getEncoded() throws CRLException; - public abstract Date getRevocationDate(); - public abstract BigInteger getSerialNumber(); - public abstract boolean hasExtensions(); - public abstract String toString(); -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509CRLSelector.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509CRLSelector.java deleted file mode 100644 index 8d4ed9c44..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509CRLSelector.java +++ /dev/null @@ -1,717 +0,0 @@ -package java.security.cert; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.security.cert.CRL; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.util.Collection; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Object; -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.x509.X509Extensions; -import org.spongycastle.asn1.x509.X509Name; -import org.spongycastle.jce.PrincipalUtil; - -/** - * A CRLSelector that selects X509CRLs that match - * all specified criteria. This class is particularly useful when selecting CRLs - * from a CertStore to check revocation status of a particular - * certificate.
- *
- * When first constructed, an X509CRLSelector has no criteria - * enabled and each of the get methods return a default value (null). - * Therefore, the {@link #match match} method would return true - * for any X509CRL. Typically, several criteria are enabled (by - * calling {@link #setIssuerNames setIssuerNames} or - * {@link #setDateAndTime setDateAndTime}, for instance) and then the - * X509CRLSelector is passed to - * {@link CertStore#getCRLs CertStore.getCRLs} or some similar method.
- *
- * Please refer to RFC 2459 for definitions of the X.509 CRL fields and - * extensions mentioned below.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single object - * concurrently should synchronize amongst themselves and provide the necessary - * locking. Multiple threads each manipulating separate objects need not - * synchronize.
- *
- * Uses {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Sequence ASN1Sequence}, - * {@link org.spongycastle.asn1.ASN1ObjectIdentifier ASN1ObjectIdentifier}, - * {@link org.spongycastle.asn1.DEROutputStream DEROutputStream}, - * {@link org.spongycastle.asn1.ASN1Object ASN1Object}, - * {@link org.spongycastle.asn1.x509.X509Name X509Name} - * - * @see CRLSelector - * @see X509CRL - */ -public class X509CRLSelector implements CRLSelector -{ - private Set issuerNames = null; - - private Set issuerNamesX509 = null; - - private BigInteger minCRL = null; - - private BigInteger maxCRL = null; - - private Date dateAndTime = null; - - private X509Certificate certChecking = null; - - /** - * Creates an X509CRLSelector. Initially, no criteria are - * set so any X509CRL will match. - */ - public X509CRLSelector() - { - } - - /** - * Sets the issuerNames criterion. The issuer distinguished name in the - * X509CRL must match at least one of the specified - * distinguished names. If null, any issuer distinguished - * name will do.
- *
- * This method allows the caller to specify, with a single method call, the - * complete set of issuer names which X509CRLs may contain. - * The specified value replaces the previous value for the issuerNames - * criterion.
- *
- * The names parameter (if not null) is a - * Collection of names. Each name is a String - * or a byte array representing a distinguished name (in RFC 2253 or ASN.1 - * DER encoded form, respectively). If null is supplied as - * the value for this argument, no issuerNames check will be performed.
- *
- * Note that the names parameter can contain duplicate - * distinguished names, but they may be removed from the - * Collection of names returned by the - * {@link #getIssuerNames getIssuerNames} method.
- *
- * If a name is specified as a byte array, it should contain a single DER - * encoded distinguished name, as defined in X.501. The ASN.1 notation for - * this structure is as follows. - * - *

-     *  Name ::= CHOICE {
-     *    RDNSequence }
-     * 
-     *  RDNSequence ::= SEQUENCE OF RDN
-     * 
-     *  RDN ::=
-     *    SET SIZE (1 .. MAX) OF AttributeTypeAndValue
-     * 
-     *  AttributeTypeAndValue ::= SEQUENCE {
-     *    type     AttributeType,
-     *    value    AttributeValue }
-     * 
-     *  AttributeType ::= OBJECT IDENTIFIER
-     * 
-     *  AttributeValue ::= ANY DEFINED BY AttributeType
-     *  ....
-     *  DirectoryString ::= CHOICE {
-     *        teletexString           TeletexString (SIZE (1..MAX)),
-     *        printableString         PrintableString (SIZE (1..MAX)),
-     *        universalString         UniversalString (SIZE (1..MAX)),
-     *        utf8String              UTF8String (SIZE (1.. MAX)),
-     *        bmpString               BMPString (SIZE (1..MAX)) }
-     * 
- * - *
- *
- * Note that a deep copy is performed on the Collection to - * protect against subsequent modifications. - * - * @param names - * a Collection of names (or null) - * - * @exception IOException - * if a parsing error occurs - * - * @see #getIssuerNames - */ - public void setIssuerNames(Collection names) throws IOException - { - if (names == null || names.isEmpty()) - { - issuerNames = null; - issuerNamesX509 = null; - } - else - { - Object item; - Iterator iter = names.iterator(); - while (iter.hasNext()) - { - item = iter.next(); - if (item instanceof String) - { - addIssuerName((String)item); - } - else if (item instanceof byte[]) - { - addIssuerName((byte[])item); - } - else - { - throw new IOException("name not byte[]or String: " - + item.toString()); - } - } - } - } - - /** - * Adds a name to the issuerNames criterion. The issuer distinguished name - * in the X509CRL must match at least one of the specified - * distinguished names.
- *
- * This method allows the caller to add a name to the set of issuer names - * which X509CRLs may contain. The specified name is added to - * any previous value for the issuerNames criterion. If the specified name - * is a duplicate, it may be ignored.
- *
- * Uses {@link org.spongycastle.asn1.x509.X509Name X509Name} for parsing the - * name - * - * @param name - * the name in RFC 2253 form - * - * @exception IOException - * if a parsing error occurs - */ - public void addIssuerName(String name) throws IOException - { - if (issuerNames == null) - { - issuerNames = new HashSet(); - issuerNamesX509 = new HashSet(); - } - X509Name nameX509; - try - { - nameX509 = new X509Name(name); - } - catch (IllegalArgumentException ex) - { - throw new IOException(ex.getMessage()); - } - issuerNamesX509.add(nameX509); - issuerNames.add(name); - } - - /** - * Adds a name to the issuerNames criterion. The issuer distinguished name - * in the X509CRL must match at least one of the specified - * distinguished names.
- *
- * This method allows the caller to add a name to the set of issuer names - * which X509CRLs may contain. The specified name is added to - * any previous value for the issuerNames criterion. If the specified name - * is a duplicate, it may be ignored. If a name is specified as a byte - * array, it should contain a single DER encoded distinguished name, as - * defined in X.501. The ASN.1 notation for this structure is as follows.
- *
- * The name is provided as a byte array. This byte array should contain a - * single DER encoded distinguished name, as defined in X.501. The ASN.1 - * notation for this structure appears in the documentation for - * {@link #setIssuerNames setIssuerNames(Collection names)}.
- *
- * Note that the byte array supplied here is cloned to protect against - * subsequent modifications.
- *
- * Uses {@link org.spongycastle.asn1.x509.X509Name X509Name} for parsing the - * name, {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Object ASN1Object} and - * {@link org.spongycastle.asn1.ASN1Sequence ASN1Sequence} - * - * @param name - * a byte array containing the name in ASN.1 DER encoded form - * - * @exception IOException - * if a parsing error occurs - */ - public void addIssuerName(byte[] name) throws IOException - { - if (issuerNames == null) - { - issuerNames = new HashSet(); - issuerNamesX509 = new HashSet(); - } - - ByteArrayInputStream inStream = new ByteArrayInputStream(name); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object obj = derInStream.readObject(); - if (obj instanceof ASN1Sequence) - { - issuerNamesX509.add(new X509Name((ASN1Sequence)obj)); - } - else - { - throw new IOException("parsing error"); - } - issuerNames.add(name.clone()); - } - - /** - * Sets the minCRLNumber criterion. The X509CRL must have a - * CRL number extension whose value is greater than or equal to the - * specified value. If null, no minCRLNumber check will be - * done. - * - * @param minCRL - * the minimum CRL number accepted (or null) - */ - public void setMinCRLNumber(BigInteger minCRL) - { - this.minCRL = minCRL; - } - - /** - * Sets the maxCRLNumber criterion. The X509CRL must have a - * CRL number extension whose value is less than or equal to the specified - * value. If null, no maxCRLNumber check will be done. - * - * @param maxCRL - * the maximum CRL number accepted (or null) - */ - public void setMaxCRLNumber(BigInteger maxCRL) - { - this.maxCRL = maxCRL; - } - - /** - * Sets the dateAndTime criterion. The specified date must be equal to or - * later than the value of the thisUpdate component of the - * X509CRL and earlier than the value of the nextUpdate - * component. There is no match if the X509CRL does not - * contain a nextUpdate component. If null, no dateAndTime - * check will be done.
- *
- * Note that the Date supplied here is cloned to protect - * against subsequent modifications. - * - * @param dateAndTime - * the Date to match against (or null) - * - * @see #getDateAndTime - */ - public void setDateAndTime(Date dateAndTime) - { - if (dateAndTime == null) - { - this.dateAndTime = null; - } - else - { - this.dateAndTime = new Date(dateAndTime.getTime()); - } - } - - /** - * Sets the certificate being checked. This is not a criterion. Rather, it - * is optional information that may help a CertStore find - * CRLs that would be relevant when checking revocation for the specified - * certificate. If null is specified, then no such optional - * information is provided. - * - * @param cert - * the X509Certificate being checked (or - * null) - * - * @see #getCertificateChecking - */ - public void setCertificateChecking(X509Certificate cert) - { - certChecking = cert; - } - - /** - * Returns a copy of the issuerNames criterion. The issuer distinguished - * name in the X509CRL must match at least one of the - * specified distinguished names. If the value returned is null, - * any issuer distinguished name will do.
- *
- * If the value returned is not null, it is a - * Collection of names. Each name is a String - * or a byte array representing a distinguished name (in RFC 2253 or ASN.1 - * DER encoded form, respectively). Note that the Collection - * returned may contain duplicate names.
- *
- * If a name is specified as a byte array, it should contain a single DER - * encoded distinguished name, as defined in X.501. The ASN.1 notation for - * this structure is given in the documentation for - * {@link #setIssuerNames setIssuerNames(Collection names)}.
- *
- * Note that a deep copy is performed on the Collection to - * protect against subsequent modifications. - * - * @return a Collection of names (or null) - * @see #setIssuerNames - */ - public Collection getIssuerNames() - { - if (issuerNames == null) - { - return null; - } - - Collection set = new HashSet(); - Iterator iter = issuerNames.iterator(); - Object item; - while (iter.hasNext()) - { - item = iter.next(); - if (item instanceof String) - { - set.add(new String((String)item)); - } - else if (item instanceof byte[]) - { - set.add(((byte[])item).clone()); - } - } - return set; - } - - /** - * Returns the minCRLNumber criterion. The X509CRL must have - * a CRL number extension whose value is greater than or equal to the - * specified value. If null, no minCRLNumber check will be - * done. - * - * @return the minimum CRL number accepted (or null) - */ - public BigInteger getMinCRL() - { - return minCRL; - } - - /** - * Returns the maxCRLNumber criterion. The X509CRL must have - * a CRL number extension whose value is less than or equal to the specified - * value. If null, no maxCRLNumber check will be done. - * - * @return the maximum CRL number accepted (or null) - */ - public BigInteger getMaxCRL() - { - return maxCRL; - } - - /** - * Returns the dateAndTime criterion. The specified date must be equal to or - * later than the value of the thisUpdate component of the - * X509CRL and earlier than the value of the nextUpdate - * component. There is no match if the X509CRL does not - * contain a nextUpdate component. If null, no dateAndTime - * check will be done.
- *
- * Note that the Date returned is cloned to protect against - * subsequent modifications. - * - * @return the Date to match against (or null) - * - * @see #setDateAndTime - */ - public Date getDateAndTime() - { - if (dateAndTime == null) - { - return null; - } - - return new Date(dateAndTime.getTime()); - } - - /** - * Returns the certificate being checked. This is not a criterion. Rather, - * it is optional information that may help a CertStore find - * CRLs that would be relevant when checking revocation for the specified - * certificate. If the value returned is null, then no such - * optional information is provided. - * - * @return the certificate being checked (or null) - * - * @see #setCertificateChecking - */ - public X509Certificate getCertificateChecking() - { - return certChecking; - } - - /** - * Returns a printable representation of the X509CRLSelector.
- *
- * Uses - * {@link org.spongycastle.asn1.x509.X509Name#toString X509Name.toString} to - * format the output - * - * @return a String describing the contents of the - * X509CRLSelector. - */ - public String toString() - { - StringBuffer s = new StringBuffer(); - s.append("X509CRLSelector: [\n"); - if (issuerNamesX509 != null) - { - s.append(" IssuerNames:\n"); - Iterator iter = issuerNamesX509.iterator(); - while (iter.hasNext()) - { - s.append(" ").append(iter.next()).append('\n'); - } - } - if (minCRL != null) - { - s.append(" minCRLNumber: ").append(minCRL).append('\n'); - } - if (maxCRL != null) - { - s.append(" maxCRLNumber: ").append(maxCRL).append('\n'); - } - if (dateAndTime != null) - { - s.append(" dateAndTime: ").append(dateAndTime).append('\n'); - } - if (certChecking != null) - { - s.append(" Certificate being checked: ").append(certChecking).append('\n'); - } - s.append(']'); - return s.toString(); - } - - /** - * Decides whether a CRL should be selected.
- *
- * Uses - * {@link org.spongycastle.asn1.x509.X509Name#toString X509Name.toString} to - * parse and to compare the crl parameter issuer and - * {@link org.spongycastle.asn1.x509.X509Extensions#CRLNumber CRLNumber} to - * access the CRL number extension. - * - * @param crl - * the CRL to be checked - * - * @return true if the CRL should be selected, - * false otherwise - */ - public boolean match(CRL crl) - { - if (!(crl instanceof X509CRL)) - { - return false; - } - - X509CRL crlX509 = (X509CRL)crl; - boolean test; - - if (issuerNamesX509 != null) - { - Iterator iter = issuerNamesX509.iterator(); - test = false; - X509Name crlIssuer = null; - try - { - crlIssuer = PrincipalUtil.getIssuerX509Principal(crlX509); - } - catch (Exception ex) - { - - return false; - } - - while (iter.hasNext()) - { - if (crlIssuer.equals(iter.next(), true)) - { - test = true; - break; - } - } - if (!test) - { - return false; - } - } - - byte[] data = crlX509.getExtensionValue(X509Extensions.CRLNumber - .getId()); - if (data != null) - { - try - { - ByteArrayInputStream inStream = new ByteArrayInputStream(data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - inStream = new ByteArrayInputStream( - ((ASN1OctetString)derInputStream.readObject()) - .getOctets()); - derInputStream = new ASN1InputStream(inStream); - BigInteger crlNumber = ((ASN1Integer)derInputStream.readObject()) - .getPositiveValue(); - if (minCRL != null && minCRL.compareTo(crlNumber) > 0) - { - return false; - } - if (maxCRL != null && maxCRL.compareTo(crlNumber) < 0) - { - return false; - } - } - catch (IOException ex) - { - return false; - } - } - else if (minCRL != null || maxCRL != null) - { - return false; - } - - if (dateAndTime != null) - { - Date check = crlX509.getThisUpdate(); - if (check == null) - { - return false; - } - else if (dateAndTime.before(check)) - { - return false; - } - - check = crlX509.getNextUpdate(); - if (check == null) - { - return false; - } - else if (!dateAndTime.before(check)) - { - return false; - } - } - - return true; - } - - /** - * Returns a copy of this object. - * - * @return the copy - */ - public Object clone() - { - try - { - X509CRLSelector copy = (X509CRLSelector)super.clone(); - if (issuerNames != null) - { - copy.issuerNames = new HashSet(); - Iterator iter = issuerNames.iterator(); - Object obj; - while (iter.hasNext()) - { - obj = iter.next(); - if (obj instanceof byte[]) - { - copy.issuerNames.add(((byte[])obj).clone()); - } - else - { - copy.issuerNames.add(obj); - } - } - copy.issuerNamesX509 = new HashSet(issuerNamesX509); - } - return copy; - } - catch (CloneNotSupportedException e) - { - /* Cannot happen */ - throw new InternalError(e.toString()); - } - } - - /** - * Decides whether a CRL should be selected. - * - * @param crl - * the CRL to be checked - * - * @return true if the CRL should be selected, - * false otherwise - */ - public boolean equals(Object obj) - { - if (!(obj instanceof X509CRLSelector)) - { - return false; - } - - X509CRLSelector equalsCRL = (X509CRLSelector)obj; - - if (!equals(dateAndTime, equalsCRL.dateAndTime)) - { - return false; - } - - if (!equals(minCRL, equalsCRL.minCRL)) - { - return false; - } - - if (!equals(maxCRL, equalsCRL.maxCRL)) - { - return false; - } - - if (!equals(issuerNamesX509, equalsCRL.issuerNamesX509)) - { - return false; - } - - if (!equals(certChecking, equalsCRL.certChecking)) - { - return false; - } - - return true; - } - - /** - * Return true if two Objects are unequal. - * This means that one is null and the other is - * not or obj1.equals(obj2) returns - * false. - **/ - private boolean equals(Object obj1, Object obj2) - { - if (obj1 == null) - { - if (obj2 != null) - { - return true; - } - } - else if (!obj1.equals(obj2)) - { - return true; - } - return false; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509CertSelector.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509CertSelector.java deleted file mode 100644 index 9292c2e30..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509CertSelector.java +++ /dev/null @@ -1,2462 +0,0 @@ -package java.security.cert; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.security.PublicKey; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Object; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1TaggedObject; -import org.spongycastle.asn1.ASN1GeneralizedTime; -import org.spongycastle.asn1.DERGeneralizedTime; -import org.spongycastle.asn1.DEROutputStream; -import org.spongycastle.asn1.util.ASN1Dump; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.ExtendedKeyUsage; -import org.spongycastle.asn1.x509.KeyPurposeId; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x509.X509Extensions; -import org.spongycastle.asn1.x509.X509Name; -import org.spongycastle.jce.PrincipalUtil; -import org.spongycastle.util.Integers; - -/** - * A CertSelector that selects - * X509Certificates that match all - * specified criteria. This class is particularly useful when - * selecting certificates from a CertStore to build a PKIX-compliant - * certification path.
- *
- * When first constructed, an X509CertSelector has no criteria enabled - * and each of the get methods return a default value (null, or -1 for - * the {@link #getBasicConstraints} method). Therefore, the {@link #match} method would - * return true for any X509Certificate. Typically, several criteria - * are enabled (by calling {@link #setIssuer} or {@link #setKeyUsage}, for instance) and - * then the X509CertSelector is passed to {@link CertStore#getCertificates} or - * some similar method.
- *
- * Several criteria can be enabled (by calling {@link #setIssuer} and - * {@link #setSerialNumber}, for example) such that the match method usually - * uniquely matches a single X509Certificate. We say usually, since it - * is possible for two issuing CAs to have the same distinguished name - * and each issue a certificate with the same serial number. Other - * unique combinations include the issuer, subject, - * subjectKeyIdentifier and/or the subjectPublicKey criteria.
- *
- * Please refer to RFC 2459 for definitions of the X.509 certificate - * extensions mentioned below.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are - * not thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize.
- *
- * TODO: implement name constraints - * TODO: implement match check for path to names
- *
- * Uses {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Sequence ASN1Sequence}, - * {@link org.spongycastle.asn1.ASN1ObjectIdentifier ASN1ObjectIdentifier}, - * {@link org.spongycastle.asn1.DEROutputStream DEROutputStream}, - * {@link org.spongycastle.asn1.ASN1Object ASN1Object}, - * {@link org.spongycastle.asn1.OIDTokenizer OIDTokenizer}, - * {@link org.spongycastle.asn1.x509.X509Name X509Name}, - * {@link org.spongycastle.asn1.x509.X509Extensions X509Extensions}, - * {@link org.spongycastle.asn1.x509.ExtendedKeyUsage ExtendedKeyUsage}, - * {@link org.spongycastle.asn1.x509.KeyPurposeId KeyPurposeId}, - * {@link org.spongycastle.asn1.x509.SubjectPublicKeyInfo SubjectPublicKeyInfo}, - * {@link org.spongycastle.asn1.x509.AlgorithmIdentifier AlgorithmIdentifier} - */ -public class X509CertSelector implements CertSelector -{ - private static final Hashtable keyPurposeIdMap = new Hashtable(); - static - { - keyPurposeIdMap.put(KeyPurposeId.id_kp_serverAuth.getId(), - KeyPurposeId.id_kp_serverAuth); - keyPurposeIdMap.put(KeyPurposeId.id_kp_clientAuth.getId(), - KeyPurposeId.id_kp_clientAuth); - keyPurposeIdMap.put(KeyPurposeId.id_kp_codeSigning.getId(), - KeyPurposeId.id_kp_codeSigning); - keyPurposeIdMap.put(KeyPurposeId.id_kp_emailProtection.getId(), - KeyPurposeId.id_kp_emailProtection); - keyPurposeIdMap.put(KeyPurposeId.id_kp_ipsecEndSystem.getId(), - KeyPurposeId.id_kp_ipsecEndSystem); - keyPurposeIdMap.put(KeyPurposeId.id_kp_ipsecTunnel.getId(), - KeyPurposeId.id_kp_ipsecTunnel); - keyPurposeIdMap.put(KeyPurposeId.id_kp_ipsecUser.getId(), - KeyPurposeId.id_kp_ipsecUser); - keyPurposeIdMap.put(KeyPurposeId.id_kp_timeStamping.getId(), - KeyPurposeId.id_kp_timeStamping); - } - - private X509Certificate x509Cert = null; - - private BigInteger serialNumber = null; - - private Object issuerDN = null; - - private X509Name issuerDNX509 = null; - - private Object subjectDN = null; - - private X509Name subjectDNX509 = null; - - private byte[] subjectKeyID = null; - - private byte[] authorityKeyID = null; - - private Date certValid = null; - - private Date privateKeyValid = null; - - private ASN1ObjectIdentifier subjectKeyAlgID = null; - - private PublicKey subjectPublicKey = null; - - private byte[] subjectPublicKeyByte = null; - - private boolean[] keyUsage = null; - - private Set keyPurposeSet = null; - - private boolean matchAllSubjectAltNames = true; - - private Set subjectAltNames = null; - - private Set subjectAltNamesByte = null; - - private int minMaxPathLen = -1; - - private Set policy = null; - - private Set policyOID = null; - - private Set pathToNames = null; - - private Set pathToNamesByte = null; - - /** - * Creates an X509CertSelector. Initially, no criteria are - * set so any X509Certificate will match. - */ - public X509CertSelector() - { - } - - /** - * Sets the certificateEquals criterion. The specified - * X509Certificate must be equal to the - * X509Certificate passed to the match method. If - * null, then this check is not applied.
- *
- * This method is particularly useful when it is necessary to match a single - * certificate. Although other criteria can be specified in conjunction with - * the certificateEquals criterion, it is usually not practical or - * necessary. - * - * @param cert - * the X509Certificate to match (or null) - * - * @see #getCertificate() - */ - public void setCertificate(X509Certificate cert) - { - x509Cert = cert; - } - - /** - * Sets the serialNumber criterion. The specified serial number must match - * the certificate serial number in the X509Certificate. If - * null, any certificate serial number will do. - * - * @param serial - * the certificate serial number to match (or null) - * - * @see #getSerialNumber() - */ - public void setSerialNumber(BigInteger serial) - { - serialNumber = serial; - } - - /** - * Sets the issuer criterion. The specified distinguished name must match - * the issuer distinguished name in the X509Certificate. If - * null, any issuer distinguished name will do.
- *
- * If issuerDN is not null, it should contain - * a distinguished name, in RFC 2253 format.
- *
- * Uses {@link org.spongycastle.asn1.x509.X509Name X509Name} for parsing the - * issuerDN. - * - * @param issuerDN - * a distinguished name in RFC 2253 format (or null) - * - * @exception IOException - * if a parsing error occurs (incorrect form for DN) - */ - public void setIssuer(String issuerDN) throws IOException - { - if (issuerDN == null) - { - this.issuerDN = null; - this.issuerDNX509 = null; - } - else - { - X509Name nameX509; - try - { - nameX509 = new X509Name(issuerDN); - } - catch (IllegalArgumentException ex) - { - throw new IOException(ex.getMessage()); - } - this.issuerDNX509 = nameX509; - this.issuerDN = issuerDN; - } - } - - /** - * Sets the issuer criterion. The specified distinguished name must match - * the issuer distinguished name in the X509Certificate. If - * null is specified, the issuer criterion is disabled and any issuer - * distinguished name will do.
- *
- * If issuerDN is not null, it should contain - * a single DER encoded distinguished name, as defined in X.501. The ASN.1 - * notation for this structure is as follows.
- *
- * - *
-     *    Name ::= CHOICE {
-     *      RDNSequence }
-     * 
-     *    RDNSequence ::= SEQUENCE OF RDN
-     * 
-     *    RDN ::=
-     *      SET SIZE (1 .. MAX) OF AttributeTypeAndValue
-     * 
-     *    AttributeTypeAndValue ::= SEQUENCE {
-     *      type     AttributeType,
-     *      value    AttributeValue }
-     * 
-     *    AttributeType ::= OBJECT IDENTIFIER
-     * 
-     *    AttributeValue ::= ANY DEFINED BY AttributeType
-     *    ....
-     *    DirectoryString ::= CHOICE {
-     *      teletexString           TeletexString (SIZE (1..MAX)),
-     *      printableString         PrintableString (SIZE (1..MAX)),
-     *      universalString         UniversalString (SIZE (1..MAX)),
-     *      utf8String              UTF8String (SIZE (1.. MAX)),
-     *      bmpString               BMPString (SIZE (1..MAX)) }
-     * 
- * - *
- *
- * Note that the byte array specified here is cloned to protect against - * subsequent modifications.
- *
- * Uses {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Object ASN1Object}, - * {@link org.spongycastle.asn1.ASN1Sequence ASN1Sequence}, - * {@link org.spongycastle.asn1.x509.X509Name X509Name} - * - * @param issuerDN - - * a byte array containing the distinguished name in ASN.1 DER - * encoded form (or null) - * - * @exception IOException - * if an encoding error occurs (incorrect form for DN) - */ - public void setIssuer(byte[] issuerDN) throws IOException - { - if (issuerDN == null) - { - this.issuerDN = null; - this.issuerDNX509 = null; - } - else - { - ByteArrayInputStream inStream = new ByteArrayInputStream(issuerDN); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object obj = derInStream.readObject(); - if (obj instanceof ASN1Sequence) - { - this.issuerDNX509 = new X509Name((ASN1Sequence)obj); - } - else - { - throw new IOException("parsing error"); - } - this.issuerDN = (byte[])issuerDN.clone(); - } - } - - /** - * Sets the subject criterion. The specified distinguished name must match - * the subject distinguished name in the X509Certificate. If - * null, any subject distinguished name will do.
- *
- * If subjectDN is not null, it should - * contain a distinguished name, in RFC 2253 format.
- *
- * Uses {@link org.spongycastle.asn1.x509.X509Name X509Name} for parsing the - * subjectDN. - * - * @param subjectDN - * a distinguished name in RFC 2253 format (or null) - * - * @exception IOException - * if a parsing error occurs (incorrect form for DN) - */ - public void setSubject(String subjectDN) throws IOException - { - if (subjectDN == null) - { - this.subjectDN = null; - this.subjectDNX509 = null; - } - else - { - X509Name nameX509; - try - { - nameX509 = new X509Name(subjectDN); - } - catch (IllegalArgumentException ex) - { - throw new IOException(ex.getMessage()); - } - - this.subjectDNX509 = nameX509; - this.subjectDN = subjectDN; - } - } - - /** - * Sets the subject criterion. The specified distinguished name must match - * the subject distinguished name in the X509Certificate. If - * null, any subject distinguished name will do.
- *
- * If subjectDN is not null, it should - * contain a single DER encoded distinguished name, as defined in X.501. For - * the ASN.1 notation for this structure, see - * {@link #setIssuer(byte []) setIssuer(byte [] issuerDN)}.
- *
- * Uses {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Object ASN1Object}, - * {@link org.spongycastle.asn1.ASN1Sequence ASN1Sequence}, - * {@link org.spongycastle.asn1.x509.X509Name X509Name} - * - * @param subjectDN - * a byte array containing the distinguished name in ASN.1 DER - * format (or null) - * - * @exception IOException - * if an encoding error occurs (incorrect form for DN) - */ - public void setSubject(byte[] subjectDN) throws IOException - { - if (subjectDN == null) - { - this.subjectDN = null; - this.subjectDNX509 = null; - } - else - { - ByteArrayInputStream inStream = new ByteArrayInputStream(subjectDN); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object obj = derInStream.readObject(); - - if (obj instanceof ASN1Sequence) - { - this.subjectDNX509 = new X509Name((ASN1Sequence)obj); - } - else - { - throw new IOException("parsing error"); - } - this.subjectDN = (byte[])subjectDN.clone(); - } - } - - /** - * Sets the subjectKeyIdentifier criterion. The X509Certificate - * must contain a SubjectKeyIdentifier extension for which the contents of - * the extension matches the specified criterion value. If the criterion - * value is null, no subjectKeyIdentifier check will be done.
- *
- * If subjectKeyID is not null, it should - * contain a single DER encoded value corresponding to the contents of the - * extension value (not including the object identifier, criticality - * setting, and encapsulating OCTET STRING) for a SubjectKeyIdentifier - * extension. The ASN.1 notation for this structure follows.
- *
- * - *
-     *    SubjectKeyIdentifier ::= KeyIdentifier
-     * 
-     *    KeyIdentifier ::= OCTET STRING
-     * 
- * - *
- *
- * Since the format of subject key identifiers is not mandated by any - * standard, subject key identifiers are not parsed by the - * X509CertSelector. Instead, the values are compared using - * a byte-by-byte comparison.
- *
- * Note that the byte array supplied here is cloned to protect against - * subsequent modifications. - * - * @param subjectKeyID - - * the subject key identifier (or null) - * - * @see #getSubjectKeyIdentifier() - */ - public void setSubjectKeyIdentifier(byte[] subjectKeyID) - { - if (subjectKeyID == null) - { - this.subjectKeyID = null; - } - else - { - this.subjectKeyID = (byte[])subjectKeyID.clone(); - } - } - - /** - * Sets the authorityKeyIdentifier criterion. The - * X509Certificate must contain an AuthorityKeyIdentifier - * extension for which the contents of the extension value matches the - * specified criterion value. If the criterion value is null, - * no authorityKeyIdentifier check will be done.
- *
- * If authorityKeyID is not null, it should - * contain a single DER encoded value corresponding to the contents of the - * extension value (not including the object identifier, criticality - * setting, and encapsulating OCTET STRING) for an AuthorityKeyIdentifier - * extension. The ASN.1 notation for this structure follows.
- *
- * - *
-     *    AuthorityKeyIdentifier ::= SEQUENCE {
-     *      keyIdentifier             [0] KeyIdentifier           OPTIONAL,
-     *      authorityCertIssuer       [1] GeneralNames            OPTIONAL,
-     *      authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL  }
-     * 
-     *    KeyIdentifier ::= OCTET STRING
-     * 
- * - *
- *
- * Authority key identifiers are not parsed by the - * X509CertSelector. Instead, the values are compared using - * a byte-by-byte comparison.
- *
- * When the keyIdentifier field of - * AuthorityKeyIdentifier is populated, the value is usually - * taken from the SubjectKeyIdentifier extension in the issuer's - * certificate. Note, however, that the result of - * X509Certificate.getExtensionValue() on the issuer's certificate may NOT be used directly as the - * input to setAuthorityKeyIdentifier. This is because the - * SubjectKeyIdentifier contains only a KeyIdentifier OCTET STRING, and not - * a SEQUENCE of KeyIdentifier, GeneralNames, and CertificateSerialNumber. - * In order to use the extension value of the issuer certificate's - * SubjectKeyIdentifier extension, it will be necessary to extract the value - * of the embedded KeyIdentifier OCTET STRING, then DER encode this OCTET - * STRING inside a SEQUENCE. For more details on SubjectKeyIdentifier, see - * {@link #setSubjectKeyIdentifier(byte[]) setSubjectKeyIdentifier(byte[] subjectKeyID }).
- *
- * Note also that the byte array supplied here is cloned to protect against - * subsequent modifications. - * - * @param authorityKeyID - * the authority key identifier (or null) - * - * @see #getAuthorityKeyIdentifier() - */ - public void setAuthorityKeyIdentifier(byte[] authorityKeyID) - { - if (authorityKeyID == null) - { - this.authorityKeyID = null; - } - else - { - this.authorityKeyID = (byte[])authorityKeyID.clone(); - } - } - - /** - * Sets the certificateValid criterion. The specified date must fall within - * the certificate validity period for the X509Certificate. If - * null, no certificateValid check will be done.
- *
- * Note that the Date supplied here is cloned to protect against subsequent - * modifications. - * - * @param certValid - * the Date to check (or null) - * - * @see #getCertificateValid() - */ - public void setCertificateValid(Date certValid) - { - if (certValid == null) - { - this.certValid = null; - } - else - { - this.certValid = new Date(certValid.getTime()); - } - } - - /** - * Sets the privateKeyValid criterion. The specified date must fall within - * the private key validity period for the X509Certificate. If - * null, no privateKeyValid check will be done.
- *
- * Note that the Date supplied here is cloned to protect against subsequent - * modifications. - * - * @param privateKeyValid - * the Date to check (or null) - * - * @see #getPrivateKeyValid() - */ - public void setPrivateKeyValid(Date privateKeyValid) - { - if (privateKeyValid == null) - { - this.privateKeyValid = null; - } - else - { - this.privateKeyValid = new Date(privateKeyValid.getTime()); - } - } - - /** - * Sets the subjectPublicKeyAlgID criterion. The X509Certificate must - * contain a subject public key with the specified algorithm. If - * null, no subjectPublicKeyAlgID check will be done. - * - * @param oid - * The object identifier (OID) of the algorithm to check for (or - * null). An OID is represented by a set of - * nonnegative integers separated by periods. - * - * @exception IOException - * if the OID is invalid, such as the first component being - * not 0, 1 or 2 or the second component being greater than - * 39. - * - * @see #getSubjectPublicKeyAlgID() - */ - public void setSubjectPublicKeyAlgID(String oid) throws IOException - { - CertUtil.parseOID(oid); - subjectKeyAlgID = new ASN1ObjectIdentifier(oid); - } - - /** - * Sets the subjectPublicKey criterion. The X509Certificate must contain the - * specified subject public key. If null, no subjectPublicKey check will be - * done. - * - * @param key - * the subject public key to check for (or null) - * - * @see #getSubjectPublicKey() - */ - public void setSubjectPublicKey(PublicKey key) - { - if (key == null) - { - subjectPublicKey = null; - subjectPublicKeyByte = null; - } - else - { - subjectPublicKey = key; - subjectPublicKeyByte = key.getEncoded(); - } - } - - /** - * Sets the subjectPublicKey criterion. The X509Certificate - * must contain the specified subject public key. If null, - * no subjectPublicKey check will be done.
- *
- * Because this method allows the public key to be specified as a byte - * array, it may be used for unknown key types.
- *
- * If key is not null, it should contain a single DER - * encoded SubjectPublicKeyInfo structure, as defined in X.509. The ASN.1 - * notation for this structure is as follows.
- *
- * - *
-     *    SubjectPublicKeyInfo  ::=  SEQUENCE  {
-     *      algorithm            AlgorithmIdentifier,
-     *      subjectPublicKey     BIT STRING  }
-     * 
-     *    AlgorithmIdentifier  ::=  SEQUENCE  {
-     *      algorithm               OBJECT IDENTIFIER,
-     *      parameters              ANY DEFINED BY algorithm OPTIONAL  }
-     *                                -- contains a value of the type
-     *                                -- registered for use with the
-     *                                -- algorithm object identifier value
-     * 
- * - *
- *
- * Note that the byte array supplied here is cloned to protect against - * subsequent modifications. - * - * @param key - * a byte array containing the subject public key in ASN.1 DER - * form (or null) - * - * @exception IOException - * if an encoding error occurs (incorrect form for subject - * public key) - * - * @see #getSubjectPublicKey() - */ - public void setSubjectPublicKey(byte[] key) throws IOException - { - if (key == null) - { - subjectPublicKey = null; - subjectPublicKeyByte = null; - } - else - { - subjectPublicKey = null; - subjectPublicKeyByte = (byte[])key.clone(); - // TODO - // try to generyte PublicKey Object from subjectPublicKeyByte - } - } - - /** - * Sets the keyUsage criterion. The X509Certificate must allow the specified - * keyUsage values. If null, no keyUsage check will be done. Note that an - * X509Certificate that has no keyUsage extension implicitly allows all - * keyUsage values.
- *
- * Note that the boolean array supplied here is cloned to protect against - * subsequent modifications. - * - * @param keyUsage - * a boolean array in the same format as the boolean array - * returned by X509Certificate.getKeyUsage(). Or - * null. - * - * @see #getKeyUsage() - */ - public void setKeyUsage(boolean[] keyUsage) - { - if (keyUsage == null) - { - this.keyUsage = null; - } - else - { - this.keyUsage = (boolean[])keyUsage.clone(); - } - } - - /** - * Sets the extendedKeyUsage criterion. The X509Certificate - * must allow the specified key purposes in its extended key usage - * extension. If keyPurposeSet is empty or null, - * no extendedKeyUsage check will be done. Note that an - * X509Certificate that has no extendedKeyUsage extension - * implicitly allows all key purposes.
- *
- * Note that the Set is cloned to protect against subsequent modifications.
- *
- * Uses {@link org.spongycastle.asn1.x509.KeyPurposeId KeyPurposeId} - * - * @param keyPurposeSet - * a Set of key purpose OIDs in string format (or - * null). Each OID is represented by a set of - * nonnegative integers separated by periods. - * - * @exception IOException - * if the OID is invalid, such as the first component being - * not 0, 1 or 2 or the second component being greater than - * 39. - * - * @see #getExtendedKeyUsage() - */ - public void setExtendedKeyUsage(Set keyPurposeSet) throws IOException - { - if (keyPurposeSet == null || keyPurposeSet.isEmpty()) - { - this.keyPurposeSet = keyPurposeSet; - } - else - { - this.keyPurposeSet = new HashSet(); - Iterator iter = keyPurposeSet.iterator(); - Object obj; - KeyPurposeId purposeID; - while (iter.hasNext()) - { - obj = iter.next(); - if (obj instanceof String) - { - purposeID = (KeyPurposeId)keyPurposeIdMap.get((String)obj); - if (purposeID == null) - { - throw new IOException("unknown purposeID " - + (String)obj); - } - this.keyPurposeSet.add(purposeID); - } - } - } - } - - /** - * Enables/disables matching all of the subjectAlternativeNames specified in - * the {@link #setSubjectAlternativeNames setSubjectAlternativeNames} or - * {@link #addSubjectAlternativeName addSubjectAlternativeName} methods. If - * enabled, the X509Certificate must contain all of the - * specified subject alternative names. If disabled, the X509Certificate - * must contain at least one of the specified subject alternative names.
- *
- * The matchAllNames flag is true by default. - * - * @param matchAllNames - * if true, the flag is enabled; if - * false, the flag is disabled. - * - * @see #getMatchAllSubjectAltNames() - */ - public void setMatchAllSubjectAltNames(boolean matchAllNames) - { - matchAllSubjectAltNames = matchAllNames; - } - - /** - * Sets the subjectAlternativeNames criterion. The - * X509Certificate must contain all or at least one of the - * specified subjectAlternativeNames, depending on the value of the - * matchAllNames flag (see {@link #setMatchAllSubjectAltNames}).
- *
- * This method allows the caller to specify, with a single method call, the - * complete set of subject alternative names for the subjectAlternativeNames - * criterion. The specified value replaces the previous value for the - * subjectAlternativeNames criterion.
- *
- * The names parameter (if not null) is a - * Collection with one entry for each name to be included in - * the subject alternative name criterion. Each entry is a List - * whose first entry is an Integer (the name type, 0-8) and - * whose second entry is a String or a byte array (the name, - * in string or ASN.1 DER encoded form, respectively). There can be multiple - * names of the same type. If null is supplied as the value - * for this argument, no subjectAlternativeNames check will be performed.
- *
- * Each subject alternative name in the Collection may be - * specified either as a String or as an ASN.1 encoded byte - * array. For more details about the formats used, see - * {@link #addSubjectAlternativeName(int, String) addSubjectAlternativeName(int type, String name)} - * and - * {@link #addSubjectAlternativeName(int, byte[]) addSubjectAlternativeName(int type, byte [] name}).
- *
- * Note that the names parameter can contain duplicate names - * (same name and name type), but they may be removed from the - * Collection of names returned by the - * {@link #getSubjectAlternativeNames} method.
- *
- * Note that a deep copy is performed on the Collection to protect against - * subsequent modifications. - * - * @param names - - * a Collection of names (or null) - * - * @exception IOException - * if a parsing error occurs - * - * @see #getSubjectAlternativeNames() - */ - public void setSubjectAlternativeNames(Collection names) throws IOException - { - try - { - if (names == null || names.isEmpty()) - { - subjectAltNames = null; - subjectAltNamesByte = null; - } - else - { - subjectAltNames = new HashSet(); - subjectAltNamesByte = new HashSet(); - Iterator iter = names.iterator(); - List item; - int type; - Object data; - while (iter.hasNext()) - { - item = (List)iter.next(); - type = ((Integer)item.get(0)).intValue(); - data = item.get(1); - if (data instanceof String) - { - addSubjectAlternativeName(type, (String)data); - } - else if (data instanceof byte[]) - { - addSubjectAlternativeName(type, (byte[])data); - } - else - { - throw new IOException( - "parsing error: unknown data type"); - } - } - } - } - catch (Exception ex) - { - throw new IOException("parsing exception:\n" + ex.toString()); - } - } - - /** - * Adds a name to the subjectAlternativeNames criterion. The - * X509Certificate must contain all or at least one of the - * specified subjectAlternativeNames, depending on the value of the - * matchAllNames flag (see {@link #setMatchAllSubjectAltNames}).
- *
- * This method allows the caller to add a name to the set of subject - * alternative names. The specified name is added to any previous value for - * the subjectAlternativeNames criterion. If the specified name is a - * duplicate, it may be ignored.
- *
- * The name is provided in string format. RFC 822, DNS, and URI names use - * the well-established string formats for those types (subject to the - * restrictions included in RFC 2459). IPv4 address names are supplied using - * dotted quad notation. OID address names are represented as a series of - * nonnegative integers separated by periods. And directory names - * (distinguished names) are supplied in RFC 2253 format. No standard string - * format is defined for otherNames, X.400 names, EDI party names, IPv6 - * address names, or any other type of names. They should be specified using - * the - * {@link #addSubjectAlternativeName(int, byte[]) addSubjectAlternativeName(int type, byte [] name)} - * method. - * - * @param type - * the name type (0-8, as specified in RFC 2459, section 4.2.1.7) - * @param name - - * the name in string form (not null) - * - * @exception IOException - * if a parsing error occurs - */ - public void addSubjectAlternativeName(int type, String name) - throws IOException - { - // TODO full implementation of CertUtil.parseGeneralName - byte[] encoded = CertUtil.parseGeneralName(type, name); - List tmpList = new ArrayList(); - tmpList.add(Integers.valueOf(type)); - tmpList.add(name); - subjectAltNames.add(tmpList); - tmpList.set(1, encoded); - subjectAltNamesByte.add(tmpList); - } - - /** - * Adds a name to the subjectAlternativeNames criterion. The - * X509Certificate must contain all or at least one of the - * specified subjectAlternativeNames, depending on the value of the - * matchAllNames flag (see {@link #setMatchAllSubjectAltNames}).
- *
- * This method allows the caller to add a name to the set of subject - * alternative names. The specified name is added to any previous value for - * the subjectAlternativeNames criterion. If the specified name is a - * duplicate, it may be ignored.
- *
- * The name is provided as a byte array. This byte array should contain the - * DER encoded name, as it would appear in the GeneralName structure defined - * in RFC 2459 and X.509. The encoded byte array should only contain the - * encoded value of the name, and should not include the tag associated with - * the name in the GeneralName structure. The ASN.1 definition of this - * structure appears below.
- *
- * - *
-     *    GeneralName ::= CHOICE {
-     *        otherName                       [0]     OtherName,
-     *        rfc822Name                      [1]     IA5String,
-     *        dNSName                         [2]     IA5String,
-     *        x400Address                     [3]     ORAddress,
-     *        directoryName                   [4]     Name,
-     *        ediPartyName                    [5]     EDIPartyName,
-     *        uniformResourceIdentifier       [6]     IA5String,
-     *        iPAddress                       [7]     OCTET STRING,
-     *        registeredID                    [8]     OBJECT IDENTIFIER}
-     * 
- * - *
- *
- * Note that the byte array supplied here is cloned to protect against - * subsequent modifications.
- *
- * TODO: check encoded format - * - * @param type - * the name type (0-8, as listed above) - * @param name - * a byte array containing the name in ASN.1 DER encoded form - * - * @exception IOException - * if a parsing error occurs - */ - public void addSubjectAlternativeName(int type, byte[] name) - throws IOException - { - // TODO check encoded format - List tmpList = new ArrayList(); - tmpList.add(Integers.valueOf(type)); - tmpList.add(name.clone()); - subjectAltNames.add(tmpList); - subjectAltNamesByte.add(tmpList); - } - - /** - * Sets the name constraints criterion. The X509Certificate - * must have subject and subject alternative names that meet the specified - * name constraints.
- *
- * The name constraints are specified as a byte array. This byte array - * should contain the DER encoded form of the name constraints, as they - * would appear in the NameConstraints structure defined in RFC 2459 and - * X.509. The ASN.1 definition of this structure appears below.
- *
- * - *
-     *   NameConstraints ::= SEQUENCE {
-     *        permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
-     *        excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
-     * 
-     *   GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
-     * 
-     *   GeneralSubtree ::= SEQUENCE {
-     *        base                    GeneralName,
-     *        minimum         [0]     BaseDistance DEFAULT 0,
-     *        maximum         [1]     BaseDistance OPTIONAL }
-     * 
-     *   BaseDistance ::= INTEGER (0..MAX)
-     * 
-     *   GeneralName ::= CHOICE {
-     *        otherName                       [0]     OtherName,
-     *        rfc822Name                      [1]     IA5String,
-     *        dNSName                         [2]     IA5String,
-     *        x400Address                     [3]     ORAddress,
-     *        directoryName                   [4]     Name,
-     *        ediPartyName                    [5]     EDIPartyName,
-     *        uniformResourceIdentifier       [6]     IA5String,
-     *        iPAddress                       [7]     OCTET STRING,
-     *        registeredID                    [8]     OBJECT IDENTIFIER}
-     * 
- * - *
- *
- * Note that the byte array supplied here is cloned to protect against - * subsequent modifications.
- *
- * TODO: implement this - * - * @param bytes - * a byte array containing the ASN.1 DER encoding of a - * NameConstraints extension to be used for checking name - * constraints. Only the value of the extension is included, not - * the OID or criticality flag. Can be null, in - * which case no name constraints check will be performed - * - * @exception IOException - * if a parsing error occurs - * @exception UnsupportedOperationException - * because this method is not supported - * @see #getNameConstraints() - */ - public void setNameConstraints(byte[] bytes) throws IOException - { - throw new UnsupportedOperationException(); - } - - /** - * Sets the basic constraints constraint. If the value is greater than or - * equal to zero, X509Certificates must include a - * basicConstraints extension with a pathLen of at least this value. If the - * value is -2, only end-entity certificates are accepted. If the value is - * -1, no check is done.
- *
- * This constraint is useful when building a certification path forward - * (from the target toward the trust anchor. If a partial path has been - * built, any candidate certificate must have a maxPathLen value greater - * than or equal to the number of certificates in the partial path. - * - * @param minMaxPathLen - * the value for the basic constraints constraint - * - * @exception IllegalArgumentException - * if the value is less than -2 - * - * @see #getBasicConstraints() - */ - public void setBasicConstraints(int minMaxPathLen) - { - if (minMaxPathLen < -2) - { - throw new IllegalArgumentException("minMaxPathLen must be >= -2"); - } - - this.minMaxPathLen = minMaxPathLen; - } - - /** - * Sets the policy constraint. The X509Certificate must include at least one - * of the specified policies in its certificate policies extension. If - * certPolicySet is empty, then the X509Certificate must include at least - * some specified policy in its certificate policies extension. If - * certPolicySet is null, no policy check will be performed.
- *
- * Note that the Set is cloned to protect against subsequent modifications.
- *
- * TODO: implement match check for this - * - * @param certPolicySet - * a Set of certificate policy OIDs in string format (or null). - * Each OID is represented by a set of nonnegative integers - * separated by periods. - * - * @exception IOException - * if a parsing error occurs on the OID such as the first - * component is not 0, 1 or 2 or the second component is - * greater than 39. - * - * @see #getPolicy() - */ - public void setPolicy(Set certPolicySet) throws IOException - { - if (certPolicySet == null) - { - policy = null; - policyOID = null; - } - else - { - policyOID = new HashSet(); - Iterator iter = certPolicySet.iterator(); - Object item; - while (iter.hasNext()) - { - item = iter.next(); - if (item instanceof String) - { - CertUtil.parseOID((String)item); - policyOID.add(new ASN1ObjectIdentifier((String)item)); - } - else - { - throw new IOException( - "certPolicySet contains null values or non String objects"); - } - } - policy = new HashSet(certPolicySet); - } - } - - /** - * Sets the pathToNames criterion. The X509Certificate must - * not include name constraints that would prohibit building a path to the - * specified names.
- *
- * This method allows the caller to specify, with a single method call, the - * complete set of names which the X509Certificates's name - * constraints must permit. The specified value replaces the previous value - * for the pathToNames criterion.
- *
- * This constraint is useful when building a certification path forward - * (from the target toward the trust anchor. If a partial path has been - * built, any candidate certificate must not include name constraints that - * would prohibit building a path to any of the names in the partial path.
- *
- * The names parameter (if not null) is a - * Collection with one entry for each name to be included in - * the pathToNames criterion. Each entry is a List whose - * first entry is an Integer (the name type, 0-8) and whose second entry is - * a String or a byte array (the name, in string or ASN.1 DER - * encoded form, respectively). There can be multiple names of the same - * type. If null is supplied as the value for this argument, - * no pathToNames check will be performed.
- *
- * Each name in the Collection may be specified either as a String or as an - * ASN.1 encoded byte array. For more details about the formats used, see - * {@link #addPathToName(int, String) addPathToName(int type, String name)} - * and - * {@link #addPathToName(int, byte[]) addPathToName(int type, byte [] name)}.
- *
- * Note that the names parameter can contain duplicate names (same name and - * name type), but they may be removed from the Collection of names returned - * by the {@link #getPathToNames} method.
- *
- * Note that a deep copy is performed on the Collection to protect against - * subsequent modifications.
- *
- * TODO: implement this match check for this - * - * @param names - * a Collection with one entry per name (or null) - * - * @exception IOException - * if a parsing error occurs - * @exception UnsupportedOperationException - * because this method is not supported - * - * @see #getPathToNames() - */ - public void setPathToNames(Collection names) throws IOException - { - try - { - if (names == null || names.isEmpty()) - { - pathToNames = null; - pathToNamesByte = null; - } - else - { - pathToNames = new HashSet(); - pathToNamesByte = new HashSet(); - Iterator iter = names.iterator(); - List item; - int type; - Object data; - - while (iter.hasNext()) - { - item = (List)iter.next(); - type = ((Integer)item.get(0)).intValue(); - data = item.get(1); - if (data instanceof String) - { - addPathToName(type, (String)data); - } - else if (data instanceof byte[]) - { - addPathToName(type, (byte[])data); - } - else - { - throw new IOException( - "parsing error: unknown data type"); - } - } - } - } - catch (Exception ex) - { - throw new IOException("parsing exception:\n" + ex.toString()); - } - } - - /** - * Adds a name to the pathToNames criterion. The - * X509Certificate must not include name constraints that - * would prohibit building a path to the specified name.
- *
- * This method allows the caller to add a name to the set of names which the - * X509Certificates's name constraints must permit. The - * specified name is added to any previous value for the pathToNames - * criterion. If the name is a duplicate, it may be ignored.
- *
- * The name is provided in string format. RFC 822, DNS, and URI names use - * the well-established string formats for those types (subject to the - * restrictions included in RFC 2459). IPv4 address names are supplied using - * dotted quad notation. OID address names are represented as a series of - * nonnegative integers separated by periods. And directory names - * (distinguished names) are supplied in RFC 2253 format. No standard string - * format is defined for otherNames, X.400 names, EDI party names, IPv6 - * address names, or any other type of names. They should be specified using - * the - * {@link #addPathToName(int, byte[]) addPathToName(int type, byte [] name)} - * method.
- *
- * TODO: implement this match check for this - * - * @param type - * the name type (0-8, as specified in RFC 2459, section 4.2.1.7) - * @param name - * the name in string form - * - * @exceptrion IOException if a parsing error occurs - */ - public void addPathToName(int type, String name) throws IOException - { - // TODO full implementation of CertUtil.parseGeneralName - byte[] encoded = CertUtil.parseGeneralName(type, name); - List tmpList = new ArrayList(); - tmpList.add(Integers.valueOf(type)); - tmpList.add(name); - pathToNames.add(tmpList); - tmpList.set(1, encoded); - pathToNamesByte.add(tmpList); - throw new UnsupportedOperationException(); - } - - /** - * Adds a name to the pathToNames criterion. The - * X509Certificate must not include name constraints that - * would prohibit building a path to the specified name.
- *
- * This method allows the caller to add a name to the set of names which the - * X509Certificates's name constraints must permit. The - * specified name is added to any previous value for the pathToNames - * criterion. If the name is a duplicate, it may be ignored.
- *
- * The name is provided as a byte array. This byte array should contain the - * DER encoded name, as it would appear in the GeneralName structure defined - * in RFC 2459 and X.509. The ASN.1 definition of this structure appears in - * the documentation for - * {@link #addSubjectAlternativeName(int,byte[]) addSubjectAlternativeName(int type, byte[] name)}.
- *
- * Note that the byte array supplied here is cloned to protect against - * subsequent modifications.
- *
- * TODO: implement this match check for this - * - * @param type - * the name type (0-8, as specified in RFC 2459, section 4.2.1.7) - * @param name - * a byte array containing the name in ASN.1 DER encoded form - * - * @exception IOException - * if a parsing error occurs - */ - public void addPathToName(int type, byte[] name) throws IOException - { - // TODO check encoded format - List tmpList = new ArrayList(); - tmpList.add(Integers.valueOf(type)); - tmpList.add(name.clone()); - pathToNames.add(tmpList); - pathToNamesByte.add(tmpList); - } - - /** - * Returns the certificateEquals criterion. The specified - * X509Certificate must be equal to the - * X509Certificate passed to the match method. If - * null, this check is not applied. - * - * @retrun the X509Certificate to match (or null) - * - * @see #setCertificate(java.security.cert.X509Certificate) - */ - public X509Certificate getCertificate() - { - return x509Cert; - } - - /** - * Returns the serialNumber criterion. The specified serial number must - * match the certificate serial number in the X509Certificate. - * If null, any certificate serial number will do. - * - * @return the certificate serial number to match (or null) - * - * @see #setSerialNumber(java.math.BigInteger) - */ - public BigInteger getSerialNumber() - { - return serialNumber; - } - - /** - * Returns the issuer criterion as a String. This distinguished name must - * match the issuer distinguished name in the X509Certificate. - * If null, the issuer criterion is disabled and any issuer - * distinguished name will do.
- *
- * If the value returned is not null, it is a distinguished - * name, in RFC 2253 format.
- *
- * Uses {@link org.spongycastle.asn1.x509.X509Name X509Name} for formatiing - * byte[] issuerDN to String. - * - * @return the required issuer distinguished name in RFC 2253 format (or - * null) - */ - public String getIssuerAsString() - { - if (issuerDN instanceof String) - { - return new String((String)issuerDN); - } - else if (issuerDNX509 != null) - { - return issuerDNX509.toString(); - } - - return null; - } - - /** - * Returns the issuer criterion as a byte array. This distinguished name - * must match the issuer distinguished name in the - * X509Certificate. If null, the issuer - * criterion is disabled and any issuer distinguished name will do.
- *
- * If the value returned is not null, it is a byte array - * containing a single DER encoded distinguished name, as defined in X.501. - * The ASN.1 notation for this structure is supplied in the documentation - * for {@link #setIssuer(byte[]) setIssuer(byte [] issuerDN)}.
- *
- * Note that the byte array returned is cloned to protect against subsequent - * modifications.
- *
- * Uses {@link org.spongycastle.asn1.DEROutputStream DEROutputStream}, - * {@link org.spongycastle.asn1.x509.X509Name X509Name} to gnerate byte[] - * output for String issuerDN. - * - * @return a byte array containing the required issuer distinguished name in - * ASN.1 DER format (or null) - * - * @exception IOException - * if an encoding error occurs - */ - public byte[] getIssuerAsBytes() throws IOException - { - if (issuerDN instanceof byte[]) - { - return (byte[])((byte[])issuerDN).clone(); - } - else if (issuerDNX509 != null) - { - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - DEROutputStream derOutStream = new DEROutputStream(outStream); - - derOutStream.writeObject(issuerDNX509.toASN1Primitive()); - derOutStream.close(); - - return outStream.toByteArray(); - } - - return null; - } - - /** - * Returns the subject criterion as a String. This distinguished name must - * match the subject distinguished name in the X509Certificate. - * If null, the subject criterion is disabled and any - * subject distinguished name will do.
- *
- * If the value returned is not null, it is a distinguished - * name, in RFC 2253 format.
- *
- * Uses {@link org.spongycastle.asn1.x509.X509Name X509Name} for formatiing - * byte[] subjectDN to String. - * - * @return the required subject distinguished name in RFC 2253 format (or - * null) - */ - public String getSubjectAsString() - { - if (subjectDN instanceof String) - { - return new String((String)subjectDN); - } - else if (subjectDNX509 != null) - { - return subjectDNX509.toString(); - } - - return null; - } - - /** - * Returns the subject criterion as a byte array. This distinguished name - * must match the subject distinguished name in the - * X509Certificate. If null, the subject - * criterion is disabled and any subject distinguished name will do.
- *
- * If the value returned is not null, it is a byte array - * containing a single DER encoded distinguished name, as defined in X.501. - * The ASN.1 notation for this structure is supplied in the documentation - * for {@link #setSubject(byte [] subjectDN) setSubject(byte [] subjectDN)}.
- *
- * Note that the byte array returned is cloned to protect against subsequent - * modifications.
- *
- * Uses {@link org.spongycastle.asn1.DEROutputStream DEROutputStream}, - * {@link org.spongycastle.asn1.x509.X509Name X509Name} to gnerate byte[] - * output for String subjectDN. - * - * @return a byte array containing the required subject distinguished name - * in ASN.1 DER format (or null) - * - * @exception IOException - * if an encoding error occurs - */ - public byte[] getSubjectAsBytes() throws IOException - { - if (subjectDN instanceof byte[]) - { - return (byte[])((byte[])subjectDN).clone(); - } - else if (subjectDNX509 != null) - { - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - DEROutputStream derOutStream = new DEROutputStream(outStream); - - derOutStream.writeObject(subjectDNX509.toASN1Primitive()); - derOutStream.close(); - - return outStream.toByteArray(); - } - - return null; - } - - /** - * Returns the subjectKeyIdentifier criterion. The - * X509Certificate must contain a SubjectKeyIdentifier - * extension with the specified value. If null, no - * subjectKeyIdentifier check will be done.
- *
- * Note that the byte array returned is cloned to protect against subsequent - * modifications. - * - * @return the key identifier (or null) - * - * @see #setSubjectKeyIdentifier - */ - public byte[] getSubjectKeyIdentifier() - { - if (subjectKeyID != null) - { - return (byte[])subjectKeyID.clone(); - } - - return null; - } - - /** - * Returns the authorityKeyIdentifier criterion. The - * X509Certificate must contain a AuthorityKeyIdentifier - * extension with the specified value. If null, no - * authorityKeyIdentifier check will be done.
- *
- * Note that the byte array returned is cloned to protect against subsequent - * modifications. - * - * @return the key identifier (or null) - * - * @see #setAuthorityKeyIdentifier - */ - public byte[] getAuthorityKeyIdentifier() - { - if (authorityKeyID != null) - { - return (byte[])authorityKeyID.clone(); - } - - return null; - } - - /** - * Returns the certificateValid criterion. The specified date must fall - * within the certificate validity period for the - * X509Certificate. If null, no - * certificateValid check will be done.
- *
- * Note that the Date returned is cloned to protect against - * subsequent modifications. - * - * @return the Date to check (or null) - * - * @see #setCertificateValid - */ - public Date getCertificateValid() - { - if (certValid != null) - { - return new Date(certValid.getTime()); - } - - return null; - } - - /** - * Returns the privateKeyValid criterion. The specified date must fall - * within the private key validity period for the - * X509Certificate. If null, no - * privateKeyValid check will be done.
- *
- * Note that the Date returned is cloned to protect against - * subsequent modifications. - * - * @return the Date to check (or null) - * - * @see #setPrivateKeyValid - */ - public Date getPrivateKeyValid() - { - if (privateKeyValid != null) - { - return new Date(privateKeyValid.getTime()); - } - - return null; - } - - /** - * Returns the subjectPublicKeyAlgID criterion. The - * X509Certificate must contain a subject public key with the - * specified algorithm. If null, no subjectPublicKeyAlgID - * check will be done. - * - * @return the object identifier (OID) of the signature algorithm to check - * for (or null). An OID is represented by a set of - * nonnegative integers separated by periods. - * - * @see #setSubjectPublicKeyAlgID - */ - public String getSubjectPublicKeyAlgID() - { - if (subjectKeyAlgID != null) - { - return subjectKeyAlgID.toString(); - } - - return null; - } - - /** - * Returns the subjectPublicKey criterion. The X509Certificate - * must contain the specified subject public key. If null, - * no subjectPublicKey check will be done. - * - * @return the subject public key to check for (or null) - * - * @see #setSubjectPublicKey - */ - public PublicKey getSubjectPublicKey() - { - return subjectPublicKey; - } - - /** - * Returns the keyUsage criterion. The X509Certificate must - * allow the specified keyUsage values. If null, no keyUsage check will be - * done.
- *
- * Note that the boolean array returned is cloned to protect against - * subsequent modifications. - * - * @return a boolean array in the same format as the boolean array returned - * by - * {@link X509Certificate#getKeyUsage() X509Certificate.getKeyUsage()}. - * Or null. - * - * @see #setKeyUsage - */ - public boolean[] getKeyUsage() - { - if (keyUsage != null) - { - return (boolean[])keyUsage.clone(); - } - - return null; - } - - /** - * Returns the extendedKeyUsage criterion. The X509Certificate - * must allow the specified key purposes in its extended key usage - * extension. If the keyPurposeSet returned is empty or - * null, no extendedKeyUsage check will be done. Note that - * an X509Certificate that has no extendedKeyUsage extension - * implicitly allows all key purposes. - * - * @return an immutable Set of key purpose OIDs in string - * format (or null) - * @see #setExtendedKeyUsage - */ - public Set getExtendedKeyUsage() - { - if (keyPurposeSet == null || keyPurposeSet.isEmpty()) - { - return keyPurposeSet; - } - - Set returnSet = new HashSet(); - Iterator iter = keyPurposeSet.iterator(); - while (iter.hasNext()) - { - returnSet.add(iter.next().toString()); - } - - return Collections.unmodifiableSet(returnSet); - } - - /** - * Indicates if the X509Certificate must contain all or at - * least one of the subjectAlternativeNames specified in the - * {@link #setSubjectAlternativeNames setSubjectAlternativeNames} or - * {@link #addSubjectAlternativeName addSubjectAlternativeName} methods. If - * true, the X509Certificate must contain all - * of the specified subject alternative names. If false, the - * X509Certificate must contain at least one of the specified - * subject alternative names. - * - * @return true if the flag is enabled; false - * if the flag is disabled. The flag is true by - * default. - * - * @see #setMatchAllSubjectAltNames - */ - public boolean getMatchAllSubjectAltNames() - { - return matchAllSubjectAltNames; - } - - /** - * Returns a copy of the subjectAlternativeNames criterion. The - * X509Certificate must contain all or at least one of the - * specified subjectAlternativeNames, depending on the value of the - * matchAllNames flag (see {@link #getMatchAllSubjectAltNames - * getMatchAllSubjectAltNames}). If the value returned is null, - * no subjectAlternativeNames check will be performed.
- *
- * If the value returned is not null, it is a - * Collection with one entry for each name to be included in - * the subject alternative name criterion. Each entry is a List - * whose first entry is an Integer (the name type, 0-8) and - * whose second entry is a String or a byte array (the name, - * in string or ASN.1 DER encoded form, respectively). There can be multiple - * names of the same type. Note that the Collection returned - * may contain duplicate names (same name and name type).
- *
- * Each subject alternative name in the Collection may be - * specified either as a String or as an ASN.1 encoded byte - * array. For more details about the formats used, see - * {@link #addSubjectAlternativeName(int type, String name) - * addSubjectAlternativeName(int type, String name)} and - * {@link #addSubjectAlternativeName(int type, byte [] name) - * addSubjectAlternativeName(int type, byte [] name)}.
- *
- * Note that a deep copy is performed on the Collection to - * protect against subsequent modifications. - * - * @return a Collection of names (or null) - * - * @see #setSubjectAlternativeNames - */ - public Collection getSubjectAlternativeNames() - { - if (subjectAltNames != null) - { - return null; - } - - Set returnAltNames = new HashSet(); - List returnList; - Iterator iter = subjectAltNames.iterator(); - List obj; - while (iter.hasNext()) - { - obj = (List)iter.next(); - returnList = new ArrayList(); - returnList.add(obj.get(0)); - if (obj.get(1) instanceof byte[]) - { - returnList.add(((byte[])obj.get(1)).clone()); - } - else - { - returnList.add(obj.get(1)); - } - returnAltNames.add(returnList); - } - - return returnAltNames; - } - - /** - * Returns the name constraints criterion. The X509Certificate - * must have subject and subject alternative names that meet the specified - * name constraints.
- *
- * The name constraints are returned as a byte array. This byte array - * contains the DER encoded form of the name constraints, as they would - * appear in the NameConstraints structure defined in RFC 2459 and X.509. - * The ASN.1 notation for this structure is supplied in the documentation - * for - * {@link #setNameConstraints(byte [] bytes) setNameConstraints(byte [] bytes)}.
- *
- * Note that the byte array returned is cloned to protect against subsequent - * modifications.
- *
- * TODO: implement this - * - * @return a byte array containing the ASN.1 DER encoding of a - * NameConstraints extension used for checking name constraints. - * null if no name constraints check will be - * performed. - * - * @exception UnsupportedOperationException - * because this method is not supported - * - * @see #setNameConstraints - */ - public byte[] getNameConstraints() - { - throw new UnsupportedOperationException(); - } - - /** - * Returns the basic constraints constraint. If the value is greater than or - * equal to zero, the X509Certificates must include a - * basicConstraints extension with a pathLen of at least this value. If the - * value is -2, only end-entity certificates are accepted. If the value is - * -1, no basicConstraints check is done. - * - * @return the value for the basic constraints constraint - * - * @see #setBasicConstraints - */ - public int getBasicConstraints() - { - return minMaxPathLen; - } - - /** - * Returns the policy criterion. The X509Certificate must - * include at least one of the specified policies in its certificate - * policies extension. If the Set returned is empty, then the - * X509Certificate must include at least some specified - * policy in its certificate policies extension. If the Set - * returned is null, no policy check will be performed. - * - * @return an immutable Set of certificate policy OIDs in - * string format (or null) - * - * @see #setPolicy - */ - public Set getPolicy() - { - if (policy == null) - { - return null; - } - - return Collections.unmodifiableSet(policy); - } - - /** - * Returns a copy of the pathToNames criterion. The - * X509Certificate must not include name constraints that - * would prohibit building a path to the specified names. If the value - * returned is null, no pathToNames check will be performed.
- *
- * If the value returned is not null, it is a - * Collection with one entry for each name to be included in - * the pathToNames criterion. Each entry is a List whose - * first entry is an Integer (the name type, 0-8) and whose - * second entry is a String or a byte array (the name, in - * string or ASN.1 DER encoded form, respectively). There can be multiple - * names of the same type. Note that the Collection returned - * may contain duplicate names (same name and name type).
- *
- * Each name in the Collection may be specified either as a - * String or as an ASN.1 encoded byte array. For more details - * about the formats used, see {@link #addPathToName(int type, String name) - * addPathToName(int type, String name)} and - * {@link #addPathToName(int type, byte [] name) addPathToName(int type, - * byte [] name)}.
- *
- * Note that a deep copy is performed on the Collection to - * protect against subsequent modifications. - * - * @return a Collection of names (or null) - * - * @see #setPathToNames - */ - public Collection getPathToNames() - { - if (pathToNames == null) - { - return null; - } - - Set returnPathToNames = new HashSet(); - List returnList; - Iterator iter = pathToNames.iterator(); - List obj; - - while (iter.hasNext()) - { - obj = (List)iter.next(); - returnList = new ArrayList(); - returnList.add(obj.get(0)); - if (obj.get(1) instanceof byte[]) - { - returnList.add(((byte[])obj.get(1)).clone()); - } - else - { - returnList.add(obj.get(1)); - } - returnPathToNames.add(returnList); - } - - return returnPathToNames; - } - - /** - * Return a printable representation of the CertSelector.
- *
- * TODO: implement output for currently unsupported options(name - * constraints)
- *
- * Uses {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Object ASN1Object}, - * {@link org.spongycastle.asn1.x509.KeyPurposeId KeyPurposeId} - * - * @return a String describing the contents of the - * CertSelector - */ - public String toString() - { - StringBuffer sb = new StringBuffer(); - sb.append("X509CertSelector: [\n"); - if (x509Cert != null) - { - sb.append(" Certificate: ").append(x509Cert).append('\n'); - } - if (serialNumber != null) - { - sb.append(" Serial Number: ").append(serialNumber).append('\n'); - } - if (issuerDN != null) - { - sb.append(" Issuer: ").append(getIssuerAsString()).append('\n'); - } - if (subjectDN != null) - { - sb.append(" Subject: ").append(getSubjectAsString()).append('\n'); - } - try - { - if (subjectKeyID != null) - { - ByteArrayInputStream inStream = new ByteArrayInputStream( - subjectKeyID); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); - sb.append(" Subject Key Identifier: ") - .append(ASN1Dump.dumpAsString(derObject)).append('\n'); - } - if (authorityKeyID != null) - { - ByteArrayInputStream inStream = new ByteArrayInputStream( - authorityKeyID); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); - sb.append(" Authority Key Identifier: ") - .append(ASN1Dump.dumpAsString(derObject)).append('\n'); - } - } - catch (IOException ex) - { - sb.append(ex.getMessage()).append('\n'); - } - if (certValid != null) - { - sb.append(" Certificate Valid: ").append(certValid).append('\n'); - } - if (privateKeyValid != null) - { - sb.append(" Private Key Valid: ").append(privateKeyValid) - .append('\n'); - } - if (subjectKeyAlgID != null) - { - sb.append(" Subject Public Key AlgID: ") - .append(subjectKeyAlgID).append('\n'); - } - if (subjectPublicKey != null) - { - sb.append(" Subject Public Key: ").append(subjectPublicKey) - .append('\n'); - } - if (keyUsage != null) - { - sb.append(" Key Usage: ").append(keyUsage).append('\n'); - } - if (keyPurposeSet != null) - { - sb.append(" Extended Key Usage: ").append(keyPurposeSet) - .append('\n'); - } - if (policy != null) - { - sb.append(" Policy: ").append(policy).append('\n'); - } - sb.append(" matchAllSubjectAltNames flag: ") - .append(matchAllSubjectAltNames).append('\n'); - if (subjectAltNamesByte != null) - { - sb.append(" SubjectAlternativNames: \n["); - Iterator iter = subjectAltNamesByte.iterator(); - List obj; - try - { - while (iter.hasNext()) - { - obj = (List)iter.next(); - ByteArrayInputStream inStream = new ByteArrayInputStream( - (byte[])obj.get(1)); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); - sb.append(" Type: ").append(obj.get(0)).append(" Data: ") - .append(ASN1Dump.dumpAsString(derObject)).append('\n'); - } - } - catch (IOException ex) - { - sb.append(ex.getMessage()).append('\n'); - } - sb.append("]\n"); - } - if (pathToNamesByte != null) - { - sb.append(" PathToNamesNames: \n["); - Iterator iter = pathToNamesByte.iterator(); - List obj; - try - { - while (iter.hasNext()) - { - obj = (List)iter.next(); - ByteArrayInputStream inStream = new ByteArrayInputStream( - (byte[])obj.get(1)); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); - sb.append(" Type: ").append(obj.get(0)).append(" Data: ") - .append(ASN1Dump.dumpAsString(derObject)).append('\n'); - } - } - catch (IOException ex) - { - sb.append(ex.getMessage()).append('\n'); - } - sb.append("]\n"); - } - sb.append(']'); - return sb.toString(); - } - - /** - * Decides whether a Certificate should be selected.
- *
- * TODO: implement missing tests (name constraints and path to names)
- *
- * Uses {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Sequence ASN1Sequence}, - * {@link org.spongycastle.asn1.ASN1ObjectIdentifier ASN1ObjectIdentifier}, - * {@link org.spongycastle.asn1.ASN1Object ASN1Object}, - * {@link org.spongycastle.asn1.DERGeneralizedTime DERGeneralizedTime}, - * {@link org.spongycastle.asn1.x509.X509Name X509Name}, - * {@link org.spongycastle.asn1.x509.X509Extensions X509Extensions}, - * {@link org.spongycastle.asn1.x509.ExtendedKeyUsage ExtendedKeyUsage}, - * {@link org.spongycastle.asn1.x509.KeyPurposeId KeyPurposeId}, - * {@link org.spongycastle.asn1.x509.SubjectPublicKeyInfo SubjectPublicKeyInfo}, - * {@link org.spongycastle.asn1.x509.AlgorithmIdentifier AlgorithmIdentifier} - * to access X509 extensions - * - * @param cert - * the Certificate to be checked - * - * @return true if the Certificate should be - * selected, false otherwise - */ - public boolean match(Certificate cert) - { - boolean[] booleanArray; - List tempList; - Iterator tempIter; - - if (!(cert instanceof X509Certificate)) - { - return false; - } - X509Certificate certX509 = (X509Certificate)cert; - - if (x509Cert != null && !x509Cert.equals(certX509)) - { - return false; - } - if (serialNumber != null - && !serialNumber.equals(certX509.getSerialNumber())) - { - return false; - } - try - { - if (issuerDNX509 != null) - { - if (!issuerDNX509.equals(PrincipalUtil - .getIssuerX509Principal(certX509), true)) - { - return false; - } - } - if (subjectDNX509 != null) - { - if (!subjectDNX509.equals(PrincipalUtil - .getSubjectX509Principal(certX509), true)) - { - return false; - } - } - } - catch (Exception ex) - { - return false; - } - if (subjectKeyID != null) - { - byte[] data = certX509 - .getExtensionValue(X509Extensions.SubjectKeyIdentifier - .getId()); - if (data == null) - { - return false; - } - try - { - ByteArrayInputStream inStream = new ByteArrayInputStream(data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - byte[] testData = ((ASN1OctetString)derInputStream.readObject()) - .getOctets(); - if (!Arrays.equals(subjectKeyID, testData)) - { - return false; - } - } - catch (IOException ex) - { - return false; - } - } - if (authorityKeyID != null) - { - byte[] data = certX509 - .getExtensionValue(X509Extensions.AuthorityKeyIdentifier - .getId()); - if (data == null) - { - return false; - } - try - { - ByteArrayInputStream inStream = new ByteArrayInputStream(data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - byte[] testData = ((ASN1OctetString)derInputStream.readObject()) - .getOctets(); - if (!Arrays.equals(authorityKeyID, testData)) - { - return false; - } - } - catch (IOException ex) - { - return false; - } - } - if (certValid != null) - { - if (certX509.getNotAfter() != null - && certValid.after(certX509.getNotAfter())) - { - return false; - } - if (certX509.getNotBefore() != null - && certValid.before(certX509.getNotBefore())) - { - return false; - } - } - if (privateKeyValid != null) - { - try - { - byte[] data = certX509 - .getExtensionValue(X509Extensions.PrivateKeyUsagePeriod - .getId()); - if (data != null) - { - ByteArrayInputStream inStream = new ByteArrayInputStream( - data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - inStream = new ByteArrayInputStream( - ((ASN1OctetString)derInputStream.readObject()) - .getOctets()); - derInputStream = new ASN1InputStream(inStream); - // TODO fix this, Sequence contains tagged objects - ASN1Sequence derObject = (ASN1Sequence)derInputStream - .readObject(); - ASN1GeneralizedTime derDate = DERGeneralizedTime - .getInstance(derObject.getObjectAt(0)); - SimpleDateFormat dateF = new SimpleDateFormat( - "yyyyMMddHHmmssZ"); - if (privateKeyValid.before(dateF.parse(derDate.getTime()))) - { - return false; - } - derDate = DERGeneralizedTime.getInstance(derObject - .getObjectAt(1)); - if (privateKeyValid.after(dateF.parse(derDate.getTime()))) - { - return false; - } - } - } - catch (Exception ex) - { - return false; - } - } - if (subjectKeyAlgID != null) - { - try - { - ByteArrayInputStream inStream = new ByteArrayInputStream( - certX509.getPublicKey().getEncoded()); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo( - (ASN1Sequence)derInputStream.readObject()); - AlgorithmIdentifier algInfo = publicKeyInfo.getAlgorithmId(); - if (!algInfo.getObjectId().equals(subjectKeyAlgID)) - { - return false; - } - } - catch (Exception ex) - { - return false; - } - } - if (subjectPublicKeyByte != null) - { - if (!Arrays.equals(subjectPublicKeyByte, certX509.getPublicKey() - .getEncoded())) - { - return false; - } - } - if (subjectPublicKey != null) - { - if (!subjectPublicKey.equals(certX509.getPublicKey())) - { - return false; - } - } - if (keyUsage != null) - { - booleanArray = certX509.getKeyUsage(); - if (booleanArray != null) - { - for (int i = 0; i < keyUsage.length; i++) - { - if (keyUsage[i] - && (booleanArray.length <= i || !booleanArray[i])) - { - return false; - } - } - } - } - if (keyPurposeSet != null && !keyPurposeSet.isEmpty()) - { - try - { - byte[] data = certX509 - .getExtensionValue(X509Extensions.ExtendedKeyUsage - .getId()); - if (data != null) - { - ByteArrayInputStream inStream = new ByteArrayInputStream( - data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.getInstance( - (ASN1Sequence)derInputStream.readObject()); - tempIter = keyPurposeSet.iterator(); - while (tempIter.hasNext()) - { - if (!extendedKeyUsage - .hasKeyPurposeId((KeyPurposeId)tempIter.next())) - { - return false; - } - } - } - } - catch (Exception ex) - { - return false; - } - } - if (minMaxPathLen != -1) - { - if (minMaxPathLen == -2 && certX509.getBasicConstraints() != -1) - { - return false; - } - if (minMaxPathLen >= 0 - && certX509.getBasicConstraints() < minMaxPathLen) - { - return false; - } - } - if (policyOID != null) - { - try - { - byte[] data = certX509 - .getExtensionValue(X509Extensions.CertificatePolicies - .getId()); - if (data == null) - { - return false; - } - if (!policyOID.isEmpty()) - { - ByteArrayInputStream inStream = new ByteArrayInputStream( - data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - inStream = new ByteArrayInputStream( - ((ASN1OctetString)derInputStream.readObject()) - .getOctets()); - derInputStream = new ASN1InputStream(inStream); - Enumeration policySequence = ((ASN1Sequence)derInputStream - .readObject()).getObjects(); - ASN1Sequence policyObject; - boolean test = false; - while (policySequence.hasMoreElements() && !test) - { - policyObject = (ASN1Sequence)policySequence - .nextElement(); - if (policyOID.contains(policyObject.getObjectAt(0))) - { - test = true; - } - } - if (!test) - { - return false; - } - } - } - catch (Exception ex) - { - ex.printStackTrace(); - return false; - } - } - if (subjectAltNamesByte != null) - { - try - { - byte[] data = certX509 - .getExtensionValue(X509Extensions.SubjectAlternativeName - .getId()); - if (data == null) - { - return false; - } - ByteArrayInputStream inStream = new ByteArrayInputStream(data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - inStream = new ByteArrayInputStream( - ((ASN1OctetString)derInputStream.readObject()) - .getOctets()); - derInputStream = new ASN1InputStream(inStream); - Enumeration altNamesSequence = ((ASN1Sequence)derInputStream - .readObject()).getObjects(); - ASN1TaggedObject altNameObject; - boolean test = false; - Set testSet = new HashSet(subjectAltNamesByte); - List testList; - ASN1Object derData; - ByteArrayOutputStream outStream; - DEROutputStream derOutStream; - while (altNamesSequence.hasMoreElements() && !test) - { - altNameObject = (ASN1TaggedObject)altNamesSequence - .nextElement(); - testList = new ArrayList(2); - testList.add(Integers.valueOf(altNameObject.getTagNo())); - derData = altNameObject.getObject(); - outStream = new ByteArrayOutputStream(); - derOutStream = new DEROutputStream(outStream); - derOutStream.writeObject(derData); - derOutStream.close(); - testList.add(outStream.toByteArray()); - - if (testSet.remove(testList)) - { - test = true; - } - - if (matchAllSubjectAltNames && !testSet.isEmpty()) - { - test = false; - } - } - if (!test) - { - return false; - } - } - catch (Exception ex) - { - ex.printStackTrace(); - return false; - } - } - - return true; - } - - /** - * Returns a copy of this object. - * - * @return the copy - */ - public Object clone() - { - try - { - X509CertSelector copy = (X509CertSelector)super.clone(); - if (issuerDN instanceof byte[]) - { - copy.issuerDN = ((byte[])issuerDN).clone(); - } - if (subjectDN instanceof byte[]) - { - copy.subjectDN = ((byte[])subjectDN).clone(); - } - if (subjectKeyID != null) - { - copy.subjectKeyID = (byte[])subjectKeyID.clone(); - } - if (authorityKeyID != null) - { - copy.authorityKeyID = (byte[])authorityKeyID.clone(); - } - if (subjectPublicKeyByte != null) - { - copy.subjectPublicKeyByte = (byte[])subjectPublicKeyByte - .clone(); - } - if (keyUsage != null) - { - copy.keyUsage = (boolean[])keyUsage.clone(); - } - if (keyPurposeSet != null) - { - copy.keyPurposeSet = new HashSet(keyPurposeSet); - } - if (policy != null) - { - copy.policy = new HashSet(policy); - copy.policyOID = new HashSet(); - Iterator iter = policyOID.iterator(); - while (iter.hasNext()) - { - copy.policyOID.add(new ASN1ObjectIdentifier( - ((ASN1ObjectIdentifier)iter.next()).getId())); - } - } - if (subjectAltNames != null) - { - copy.subjectAltNames = new HashSet(getSubjectAlternativeNames()); - Iterator iter = subjectAltNamesByte.iterator(); - List obj; - List cloneObj; - while (iter.hasNext()) - { - obj = (List)iter.next(); - cloneObj = new ArrayList(); - cloneObj.add(obj.get(0)); - cloneObj.add(((byte[])obj.get(1)).clone()); - copy.subjectAltNamesByte.add(cloneObj); - } - } - if (pathToNames != null) - { - copy.pathToNames = new HashSet(getPathToNames()); - Iterator iter = pathToNamesByte.iterator(); - List obj; - List cloneObj; - while (iter.hasNext()) - { - obj = (List)iter.next(); - cloneObj = new ArrayList(); - cloneObj.add(obj.get(0)); - cloneObj.add(((byte[])obj.get(1)).clone()); - copy.pathToNamesByte.add(cloneObj); - } - } - return copy; - } - catch (CloneNotSupportedException e) - { - /* Cannot happen */ - throw new InternalError(e.toString()); - } - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509Certificate.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509Certificate.java deleted file mode 100644 index d56f1c6f3..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509Certificate.java +++ /dev/null @@ -1,33 +0,0 @@ - -package java.security.cert; - -import java.math.BigInteger; -import java.security.Principal; -import java.util.Date; - -public abstract class X509Certificate extends Certificate -implements X509Extension -{ - protected X509Certificate() - { - super("X.509"); - } - - public abstract void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException; - public abstract void checkValidity(Date date) throws CertificateExpiredException, CertificateNotYetValidException; - public abstract int getBasicConstraints(); - public abstract Principal getIssuerDN(); - public abstract boolean[] getIssuerUniqueID(); - public abstract boolean[] getKeyUsage(); - public abstract Date getNotAfter(); - public abstract Date getNotBefore(); - public abstract BigInteger getSerialNumber(); - public abstract String getSigAlgName(); - public abstract String getSigAlgOID(); - public abstract byte[] getSigAlgParams(); - public abstract byte[] getSignature(); - public abstract Principal getSubjectDN(); - public abstract boolean[] getSubjectUniqueID(); - public abstract byte[] getTBSCertificate() throws CertificateEncodingException; - public abstract int getVersion(); -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509Extension.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509Extension.java deleted file mode 100644 index 20855be1e..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/cert/X509Extension.java +++ /dev/null @@ -1,12 +0,0 @@ - -package java.security.cert; - -import java.util.Set; - -public interface X509Extension -{ - public abstract Set getCriticalExtensionOIDs(); - public abstract byte[] getExtensionValue(String oid); - public abstract Set getNonCriticalExtensionOIDs(); - public abstract boolean hasUnsupportedCriticalExtension(); -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/interfaces/RSAMultiPrimePrivateCrtKey.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/interfaces/RSAMultiPrimePrivateCrtKey.java deleted file mode 100644 index 0fbb0fb17..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/interfaces/RSAMultiPrimePrivateCrtKey.java +++ /dev/null @@ -1,67 +0,0 @@ - -package java.security.interfaces; - -import java.math.BigInteger; -import java.security.spec.RSAOtherPrimeInfo; - -/** - * The interface to an RSA multi-prime private key, as defined in the - * PKCS#1 v2.1, using the Chinese Remainder Theorem (CRT) information values. - * - * @since 1.4 - * @see RSAPrivateKeySpec, RSAMultiPrimePrivateCrtKeySpec, RSAPrivateKey, - * RSAPrivateCrtKey - */ -public interface RSAMultiPrimePrivateCrtKey -extends RSAPrivateKey -{ - /** - * Returns the public exponent. - * - * @returns the public exponent. - */ - public BigInteger getPublicExponent(); - - /** - * Returns the primeP. - * - * @returns the primeP. - */ - public BigInteger getPrimeP(); - - /** - * Returns the primeQ. - * - * @returns the primeQ. - */ - public BigInteger getPrimeQ(); - - /** - * Returns the primeExponentP. - * - * @returns the primeExponentP. - */ - public BigInteger getPrimeExponentP(); - - /** - * Returns the primeExponentQ. - * - * @returns the primeExponentQ. - */ - public BigInteger getPrimeExponentQ(); - - /** - * Returns the crtCoefficient. - * - * @returns the crtCoefficient. - */ - public BigInteger getCrtCoefficient(); - - /** - * Returns the otherPrimeInfo or null if there are only two prime - * factors (p and q). - * - * @returns the otherPrimeInfo. - */ - public RSAOtherPrimeInfo[] getOtherPrimeInfo(); -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/interfaces/RSAPrivateCrtKey.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/interfaces/RSAPrivateCrtKey.java deleted file mode 100644 index 81855907c..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/interfaces/RSAPrivateCrtKey.java +++ /dev/null @@ -1,16 +0,0 @@ - -package java.security.interfaces; - -import java.math.BigInteger; - -public interface RSAPrivateCrtKey extends RSAPrivateKey -{ - public static final long serialVersionUID = 6034044314589513430L; - - public abstract BigInteger getCrtCoefficient(); - public abstract BigInteger getPrimeExponentP(); - public abstract BigInteger getPrimeExponentQ(); - public abstract BigInteger getPrimeP(); - public abstract BigInteger getPrimeQ(); - public abstract BigInteger getPublicExponent(); -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/interfaces/RSAPrivateKey.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/interfaces/RSAPrivateKey.java deleted file mode 100644 index 9b37eef93..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/interfaces/RSAPrivateKey.java +++ /dev/null @@ -1,13 +0,0 @@ - -package java.security.interfaces; - -import java.math.BigInteger; -import java.security.PrivateKey; - -public interface RSAPrivateKey extends PrivateKey -{ - public static final long serialVersionUID = 6034044314589513430L; - - public abstract BigInteger getModulus(); - public abstract BigInteger getPrivateExponent(); -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/interfaces/RSAPublicKey.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/interfaces/RSAPublicKey.java deleted file mode 100644 index 6ae00ec2c..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/interfaces/RSAPublicKey.java +++ /dev/null @@ -1,13 +0,0 @@ - -package java.security.interfaces; - -import java.math.BigInteger; -import java.security.PublicKey; - -public interface RSAPublicKey extends PublicKey -{ - public static final long serialVersionUID = 7187392471159151072L; - - public abstract BigInteger getModulus(); - public abstract BigInteger getPublicExponent(); -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/AlgorithmParameterSpec.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/AlgorithmParameterSpec.java deleted file mode 100644 index 37a03e9b2..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/AlgorithmParameterSpec.java +++ /dev/null @@ -1,6 +0,0 @@ - -package java.security.spec; - -public interface AlgorithmParameterSpec -{ -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/DSAParameterSpec.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/DSAParameterSpec.java deleted file mode 100644 index a3897f8a6..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/DSAParameterSpec.java +++ /dev/null @@ -1,34 +0,0 @@ - -package java.security.spec; - -import java.math.BigInteger; -import java.security.interfaces.DSAParams; - -public class DSAParameterSpec implements AlgorithmParameterSpec, DSAParams -{ - private BigInteger p; - private BigInteger q; - private BigInteger g; - - public DSAParameterSpec(BigInteger p, BigInteger q, BigInteger g) - { - this.p = p; - this.q = q; - this.g = g; - } - - public BigInteger getG() - { - return g; - } - - public BigInteger getP() - { - return p; - } - - public BigInteger getQ() - { - return q; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/DSAPrivateKeySpec.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/DSAPrivateKeySpec.java deleted file mode 100644 index ff5febef6..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/DSAPrivateKeySpec.java +++ /dev/null @@ -1,40 +0,0 @@ - -package java.security.spec; - -import java.math.BigInteger; - -public class DSAPrivateKeySpec implements KeySpec -{ - private BigInteger x; - private BigInteger p; - private BigInteger q; - private BigInteger g; - - public DSAPrivateKeySpec(BigInteger x, BigInteger p, BigInteger q, BigInteger g) - { - this.x = x; - this.p = p; - this.q = q; - this.g = g; - } - - public BigInteger getG() - { - return g; - } - - public BigInteger getP() - { - return p; - } - - public BigInteger getQ() - { - return q; - } - - public BigInteger getX() - { - return x; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/DSAPublicKeySpec.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/DSAPublicKeySpec.java deleted file mode 100644 index f8ca36792..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/DSAPublicKeySpec.java +++ /dev/null @@ -1,40 +0,0 @@ - -package java.security.spec; - -import java.math.BigInteger; - -public class DSAPublicKeySpec implements KeySpec -{ - private BigInteger y; - private BigInteger p; - private BigInteger q; - private BigInteger g; - - public DSAPublicKeySpec(BigInteger y, BigInteger p, BigInteger q, BigInteger g) - { - this.y = y; - this.p = p; - this.q = q; - this.g = g; - } - - public BigInteger getG() - { - return g; - } - - public BigInteger getP() - { - return p; - } - - public BigInteger getQ() - { - return q; - } - - public BigInteger getY() - { - return y; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/EncodedKeySpec.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/EncodedKeySpec.java deleted file mode 100644 index 7295460f0..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/EncodedKeySpec.java +++ /dev/null @@ -1,19 +0,0 @@ - -package java.security.spec; - -public abstract class EncodedKeySpec implements KeySpec -{ - private byte[] encodedKey; - - public EncodedKeySpec(byte[] encodedKey) - { - this.encodedKey = (byte[])encodedKey.clone(); - } - - public byte[] getEncoded() - { - return (byte[])encodedKey.clone(); - } - - public abstract String getFormat(); -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/InvalidKeySpecException.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/InvalidKeySpecException.java deleted file mode 100644 index cb29aee38..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/InvalidKeySpecException.java +++ /dev/null @@ -1,16 +0,0 @@ - -package java.security.spec; - -import java.security.GeneralSecurityException; - -public class InvalidKeySpecException extends GeneralSecurityException -{ - public InvalidKeySpecException() - { - } - - public InvalidKeySpecException(String msg) - { - super(msg); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/InvalidParameterSpecException.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/InvalidParameterSpecException.java deleted file mode 100644 index c8303edda..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/InvalidParameterSpecException.java +++ /dev/null @@ -1,16 +0,0 @@ - -package java.security.spec; - -import java.security.GeneralSecurityException; - -public class InvalidParameterSpecException extends GeneralSecurityException -{ - public InvalidParameterSpecException() - { - } - - public InvalidParameterSpecException(String msg) - { - super(msg); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/KeySpec.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/KeySpec.java deleted file mode 100644 index cfa7cb92f..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/KeySpec.java +++ /dev/null @@ -1,6 +0,0 @@ - -package java.security.spec; - -public interface KeySpec -{ -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/PKCS8EncodedKeySpec.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/PKCS8EncodedKeySpec.java deleted file mode 100644 index 10c5f66c2..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/PKCS8EncodedKeySpec.java +++ /dev/null @@ -1,20 +0,0 @@ - -package java.security.spec; - -public class PKCS8EncodedKeySpec extends EncodedKeySpec -{ - public PKCS8EncodedKeySpec(byte[] encodedKey) - { - super(encodedKey); - } - - public byte[] getEncoded() - { - return super.getEncoded(); - } - - public final String getFormat() - { - return "PKCS#8"; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/PSSParameterSpec.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/PSSParameterSpec.java deleted file mode 100644 index c4b4989cd..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/PSSParameterSpec.java +++ /dev/null @@ -1,45 +0,0 @@ - -package java.security.spec; - -/** - * This class specifies a parameter spec for RSA PSS encoding scheme, - * as defined in the PKCS#1 v2.1. - * - * @since 1.4 - * @see AlgorithmParameterSpec, Signature - */ -public class PSSParameterSpec - extends Object - implements AlgorithmParameterSpec -{ - private int saltLen; - - /** - * Creates a new PSSParameterSpec given the salt length as defined - * in PKCS#1. - * - * @param saltLen - the length of salt in bits to be used in PKCS#1 - * PSS encoding. - * @throws IllegalArgumentException - if saltLen is less than 0. - */ - public PSSParameterSpec(int saltLen) - { - if ( saltLen < 0 ) - { - throw new IllegalArgumentException("Salt length must be >= 0"); - } - - this.saltLen = saltLen; - } - - /** - * Returns the salt length in bits. - * - * @returns the salt length. - */ - public int getSaltLength() - { - return saltLen; - } -} - diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAKeyGenParameterSpec.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAKeyGenParameterSpec.java deleted file mode 100644 index 756c6c0fd..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAKeyGenParameterSpec.java +++ /dev/null @@ -1,35 +0,0 @@ -package java.security.spec; - -import java.math.BigInteger; - -/** - * specifies parameters to be used for the generation of - * a RSA key pair. - */ -public class RSAKeyGenParameterSpec - implements AlgorithmParameterSpec -{ - static BigInteger F0 = BigInteger.valueOf(3); - static BigInteger F4 = BigInteger.valueOf(65537); - - private int keysize; - private BigInteger publicExponent; - - public RSAKeyGenParameterSpec( - int keysize, - BigInteger publicExponent) - { - this.keysize = keysize; - this.publicExponent = publicExponent; - } - - public int getKeysize() - { - return keysize; - } - - public BigInteger getPublicExponent() - { - return publicExponent; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAMultiPrimePrivateCrtKeySpec.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAMultiPrimePrivateCrtKeySpec.java deleted file mode 100644 index 53c3a8a51..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAMultiPrimePrivateCrtKeySpec.java +++ /dev/null @@ -1,159 +0,0 @@ - -package java.security.spec; - -import java.math.BigInteger; - -/** - * This class specifies an RSA multi-prime private key, as defined in - * the PKCS#1 v2.1, using the Chinese Remainder Theorem (CRT) information - * values for efficiency. - * - * @since 1.4 - * @see Key, KeyFactory, KeySpec, PKCS8EncodedKeySpec, RSAPrivateKeySpec, - * RSAPublicKeySpec, RSAOtherPrimeInfo - */ -public class RSAMultiPrimePrivateCrtKeySpec - extends RSAPrivateKeySpec -{ - private BigInteger publicExponent; - private BigInteger privateExponent; - private BigInteger primeP; - private BigInteger primeQ; - private BigInteger primeExponentP; - private BigInteger primeExponentQ; - private BigInteger crtCoefficient; - private RSAOtherPrimeInfo[] otherPrimeInfo; - - /** - * Creates a new RSAMultiPrimePrivateCrtKeySpec given the modulus, - * publicExponent, privateExponent, primeP, primeQ, primeExponentP, - * primeExponentQ, crtCoefficient, and otherPrimeInfo as defined in - * PKCS#1 v2.1. - * - * Note that otherPrimeInfo is cloned when constructing this object. - * - * @param modulus - the modulus n. - * @param publicExponent - the public exponent e. - * @param privateExponent - the private exponent d. - * @param primeP - the prime factor p of n. - * @param primeQ - the prime factor q of n. - * @param primeExponentP - this is d mod (p-1). - * @param primeExponentQ - this is d mod (q-1). - * @param crtCoefficient - the Chinese Remainder Theorem coefficient q-1 - * mod p. - * @param otherPrimeInfo - triplets of the rest of primes, null can be - * specified if there are only two prime factors (p and q). - * @throws NullPointerException - if any of the parameters, i.e. modulus, - * publicExponent, privateExponent, primeP, primeQ, primeExponentP, - * primeExponentQ, crtCoefficient, is null. - * @throws IllegalArgumentException - if an empty, i.e. 0-length, - * otherPrimeInfo is specified. - */ - public RSAMultiPrimePrivateCrtKeySpec( - BigInteger modulus, - BigInteger publicExponent, - BigInteger privateExponent, - BigInteger primeP, - BigInteger primeQ, - BigInteger primeExponentP, - BigInteger primeExponentQ, - BigInteger crtCoefficient, - RSAOtherPrimeInfo[] otherPrimeInfo) - { - super(modulus, privateExponent); - - if ( publicExponent == null || primeP == null || primeQ == null - || primeExponentP == null || primeExponentQ == null - || crtCoefficient == null ) - { - throw new NullPointerException("Invalid null argument"); - } - - if ( otherPrimeInfo != null ) - { - if ( otherPrimeInfo.length == 0 ) - { - throw new IllegalArgumentException("Invalid length for otherPrimeInfo"); - } - - this.otherPrimeInfo = (RSAOtherPrimeInfo[])otherPrimeInfo.clone(); - } - } - - /** - * Returns the public exponent. - * - * @returns the public exponent. - */ - public BigInteger getPublicExponent() - { - return publicExponent; - } - - /** - * Returns the primeP. - * - * @returns the primeP. - */ - public BigInteger getPrimeP() - { - return primeP; - } - - /** - * Returns the primeQ. - * - * @returns the primeQ. - */ - public BigInteger getPrimeQ() - { - return primeQ; - } - - /** - * Returns the primeExponentP. - * - * @returns the primeExponentP. - */ - public BigInteger getPrimeExponentP() - { - return primeExponentP; - } - - /** - * Returns the primeExponentQ. - * - * @returns the primeExponentQ. - */ - public BigInteger getPrimeExponentQ() - { - return primeExponentQ; - } - - /** - * Returns the crtCofficient. - * - * @returns the crtCofficient. - */ - public BigInteger getCrtCoefficient() - { - return crtCoefficient; - } - - /** - * Returns a copy of the otherPrimeInfo or null if there are only - * two prime factors (p and q). - * - * @returns the otherPrimeInfo. - */ - public RSAOtherPrimeInfo[] getOtherPrimeInfo() - { - if ( otherPrimeInfo != null ) - { - return (RSAOtherPrimeInfo[])otherPrimeInfo.clone(); - } - - return null; - } -} - diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAOtherPrimeInfo.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAOtherPrimeInfo.java deleted file mode 100644 index 4d0e1468e..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAOtherPrimeInfo.java +++ /dev/null @@ -1,80 +0,0 @@ - -package java.security.spec; - -import java.math.BigInteger; - -/** - * This class represents the triplet (prime, exponent, and coefficient) - * inside RSA's OtherPrimeInfo structure, as defined in the PKCS#1 v2.1. - * The ASN.1 syntax of RSA's OtherPrimeInfo is as follows: - * - *
- * OtherPrimeInfo ::= SEQUENCE {
- *    prime INTEGER,
- *    exponent INTEGER,
- *    coefficient INTEGER
- * }
- * 
- */ -public class RSAOtherPrimeInfo -extends Object -{ - private BigInteger prime; - private BigInteger primeExponent; - private BigInteger crtCoefficient; - - /** - * Creates a new RSAOtherPrimeInfo given the prime, primeExponent, - * and crtCoefficient as defined in PKCS#1. - * - * @param prime - the prime factor of n. - * @param primeExponent - the exponent. - * @param crtCoefficient - the Chinese Remainder Theorem coefficient. - * @throws NullPointerException - if any of the parameters, i.e. prime, - * primeExponent, crtCoefficient, is null. - */ - public RSAOtherPrimeInfo( - BigInteger prime, - BigInteger primeExponent, - BigInteger crtCoefficient) - { - if ( prime == null || primeExponent == null || crtCoefficient == null ) - { - throw new NullPointerException("Null parameter"); - } - - this.prime = prime; - this.primeExponent = primeExponent; - this.crtCoefficient = crtCoefficient; - } - - /** - * Returns the prime. - * - * @returns the prime. - */ - public final BigInteger getPrime() - { - return prime; - } - - /** - * Returns the prime's exponent. - * - * @returns the primeExponent. - */ - public final BigInteger getExponent() - { - return primeExponent; - } - - /** - * Returns the prime's crtCoefficient. - * - * @returns the crtCoefficient. - */ - public final BigInteger getCrtCoefficient() - { - return crtCoefficient; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAPrivateCrtKeySpec.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAPrivateCrtKeySpec.java deleted file mode 100644 index b9d450ad7..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAPrivateCrtKeySpec.java +++ /dev/null @@ -1,64 +0,0 @@ - -package java.security.spec; - -import java.math.BigInteger; - -public class RSAPrivateCrtKeySpec extends RSAPrivateKeySpec -{ - private BigInteger publicExponent; - private BigInteger primeP; - private BigInteger primeQ; - private BigInteger primeExponentP; - private BigInteger primeExponentQ; - private BigInteger crtCoefficient; - - public RSAPrivateCrtKeySpec( - BigInteger modulus, - BigInteger publicExponent, - BigInteger privateExponent, - BigInteger primeP, - BigInteger primeQ, - BigInteger primeExponentP, - BigInteger primeExponentQ, - BigInteger crtCoefficient) - { - super(modulus, privateExponent); - - this.publicExponent = publicExponent; - this.primeP = primeP; - this.primeQ = primeQ; - this.primeExponentP = primeExponentP; - this.primeExponentQ = primeExponentQ; - this.crtCoefficient = crtCoefficient; - } - - public BigInteger getCrtCoefficient() - { - return crtCoefficient; - } - - public BigInteger getPrimeExponentP() - { - return primeExponentP; - } - - public BigInteger getPrimeExponentQ() - { - return primeExponentQ; - } - - public BigInteger getPrimeP() - { - return primeP; - } - - public BigInteger getPrimeQ() - { - return primeQ; - } - - public BigInteger getPublicExponent() - { - return publicExponent; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAPrivateKeySpec.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAPrivateKeySpec.java deleted file mode 100644 index 88dc4c159..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAPrivateKeySpec.java +++ /dev/null @@ -1,28 +0,0 @@ - -package java.security.spec; - -import java.math.BigInteger; - -public class RSAPrivateKeySpec extends Object implements KeySpec -{ - private BigInteger modulus; - private BigInteger privateExponent; - - public RSAPrivateKeySpec( - BigInteger modulus, - BigInteger privateExponent) - { - this.modulus = modulus; - this.privateExponent = privateExponent; - } - - public BigInteger getModulus() - { - return modulus; - } - - public BigInteger getPrivateExponent() - { - return privateExponent; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAPublicKeySpec.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAPublicKeySpec.java deleted file mode 100644 index b3a367e7e..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/RSAPublicKeySpec.java +++ /dev/null @@ -1,28 +0,0 @@ - -package java.security.spec; - -import java.math.BigInteger; - -public class RSAPublicKeySpec extends Object implements KeySpec -{ - private BigInteger modulus; - private BigInteger publicExponent; - - public RSAPublicKeySpec( - BigInteger modulus, - BigInteger publicExponent) - { - this.modulus = modulus; - this.publicExponent = publicExponent; - } - - public BigInteger getModulus() - { - return modulus; - } - - public BigInteger getPublicExponent() - { - return publicExponent; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/X509EncodedKeySpec.java b/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/X509EncodedKeySpec.java deleted file mode 100644 index 1d095b11d..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/security/spec/X509EncodedKeySpec.java +++ /dev/null @@ -1,20 +0,0 @@ - -package java.security.spec; - -public class X509EncodedKeySpec extends EncodedKeySpec -{ - public X509EncodedKeySpec(byte[] encodedKey) - { - super(encodedKey); - } - - public byte[] getEncoded() - { - return super.getEncoded(); - } - - public final String getFormat() - { - return "X.509"; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/util/AbstractCollection.java b/extern/spongycastle/core/src/main/jdk1.1/java/util/AbstractCollection.java deleted file mode 100644 index 0ea61b772..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/util/AbstractCollection.java +++ /dev/null @@ -1,242 +0,0 @@ -package java.util; - -import java.lang.reflect.Array; -/** - * Title: - * Description: - * Copyright: Copyright (c) 2001 - * Company: - * @version 1.0 - */ - - -public abstract class AbstractCollection implements Collection - { - protected AbstractCollection() - { - } - - public abstract Iterator iterator(); - - public abstract int size(); - - public boolean isEmpty() - { - return size()==0; - } - - public boolean contains(Object o) - { - Iterator it=iterator(); - while(it.hasNext()) - { - Object e=it.next(); - if(o==null) - { - if(e==null) - return true; - } - else - { - if(o.equals(e)) - return true; - } - } - return false; - } - - public Object[] toArray() - { - Object[] arObjects=new Object[size()]; - Iterator it=iterator(); - int i=0; - while(it.hasNext()) - { - arObjects[i++]=it.next(); - } - return arObjects; - } - - public Object[] toArray(Object[] a) throws NullPointerException,ArrayStoreException - //TODO: Check if this is realy compatible to SUN!!! - { - if(a==null) - throw new NullPointerException(); - - if (isEmpty()) return a; - Object[] arObjects=null; - int size=size(); - if(a.lengthsize) - arObjects[size]=null; - - } - - Iterator it=iterator(); - int i=0; - while(it.hasNext()) - { - Object o=it.next(); - arObjects[i++]=o; - } - return arObjects; - } - - public boolean add(Object o) throws UnsupportedOperationException,NullPointerException,ClassCastException,IllegalArgumentException - { - throw new UnsupportedOperationException(); - } - - public boolean remove(Object o) throws UnsupportedOperationException - { - Iterator it=iterator(); - while(it.hasNext()) - { - Object e=it.next(); - if(o==null) - { - if(e==null) - { - try - { - it.remove(); - } - catch(UnsupportedOperationException ue) - { - throw ue; - } - return true; - } - } - else - { - if(o.equals(e)) - { - try - { - it.remove(); - } - catch(UnsupportedOperationException ue) - { - throw ue; - } - return true; - } - } - } - return false; - } - - public boolean containsAll(Collection c) - { - Iterator it=c.iterator(); - while(it.hasNext()) - { - if(!contains(it.next())) - return false; - } - return true; - } - - public boolean addAll(Collection c) throws UnsupportedOperationException - { - Iterator it=c.iterator(); - boolean ret=false; - while(it.hasNext()) - { - try - { - ret|=add(it.next()); - } - catch(UnsupportedOperationException ue) - { - throw ue; - } - } - return ret; - } - - public boolean removeAll(Collection c) throws UnsupportedOperationException - { - Iterator it=iterator(); - boolean ret=false; - while(it.hasNext()) - { - if(c.contains(it.next())) - try - { - it.remove(); - ret=true; - } - catch(UnsupportedOperationException ue) - { - throw ue; - } - } - return ret; - } - - public boolean retainAll(Collection c) throws UnsupportedOperationException - { - Iterator it=iterator(); - boolean ret=false; - while(it.hasNext()) - { - if(!c.contains(it.next())) - try - { - it.remove(); - ret=true; - } - catch(UnsupportedOperationException ue) - { - throw ue; - } - } - return ret; - } - - public void clear() throws UnsupportedOperationException - { - Iterator it=iterator(); - while(it.hasNext()) - { - try - { - it.next(); - it.remove(); - } - catch(UnsupportedOperationException ue) - { - throw ue; - } - } - } - - public String toString() - { - String ret="["; - Iterator it=iterator(); - if(it.hasNext()) - ret+=String.valueOf(it.next()); - while(it.hasNext()) - { - ret+=", "; - ret+=String.valueOf(it.next()); - - } - ret+="]"; - return ret; - } - -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/util/AbstractList.java b/extern/spongycastle/core/src/main/jdk1.1/java/util/AbstractList.java deleted file mode 100644 index 363b57aec..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/util/AbstractList.java +++ /dev/null @@ -1,281 +0,0 @@ -package java.util; - -/** - * Title: - * Description: - * Copyright: Copyright (c) 2001 - * Company: - * @version 1.0 - */ - -public abstract class AbstractList extends AbstractCollection implements List - -{ - protected AbstractList al = this; - - - protected AbstractList() - { - } - - public boolean add(Object o) throws UnsupportedOperationException, ClassCastException, IllegalArgumentException - { - try - { - add(size(),o); - return true; - } - catch(UnsupportedOperationException ue) - { - throw ue; - } - } - - public abstract Object get(int index) throws IndexOutOfBoundsException; - - public Object set(int index,Object element) throws UnsupportedOperationException, ClassCastException, IllegalArgumentException, IndexOutOfBoundsException - { - throw new UnsupportedOperationException(); - } - - public void add(int index,Object element) throws UnsupportedOperationException, ClassCastException, IllegalArgumentException, IndexOutOfBoundsException - { - throw new UnsupportedOperationException(); - } - - public Object remove(int index) throws UnsupportedOperationException, IndexOutOfBoundsException - { - Object o = get(index); - - removeRange(index,index+1); - return o; - } - - public int indexOf(Object o) - { - ListIterator li = listIterator(); - Object e; - while(li.hasNext()) - { - int index=li.nextIndex(); - e=li.next(); - System.out.println(e); - if(o==null) - { - if(e==null) - return index; - } - else - { - if(o.equals(e)) - return index; - } - } - return -1; - } - - public int lastIndexOf(Object o) - { - ListIterator li=listIterator(size()); - while(li.hasPrevious()) - { - int index=li.previousIndex(); - Object e=li.previous(); - if(o==null) - { - if(e==null) - return index; - } - else - { - if(o.equals(e)) - return index; - } - } - return -1; - } - - public void clear() throws UnsupportedOperationException - { - try - { - removeRange(0,size()); - } - catch(UnsupportedOperationException ue) - { - throw ue; - } - } - - public boolean addAll(int index,Collection c) throws UnsupportedOperationException, ClassCastException, IllegalArgumentException, IndexOutOfBoundsException - { - Iterator it=c.iterator(); - boolean ret=false; - while(it.hasNext()) - { - try - { - add(index++,it.next()); - ret=true; - } - catch(UnsupportedOperationException ue) - { - throw ue; - } - } - return ret; - } - - public Iterator iterator() - { - return new AbstractListIterator(this,0); - } - - public ListIterator listIterator() - { - return listIterator(0); - } - - public ListIterator listIterator(int index) throws IndexOutOfBoundsException - { - if(index<0||index>size()) throw new IndexOutOfBoundsException(); - return new AbstractListListIterator(this,index); - } - - public List subList(int fromIndex,int toIndex) throws IndexOutOfBoundsException,IllegalArgumentException - { - if(fromIndex < 0 || toIndex > size()) - throw new IndexOutOfBoundsException(); - if(fromIndex>toIndex) - throw new IllegalArgumentException(); - return (List) new Sublist(this,fromIndex,toIndex); - } - - public boolean equals(Object o) - { - if(o==this) - return true; - if(!(o instanceof List)) - return false; - Iterator it1=iterator(); - Iterator it2=((List)o).iterator(); - while(it1.hasNext()) - { - if(!it2.hasNext()) - return false; - Object e1=it1.next(); - Object e2=it2.next(); - if(e1==null) - { - if(e2!=null) - return false; - } - if(!e1.equals(e2)) - return false; - } - return true; - } - - public int hashCode() - { - int hashCode = 1; - Iterator it = iterator(); - while (it.hasNext()) - { - Object o = it.next(); - hashCode = 31*hashCode + (o==null ? 0 : o.hashCode()); - } - return hashCode; - } - - protected void removeRange(int fromIndex,int toIndex) - { - System.out.println("breakpoint 1"); - if(fromIndex==toIndex) return; - System.out.println("breakpoint 2"); - ListIterator li=listIterator(fromIndex); - System.out.println("breakpoint 3"); - int i=fromIndex; - do - { - li.next(); - li.remove(); - i++; - }while(li.hasNext()&&i0; - } - - public Object previous()// throws NoSuchElementException; - { - return m_al.get(--m_nextIndex); - } - - public int nextIndex() - { - return m_nextIndex; - } - - public int previousIndex() - { - return m_nextIndex-1; - } - - public void set(Object o) //throws UnsupportedOperationException, ClassCastException, IllegalArgumentException,IllegalStateException; - { - m_al.set(m_nextIndex-1,o); - } - - public void add(Object o)// throws UnsupportedOperationException, ClassCastException, IllegalArgumentException; - { - m_al.add(m_nextIndex-1,o); - } - } - - -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/util/AbstractMap.java b/extern/spongycastle/core/src/main/jdk1.1/java/util/AbstractMap.java deleted file mode 100644 index d5b2e02e1..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/util/AbstractMap.java +++ /dev/null @@ -1,164 +0,0 @@ -package java.util; - -/************* - * Title: - * Description: - * Copyright: Copyright (c) 2001 - * Company: - * @version 1.0 - */ - -public abstract class AbstractMap implements Map{ - - protected AbstractMap() - { - } - - public int size() - { - return entrySet().size(); - } - - public boolean isEmpty() - { - return size()==0; - } - - public boolean containsValue(Object value) - { - Iterator it=entrySet().iterator(); - while(it.hasNext()) - { - Map.Entry v=(Map.Entry)it.next(); - if(value==null) - { - if(v.getValue()==null) - return true; - } - else - { - if(value.equals(v.getValue())) - return true; - } - } - return false; - } - - public boolean containsKey(Object key) throws ClassCastException,NullPointerException - { - Iterator it=entrySet().iterator(); - while(it.hasNext()) - { - Map.Entry v=(Map.Entry)it.next(); - if(key==null) - { - if(v.getKey()==null) - return true; - } - else - { - if(key.equals(v.getKey())) - return true; - } - } - return false; - } - - public Object get(Object key)throws ClassCastException,NullPointerException - { - Iterator it=entrySet().iterator(); - while(it.hasNext()) - { - Map.Entry v=(Map.Entry)it.next(); - if(key==null) - { - if(v.getKey()==null) - return v.getValue(); - } - else - { - if(key.equals(v.getKey())) - return v.getValue(); - } - } - return null; - } - - public Object put(Object key,Object value) throws UnsupportedOperationException - { - throw new UnsupportedOperationException(); - } - - public Object remove(Object key) - { - Iterator it=entrySet().iterator(); - Object o=null; - while(it.hasNext()) - { - Map.Entry v=(Map.Entry)it.next(); - if(key==null) - { - if(v.getKey()==null) - { - o=v.getValue(); - it.remove(); - return o; - } - } - else - { - if(key.equals(v.getKey())) - { - o=v.getValue(); - it.remove(); - return o; - } - } - } - return null; - } - - public void putAll(Map t) - { - Iterator it=t.entrySet().iterator(); - while(it.hasNext()) - { - Map.Entry v=(Map.Entry)it.next(); - put(v.getKey(),v.getValue()); - } - } - - public void clear() - { - entrySet().clear(); - } - - public Set keySet() - { - throw new UnsupportedOperationException("no keySet in AbstractMap()"); - } - - public Collection values() - { - throw new UnsupportedOperationException("no values in AbstractMap()"); - } - - public abstract Set entrySet(); - - public boolean equals(Object o) - { - throw new UnsupportedOperationException("no equals in AbstractMap()"); - } - - public int hashCode() - { - throw new UnsupportedOperationException("no hashCode in AbstractMap()"); - } - - public String toString() - { - throw new UnsupportedOperationException("no toString in AbstractMap()"); - } - - -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/util/AbstractSet.java b/extern/spongycastle/core/src/main/jdk1.1/java/util/AbstractSet.java deleted file mode 100644 index 45bbb22f6..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/util/AbstractSet.java +++ /dev/null @@ -1,42 +0,0 @@ -package java.util; - -/** - * Title: - * Description: - * Copyright: Copyright (c) 2001 - * Company: - * @version 1.0 - */ - -public abstract class AbstractSet extends AbstractCollection implements Set - { - protected AbstractSet() - { - } - - public boolean equals(Object o) - { - if(this==o) - return true; - if(o==null) - return false; - if(!(o instanceof Set)) - return false; - if(((Set)o).size()!=size()) - return false; - return containsAll((Collection)o); - } - - public int hashCode() - { - int hashCode=0; - Iterator it=iterator(); - while(it.hasNext()) - { - Object o=it.next(); - if(o!=null) - hashCode+=o.hashCode(); - } - return hashCode; - } - } diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/util/ArrayList.java b/extern/spongycastle/core/src/main/jdk1.1/java/util/ArrayList.java deleted file mode 100644 index 7e3cbbc3d..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/util/ArrayList.java +++ /dev/null @@ -1,107 +0,0 @@ -package java.util; - -public class ArrayList extends AbstractList - implements List - { - Vector m_Vector=null; - - public ArrayList() - { - m_Vector=new Vector(); - } - - public ArrayList(Collection c) - { - m_Vector=new Vector((int)(c.size()*1.1)); - addAll(c); - } - - public ArrayList(int initialCapacity) - { - m_Vector=new Vector(initialCapacity); - } - - public void trimToSize() - { - m_Vector.trimToSize(); - } - - public void ensureCapacity(int minCapacity) - { - m_Vector.ensureCapacity(minCapacity); - } - - public int size() - { - return m_Vector.size(); - } - - public boolean contains(Object elem) - { - return m_Vector.contains(elem); - } - - public int indexOf(Object elem) - { - return m_Vector.indexOf(elem); - } - - public int lastIndexOf(Object elem) - { - return m_Vector.lastIndexOf(elem); - } - - public Object clone() - { - ArrayList al=new ArrayList(); - al.m_Vector=(Vector)m_Vector.clone(); - return al; - } - - public Object[] toArray() - { - Object[] o=new Object[m_Vector.size()]; - m_Vector.copyInto(o); - return o; - } - - public Object get(int index) - { - return m_Vector.elementAt(index); - } - - public Object set(int index,Object elem) - { - Object o=m_Vector.elementAt(index); - m_Vector.setElementAt(elem,index); - return o; - } - - public boolean add(Object o) - { - m_Vector.addElement(o); - return true; - } - - public void add(int index,Object elem) - { - m_Vector.insertElementAt(elem,index); - } - - public Object remove(int index) - { - Object o=m_Vector.elementAt(index); - m_Vector.removeElementAt(index); - return o; - } - - public void clear() - { - m_Vector.removeAllElements(); - } - - - - - - } diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/util/Arrays.java b/extern/spongycastle/core/src/main/jdk1.1/java/util/Arrays.java deleted file mode 100644 index 0591e8d7f..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/util/Arrays.java +++ /dev/null @@ -1,90 +0,0 @@ -package java.util; - -public class Arrays -{ - - private Arrays() {} - - public static void fill(byte[] ret, byte v) - { - for (int i = 0; i != ret.length; i++) - { - ret[i] = v; - } - } - - public static boolean equals(byte[] a, byte[] a2) { - if (a==a2) - return true; - if (a==null || a2==null) - return false; - - int length = a.length; - if (a2.length != length) - return false; - - for (int i=0; i index) return true; - return false; - } - - public Object next() - { - Object o = vec.elementAt(index); - if (o==Nullobject) o=null; - index++; - return o; - - } - - public void remove() - { - index--; - vec.removeElementAt(index); - } - - } - - ////////////////////////////////////////////////////////////// - ///// innere Klasse Entry //////////////////////////////////// - ////////////////////////////////////////////////////////////// - - - class Entry implements Map.Entry - { - public Object key=null; - public Object value=null; - - public Entry(Object ke,Object valu) - { - key = ke; - value = valu; - } - public boolean equals(Object o) - { - if (value == ((Entry)o).value && key == ((Entry)o).key ) return true; - else return false; - - } - - public Object getValue() - { - return value; - } - - public Object getKey() - { - return (Object)key; - } - - public int hashCode() - { - return value.hashCode() + key.hashCode(); - - } - - public Object setValue(Object valu) - { - value = (String)valu; - return this; - } - } - - //////////////////////////////////////////////////////////////////// - - private Hashtable m_HashTable=null; - private Null Nullobject = null; - - public HashMap() - { - Nullobject = new Null(); - m_HashTable=new Hashtable(); - } - - public HashMap(int initialCapacity) - { - Nullobject = new Null(); - m_HashTable=new Hashtable(initialCapacity); - } - - public HashMap(int initialCapacity, float loadFactor) - { - Nullobject = new Null(); - m_HashTable=new Hashtable(initialCapacity, loadFactor); - } - - public HashMap(Map t) - { - Nullobject = new Null(); - m_HashTable=new Hashtable(); - this.putAll(t); - } - - public void clear() - { - m_HashTable.clear(); - } - - public Object clone() - { - HashMap hm=new HashMap(); - hm.m_HashTable=(Hashtable)m_HashTable.clone(); - return hm; - } - - public boolean containsKey(Object key) - { - if (key == null) key = Nullobject; - boolean b = m_HashTable.containsKey(key); - return b; - - } - - public boolean containsValue(Object value) - { - if (value == null ) value = Nullobject; - boolean b = m_HashTable.contains(value); - return b; - } - - public Set entrySet() - { - - Object Key = null; - ISet s = new ISet(); - Enumeration enum = m_HashTable.keys(); - while (enum.hasMoreElements()) - { - Key = enum.nextElement(); - s.add(new Entry(Key,m_HashTable.get(Key))); - } - return s; - } - - public Object get(Object key) - { - - if (key==null) key= Nullobject; - - Object o = m_HashTable.get(key); - - if (o == Nullobject) o=null; - - return o; - } - - public boolean isEmpty() - { - return m_HashTable.isEmpty(); - } - - public Set keySet() - { - ISet s=new ISet(); - Enumeration enum = m_HashTable.keys(); - - while (enum.hasMoreElements()) - { - s.add(enum.nextElement()); - } - - return s; - } - - public Object put(Object key, Object value) - { - if (key==null) key=Nullobject; - if (value==null) value = Nullobject; - return m_HashTable.put(key,value); - } - - public void putAll(Map m) - { - Iterator it = m.entrySet().iterator(); - Object key=null; - Object value=null; - - while (it.hasNext()) - { - Map.Entry me = (Map.Entry)it.next(); - if (me.getKey() == null) key = Nullobject; - else key= me.getKey(); - if (me.getValue()==null) value = Nullobject; - else value = me.getValue(); - m_HashTable.put(key,value); - } - } - - public Object remove(Object key) - { - return m_HashTable.remove(key); - } - - public int size() - { - return m_HashTable.size(); - } - - public Collection values() - { - - ISet s=new ISet(); - Enumeration enum = m_HashTable.keys(); - - while (enum.hasMoreElements()) - { - Object Key = enum.nextElement(); - //s.add(((Map.Entry)m_HashTable.get(Key)).getValue()); - s.add(m_HashTable.get(Key)); - } - return s; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/util/HashSet.java b/extern/spongycastle/core/src/main/jdk1.1/java/util/HashSet.java deleted file mode 100644 index 5721cd20e..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/util/HashSet.java +++ /dev/null @@ -1,83 +0,0 @@ -package java.util; - -import java.io.*; -///*sk13*/import java.util.Hashtable; - -public class HashSet extends /*sk13*/AbstractSet - /*sk13*/ /*extends Hashmap*/ - -{ - private HashMap m_HashMap=null; - - public HashSet() - { - m_HashMap=new HashMap(); - - } - - public HashSet(Collection c) - { - m_HashMap=new HashMap(Math.max(11,c.size()*2)); - addAll(c); - - } - - public HashSet(int initialCapacity, float loadFactor) - { - m_HashMap=new HashMap(initialCapacity,loadFactor); - - } - - public HashSet(int initialCapacity) - { - m_HashMap=new HashMap(initialCapacity); - - } - - public Iterator iterator() - { - return (m_HashMap.keySet()).iterator(); - } - - public int size() - { - return m_HashMap.size(); - } - - public boolean contains(Object o) - { - return m_HashMap.containsKey(o); - } - - public boolean add(Object o) - { - if (!m_HashMap.containsValue(o)) - { - m_HashMap.put(o, o); - - return true; - - } - - return false; - } - - public boolean remove(Object o) - { - return (m_HashMap.remove(o)!=null); - } - - public void clear() - { - m_HashMap.clear(); - } - - - public Object clone() - { - HashSet hs=new HashSet(); - hs.m_HashMap=(HashMap)m_HashMap.clone(); - return hs; - } - -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/util/Iterator.java b/extern/spongycastle/core/src/main/jdk1.1/java/util/Iterator.java deleted file mode 100644 index 9f977fe8c..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/util/Iterator.java +++ /dev/null @@ -1,9 +0,0 @@ - -package java.util; - -public interface Iterator -{ - public abstract boolean hasNext(); - public abstract Object next() throws NoSuchElementException; - public abstract void remove() throws UnsupportedOperationException,IllegalStateException; -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/util/List.java b/extern/spongycastle/core/src/main/jdk1.1/java/util/List.java deleted file mode 100644 index ee5896ea8..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/util/List.java +++ /dev/null @@ -1,15 +0,0 @@ -package java.util; - -public interface List extends Collection - { - void add(int index, Object element)throws UnsupportedOperationException,ClassCastException,IllegalArgumentException,IndexOutOfBoundsException; - boolean addAll(int index, Collection c) throws UnsupportedOperationException,ClassCastException,IllegalArgumentException,IndexOutOfBoundsException; - Object get(int index) throws IndexOutOfBoundsException; - int indexOf(Object o); - int lastIndexOf(Object o); - ListIterator listIterator(); - ListIterator listIterator(int index)throws IndexOutOfBoundsException; - Object remove(int index)throws UnsupportedOperationException,IndexOutOfBoundsException; - Object set(int index, Object element) throws UnsupportedOperationException,ClassCastException,IllegalArgumentException,IndexOutOfBoundsException; - List subList(int fromIndex, int toIndex) throws IndexOutOfBoundsException; - } diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/util/ListIterator.java b/extern/spongycastle/core/src/main/jdk1.1/java/util/ListIterator.java deleted file mode 100644 index 15e17896e..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/util/ListIterator.java +++ /dev/null @@ -1,19 +0,0 @@ -package java.util; - -/** - * Title: - * Description: - * Copyright: Copyright (c) 2001 - * Company: - * @version 1.0 - */ - -public interface ListIterator extends Iterator - { - public boolean hasPrevious(); - public Object previous() throws NoSuchElementException; - public int nextIndex(); - public int previousIndex(); - public void set(Object o) throws UnsupportedOperationException, ClassCastException, IllegalArgumentException,IllegalStateException; - public void add(Object o) throws UnsupportedOperationException, ClassCastException, IllegalArgumentException; - } diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/util/Map.java b/extern/spongycastle/core/src/main/jdk1.1/java/util/Map.java deleted file mode 100644 index e0040a383..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/util/Map.java +++ /dev/null @@ -1,37 +0,0 @@ -package java.util; - -/** - * Title: - * Description: - * Copyright: Copyright (c) 2001 - * Company: - * @version 1.0 - */ - -public interface Map { - - public static interface Entry - { - public Object getKey(); - public Object getValue(); - public Object setValue(Object value) throws UnsupportedOperationException, ClassCastException,IllegalArgumentException,NullPointerException; - public boolean equals(Object o); - public int hashCode(); - }; - - public int size(); - public boolean isEmpty(); - public boolean containsKey(Object Key) throws ClassCastException,NullPointerException; - public boolean containsValue(Object value); - public Object get(Object key)throws ClassCastException,NullPointerException; - public Object put(Object key,Object value)throws UnsupportedOperationException, ClassCastException,IllegalArgumentException,NullPointerException; - public Object remove(Object key)throws UnsupportedOperationException; - public void putAll(Map t)throws UnsupportedOperationException, ClassCastException,IllegalArgumentException,NullPointerException; - public void clear()throws UnsupportedOperationException; - public Set keySet(); - public Collection values(); - public Set entrySet(); - public boolean equals(Object o); - public int hashCode(); - - } diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/util/Set.java b/extern/spongycastle/core/src/main/jdk1.1/java/util/Set.java deleted file mode 100644 index e312d6b83..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/util/Set.java +++ /dev/null @@ -1,26 +0,0 @@ - -package java.util; - -public interface Set extends Collection - { - - public int size(); - public boolean isEmpty(); - public boolean contains(Object o); - public Iterator iterator(); - public Object[] toArray(); - public Object[] toArray(Object[] a); - public boolean add(Object o); - public boolean remove(Object o); - public boolean containsAll(Collection c); - public boolean addAll(Collection c); - public boolean retainAll(Collection c); - public boolean removeAll(Collection c); - public void clear(); - public boolean equals(Object o); - public int hashCode(); - - - - - } diff --git a/extern/spongycastle/core/src/main/jdk1.1/java/util/Sublist.java b/extern/spongycastle/core/src/main/jdk1.1/java/util/Sublist.java deleted file mode 100644 index 3f1a4a1bd..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/java/util/Sublist.java +++ /dev/null @@ -1,125 +0,0 @@ -package java.util; - -/** - * Title: - * Description: - * Copyright: Copyright (c) 2001 - * Company: - * @version 1.0 - */ - -public class Sublist extends AbstractList - - { - AbstractList m_al=null; - int m_fromIndex=0; - int m_toIndex=0; - int size=0; - - public Sublist(AbstractList ali,int fromIndex,int toIndex) - { - m_al=ali; - m_toIndex=toIndex; - m_fromIndex=fromIndex; - size = size(); - } - public Object set(int index,Object o) - { - if (index < size) - { - o = m_al.set(index+m_fromIndex,o); - if (o != null) - { - size++; - m_toIndex++; - } - return o; - } - else throw new IndexOutOfBoundsException(); - } - - public Object get(int index) throws IndexOutOfBoundsException - { - if (index < size) return m_al.get(index+m_fromIndex); - else throw new IndexOutOfBoundsException(); - } - - public void add (int index,Object o) - { - - if (index <= size) - { - m_al.add(index + m_fromIndex,o); - m_toIndex++; - size++; - - } - else throw new IndexOutOfBoundsException(); - - } - - public Object remove(int index,Object o) - { - if (index < size) - { - Object ob = m_al.remove(index + m_fromIndex); - if (ob !=null) - { - m_toIndex--; - size--; - } - return ob; - } - else throw new IndexOutOfBoundsException(); - } - - public boolean addAll(int index, Collection c) - { - if (index < size) - { - boolean bool = m_al.addAll(index + m_fromIndex,c); - if (bool) - { - int lange = c.size(); - m_toIndex = m_toIndex + lange; - size = size + lange; - } - return bool; - } - else throw new IndexOutOfBoundsException(); - } - - public boolean addAll(Collection c) - { - boolean bool = m_al.addAll(m_toIndex,c); - if (bool) - { - int lange = c.size(); - m_toIndex = m_toIndex + lange; - size = size + lange; - } - return bool; - } - - public void removeRange (int from,int to) - { - if ((from <= to) && (from <= size) && (to <= size)) - { - m_al.removeRange(from,to); - int lange = to - from; - m_toIndex = m_toIndex - lange; - size = size - lange; - } - else - { - if (from > to) throw new IllegalArgumentException(); - else throw new IndexOutOfBoundsException(); - } - } - - public int size() - { - return (m_toIndex - m_fromIndex); - } - -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/ASN1InputStream.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/ASN1InputStream.java deleted file mode 100644 index 8c6571def..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/ASN1InputStream.java +++ /dev/null @@ -1,466 +0,0 @@ -package org.spongycastle.asn1; - -import java.io.ByteArrayInputStream; -import java.io.EOFException; -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.spongycastle.util.io.Streams; - -/** - * a general purpose ASN.1 decoder - note: this class differs from the - * others in that it returns null after it has read the last object in - * the stream. If an ASN.1 NULL is encountered a DER/BER Null object is - * returned. - */ -public class ASN1InputStream - extends FilterInputStream - implements BERTags -{ - private int limit; - private boolean lazyEvaluate; - - private byte[][] tmpBuffers; - - public ASN1InputStream( - InputStream is) - { - this(is, StreamUtil.findLimit(is)); - } - - /** - * Create an ASN1InputStream based on the input byte array. The length of DER objects in - * the stream is automatically limited to the length of the input array. - * - * @param input array containing ASN.1 encoded data. - */ - public ASN1InputStream( - byte[] input) - { - this(new ByteArrayInputStream(input), input.length); - } - - /** - * Create an ASN1InputStream based on the input byte array. The length of DER objects in - * the stream is automatically limited to the length of the input array. - * - * @param input array containing ASN.1 encoded data. - * @param lazyEvaluate true if parsing inside constructed objects can be delayed. - */ - public ASN1InputStream( - byte[] input, - boolean lazyEvaluate) - { - this(new ByteArrayInputStream(input), input.length, lazyEvaluate); - } - - /** - * Create an ASN1InputStream where no DER object will be longer than limit. - * - * @param input stream containing ASN.1 encoded data. - * @param limit maximum size of a DER encoded object. - */ - public ASN1InputStream( - InputStream input, - int limit) - { - this(input, limit, false); - } - - /** - * Create an ASN1InputStream where no DER object will be longer than limit, and constructed - * objects such as sequences will be parsed lazily. - * - * @param input stream containing ASN.1 encoded data. - * @param lazyEvaluate true if parsing inside constructed objects can be delayed. - */ - public ASN1InputStream( - InputStream input, - boolean lazyEvaluate) - { - this(input, StreamUtil.findLimit(input), lazyEvaluate); - } - - /** - * Create an ASN1InputStream where no DER object will be longer than limit, and constructed - * objects such as sequences will be parsed lazily. - * - * @param input stream containing ASN.1 encoded data. - * @param limit maximum size of a DER encoded object. - * @param lazyEvaluate true if parsing inside constructed objects can be delayed. - */ - public ASN1InputStream( - InputStream input, - int limit, - boolean lazyEvaluate) - { - super(input); - this.limit = limit; - this.lazyEvaluate = lazyEvaluate; - this.tmpBuffers = new byte[11][]; - } - - int getLimit() - { - return limit; - } - - protected int readLength() - throws IOException - { - return readLength(this, limit); - } - - protected void readFully( - byte[] bytes) - throws IOException - { - if (Streams.readFully(this, bytes) != bytes.length) - { - throw new EOFException("EOF encountered in middle of object"); - } - } - - /** - * build an object given its tag and the number of bytes to construct it from. - */ - protected ASN1Primitive buildObject( - int tag, - int tagNo, - int length) - throws IOException - { - boolean isConstructed = (tag & CONSTRUCTED) != 0; - - DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(this, length); - - if ((tag & APPLICATION) != 0) - { - return new DERApplicationSpecific(isConstructed, tagNo, defIn.toByteArray()); - } - - if ((tag & TAGGED) != 0) - { - return new ASN1StreamParser(defIn).readTaggedObject(isConstructed, tagNo); - } - - if (isConstructed) - { - // TODO There are other tags that may be constructed (e.g. BIT_STRING) - switch (tagNo) - { - case OCTET_STRING: - // - // yes, people actually do this... - // - ASN1EncodableVector v = buildDEREncodableVector(defIn); - ASN1OctetString[] strings = new ASN1OctetString[v.size()]; - - for (int i = 0; i != strings.length; i++) - { - strings[i] = (ASN1OctetString)v.get(i); - } - - return new BEROctetString(strings); - case SEQUENCE: - if (lazyEvaluate) - { - return new LazyEncodedSequence(defIn.toByteArray()); - } - else - { - return DERFactory.createSequence(buildDEREncodableVector(defIn)); - } - case SET: - return DERFactory.createSet(buildDEREncodableVector(defIn)); - case EXTERNAL: - return new DERExternal(buildDEREncodableVector(defIn)); - default: - throw new IOException("unknown tag " + tagNo + " encountered"); - } - } - - return createPrimitiveDERObject(tagNo, defIn, tmpBuffers); - } - - ASN1EncodableVector buildEncodableVector() - throws IOException - { - ASN1EncodableVector v = new ASN1EncodableVector(); - ASN1Primitive o; - - while ((o = readObject()) != null) - { - v.add(o); - } - - return v; - } - - ASN1EncodableVector buildDEREncodableVector( - DefiniteLengthInputStream dIn) throws IOException - { - return new ASN1InputStream(dIn).buildEncodableVector(); - } - - public ASN1Primitive readObject() - throws IOException - { - int tag = read(); - if (tag <= 0) - { - if (tag == 0) - { - throw new IOException("unexpected end-of-contents marker"); - } - - return null; - } - - // - // calculate tag number - // - int tagNo = readTagNumber(this, tag); - - boolean isConstructed = (tag & CONSTRUCTED) != 0; - - // - // calculate length - // - int length = readLength(); - - if (length < 0) // indefinite length method - { - if (!isConstructed) - { - throw new IOException("indefinite length primitive encoding encountered"); - } - - IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(this, limit); - ASN1StreamParser sp = new ASN1StreamParser(indIn, limit); - - if ((tag & APPLICATION) != 0) - { - return new BERApplicationSpecificParser(tagNo, sp).getLoadedObject(); - } - - if ((tag & TAGGED) != 0) - { - return new BERTaggedObjectParser(true, tagNo, sp).getLoadedObject(); - } - - // TODO There are other tags that may be constructed (e.g. BIT_STRING) - switch (tagNo) - { - case OCTET_STRING: - return new BEROctetStringParser(sp).getLoadedObject(); - case SEQUENCE: - return new BERSequenceParser(sp).getLoadedObject(); - case SET: - return new BERSetParser(sp).getLoadedObject(); - case EXTERNAL: - return new DERExternalParser(sp).getLoadedObject(); - default: - throw new IOException("unknown BER object encountered"); - } - } - else - { - try - { - return buildObject(tag, tagNo, length); - } - catch (IllegalArgumentException e) - { - throw new ASN1Exception("corrupted stream detected", e); - } - } - } - - static int readTagNumber(InputStream s, int tag) - throws IOException - { - int tagNo = tag & 0x1f; - - // - // with tagged object tag number is bottom 5 bits, or stored at the start of the content - // - if (tagNo == 0x1f) - { - tagNo = 0; - - int b = s.read(); - - // X.690-0207 8.1.2.4.2 - // "c) bits 7 to 1 of the first subsequent octet shall not all be zero." - if ((b & 0x7f) == 0) // Note: -1 will pass - { - throw new IOException("corrupted stream - invalid high tag number found"); - } - - while ((b >= 0) && ((b & 0x80) != 0)) - { - tagNo |= (b & 0x7f); - tagNo <<= 7; - b = s.read(); - } - - if (b < 0) - { - throw new EOFException("EOF found inside tag value."); - } - - tagNo |= (b & 0x7f); - } - - return tagNo; - } - - static int readLength(InputStream s, int limit) - throws IOException - { - int length = s.read(); - if (length < 0) - { - throw new EOFException("EOF found when length expected"); - } - - if (length == 0x80) - { - return -1; // indefinite-length encoding - } - - if (length > 127) - { - int size = length & 0x7f; - - // Note: The invalid long form "0xff" (see X.690 8.1.3.5c) will be caught here - if (size > 4) - { - throw new IOException("DER length more than 4 bytes: " + size); - } - - length = 0; - for (int i = 0; i < size; i++) - { - int next = s.read(); - - if (next < 0) - { - throw new EOFException("EOF found reading length"); - } - - length = (length << 8) + next; - } - - if (length < 0) - { - throw new IOException("corrupted stream - negative length found"); - } - - if (length >= limit) // after all we must have read at least 1 byte - { - throw new IOException("corrupted stream - out of bounds length found"); - } - } - - return length; - } - - private static byte[] getBuffer(DefiniteLengthInputStream defIn, byte[][] tmpBuffers) - throws IOException - { - int len = defIn.getRemaining(); - if (defIn.getRemaining() < tmpBuffers.length) - { - byte[] buf = tmpBuffers[len]; - - if (buf == null) - { - buf = tmpBuffers[len] = new byte[len]; - } - - Streams.readFully(defIn, buf); - - return buf; - } - else - { - return defIn.toByteArray(); - } - } - - private static char[] getBMPCharBuffer(DefiniteLengthInputStream defIn) - throws IOException - { - int len = defIn.getRemaining() / 2; - char[] buf = new char[len]; - int totalRead = 0; - while (totalRead < len) - { - int ch1 = defIn.read(); - if (ch1 < 0) - { - break; - } - int ch2 = defIn.read(); - if (ch2 < 0) - { - break; - } - buf[totalRead++] = (char)((ch1 << 8) | (ch2 & 0xff)); - } - - return buf; - } - - static ASN1Primitive createPrimitiveDERObject( - int tagNo, - DefiniteLengthInputStream defIn, - byte[][] tmpBuffers) - throws IOException - { - switch (tagNo) - { - case BIT_STRING: - return DERBitString.fromInputStream(defIn.getRemaining(), defIn); - case BMP_STRING: - return new DERBMPString(getBMPCharBuffer(defIn)); - case BOOLEAN: - return ASN1Boolean.fromOctetString(getBuffer(defIn, tmpBuffers)); - case ENUMERATED: - return ASN1Enumerated.fromOctetString(getBuffer(defIn, tmpBuffers)); - case GENERALIZED_TIME: - return new ASN1GeneralizedTime(defIn.toByteArray()); - case GENERAL_STRING: - return new DERGeneralString(defIn.toByteArray()); - case IA5_STRING: - return new DERIA5String(defIn.toByteArray()); - case INTEGER: - return new ASN1Integer(defIn.toByteArray(), false); - case NULL: - return DERNull.INSTANCE; // actual content is ignored (enforce 0 length?) - case NUMERIC_STRING: - return new DERNumericString(defIn.toByteArray()); - case OBJECT_IDENTIFIER: - return ASN1ObjectIdentifier.fromOctetString(getBuffer(defIn, tmpBuffers)); - case OCTET_STRING: - return new DEROctetString(defIn.toByteArray()); - case PRINTABLE_STRING: - return new DERPrintableString(defIn.toByteArray()); - case T61_STRING: - return new DERT61String(defIn.toByteArray()); - case UNIVERSAL_STRING: - return new DERUniversalString(defIn.toByteArray()); - case UTC_TIME: - return new ASN1UTCTime(defIn.toByteArray()); - case UTF8_STRING: - return new DERUTF8String(defIn.toByteArray()); - case VISIBLE_STRING: - return new DERVisibleString(defIn.toByteArray()); - default: - throw new IOException("unknown tag " + tagNo + " encountered"); - } - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/ASN1StreamParser.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/ASN1StreamParser.java deleted file mode 100644 index bbaef0565..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/ASN1StreamParser.java +++ /dev/null @@ -1,247 +0,0 @@ -package org.spongycastle.asn1; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -public class ASN1StreamParser -{ - private InputStream _in; - private int _limit; - private byte[][] tmpBuffers; - - public ASN1StreamParser( - InputStream in) - { - this(in, StreamUtil.findLimit(in)); - } - - public ASN1StreamParser( - InputStream in, - int limit) - { - this._in = in; - this._limit = limit; - - this.tmpBuffers = new byte[11][]; - } - - public ASN1StreamParser( - byte[] encoding) - { - this(new ByteArrayInputStream(encoding), encoding.length); - } - - ASN1Encodable readIndef(int tagValue) throws IOException - { - // Note: INDEF => CONSTRUCTED - - // TODO There are other tags that may be constructed (e.g. BIT_STRING) - switch (tagValue) - { - case BERTags.EXTERNAL: - return new DERExternalParser(this); - case BERTags.OCTET_STRING: - return new BEROctetStringParser(this); - case BERTags.SEQUENCE: - return new BERSequenceParser(this); - case BERTags.SET: - return new BERSetParser(this); - default: - throw new ASN1Exception("unknown BER object encountered: 0x" + Integer.toHexString(tagValue)); - } - } - - ASN1Encodable readImplicit(boolean constructed, int tag) throws IOException - { - if (_in instanceof IndefiniteLengthInputStream) - { - if (!constructed) - { - throw new IOException("indefinite length primitive encoding encountered"); - } - - return readIndef(tag); - } - - if (constructed) - { - switch (tag) - { - case BERTags.SET: - return new DERSetParser(this); - case BERTags.SEQUENCE: - return new DERSequenceParser(this); - case BERTags.OCTET_STRING: - return new BEROctetStringParser(this); - } - } - else - { - switch (tag) - { - case BERTags.SET: - throw new ASN1Exception("sequences must use constructed encoding (see X.690 8.9.1/8.10.1)"); - case BERTags.SEQUENCE: - throw new ASN1Exception("sets must use constructed encoding (see X.690 8.11.1/8.12.1)"); - case BERTags.OCTET_STRING: - return new DEROctetStringParser((DefiniteLengthInputStream)_in); - } - } - - // TODO ASN1Exception - throw new RuntimeException("implicit tagging not implemented"); - } - - ASN1Primitive readTaggedObject(boolean constructed, int tag) throws IOException - { - if (!constructed) - { - // Note: !CONSTRUCTED => IMPLICIT - DefiniteLengthInputStream defIn = (DefiniteLengthInputStream)_in; - return new DERTaggedObject(false, tag, new DEROctetString(defIn.toByteArray())); - } - - ASN1EncodableVector v = readVector(); - - if (_in instanceof IndefiniteLengthInputStream) - { - return v.size() == 1 - ? new BERTaggedObject(true, tag, v.get(0)) - : new BERTaggedObject(false, tag, BERFactory.createSequence(v)); - } - - return v.size() == 1 - ? new DERTaggedObject(true, tag, v.get(0)) - : new DERTaggedObject(false, tag, DERFactory.createSequence(v)); - } - - public ASN1Encodable readObject() - throws IOException - { - int tag = _in.read(); - if (tag == -1) - { - return null; - } - - // - // turn of looking for "00" while we resolve the tag - // - set00Check(false); - - // - // calculate tag number - // - int tagNo = ASN1InputStream.readTagNumber(_in, tag); - - boolean isConstructed = (tag & BERTags.CONSTRUCTED) != 0; - - // - // calculate length - // - int length = ASN1InputStream.readLength(_in, _limit); - - if (length < 0) // indefinite length method - { - if (!isConstructed) - { - throw new IOException("indefinite length primitive encoding encountered"); - } - - IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(_in, _limit); - ASN1StreamParser sp = new ASN1StreamParser(indIn, _limit); - - if ((tag & BERTags.APPLICATION) != 0) - { - return new BERApplicationSpecificParser(tagNo, sp); - } - - if ((tag & BERTags.TAGGED) != 0) - { - return new BERTaggedObjectParser(true, tagNo, sp); - } - - return sp.readIndef(tagNo); - } - else - { - DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(_in, length); - - if ((tag & BERTags.APPLICATION) != 0) - { - return new DERApplicationSpecific(isConstructed, tagNo, defIn.toByteArray()); - } - - if ((tag & BERTags.TAGGED) != 0) - { - return new BERTaggedObjectParser(isConstructed, tagNo, new ASN1StreamParser(defIn)); - } - - if (isConstructed) - { - // TODO There are other tags that may be constructed (e.g. BIT_STRING) - switch (tagNo) - { - case BERTags.OCTET_STRING: - // - // yes, people actually do this... - // - return new BEROctetStringParser(new ASN1StreamParser(defIn)); - case BERTags.SEQUENCE: - return new DERSequenceParser(new ASN1StreamParser(defIn)); - case BERTags.SET: - return new DERSetParser(new ASN1StreamParser(defIn)); - case BERTags.EXTERNAL: - return new DERExternalParser(new ASN1StreamParser(defIn)); - default: - throw new IOException("unknown tag " + tagNo + " encountered"); - } - } - - // Some primitive encodings can be handled by parsers too... - switch (tagNo) - { - case BERTags.OCTET_STRING: - return new DEROctetStringParser(defIn); - } - - try - { - return ASN1InputStream.createPrimitiveDERObject(tagNo, defIn, tmpBuffers); - } - catch (IllegalArgumentException e) - { - throw new ASN1Exception("corrupted stream detected", e); - } - } - } - - private void set00Check(boolean enabled) - { - if (_in instanceof IndefiniteLengthInputStream) - { - ((IndefiniteLengthInputStream)_in).setEofOn00(enabled); - } - } - - ASN1EncodableVector readVector() throws IOException - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - ASN1Encodable obj; - while ((obj = readObject()) != null) - { - if (obj instanceof InMemoryRepresentable) - { - v.add(((InMemoryRepresentable)obj).getLoadedObject()); - } - else - { - v.add(obj.toASN1Primitive()); - } - } - - return v; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/DERApplicationSpecific.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/DERApplicationSpecific.java deleted file mode 100644 index 30c66ab65..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/DERApplicationSpecific.java +++ /dev/null @@ -1,276 +0,0 @@ -package org.spongycastle.asn1; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.spongycastle.util.Arrays; - -/** - * Base class for an application specific object - */ -public class DERApplicationSpecific - extends ASN1Primitive -{ - private boolean isConstructed; - private int tag; - private byte[] octets; - - DERApplicationSpecific( - boolean isConstructed, - int tag, - byte[] octets) - { - this.isConstructed = isConstructed; - this.tag = tag; - this.octets = octets; - } - - public DERApplicationSpecific( - int tag, - byte[] octets) - { - this(false, tag, octets); - } - - public DERApplicationSpecific( - int tag, - ASN1Encodable object) - throws IOException - { - this(true, tag, object); - } - - public DERApplicationSpecific( - boolean explicit, - int tag, - ASN1Encodable object) - throws IOException - { - ASN1Primitive primitive = object.toASN1Primitive(); - - byte[] data = primitive.getEncoded(ASN1Encoding.DER); - - this.isConstructed = explicit || (primitive instanceof ASN1Set || primitive instanceof ASN1Sequence); - this.tag = tag; - - if (explicit) - { - this.octets = data; - } - else - { - int lenBytes = getLengthOfHeader(data); - byte[] tmp = new byte[data.length - lenBytes]; - System.arraycopy(data, lenBytes, tmp, 0, tmp.length); - this.octets = tmp; - } - } - - public DERApplicationSpecific(int tagNo, ASN1EncodableVector vec) - { - this.tag = tagNo; - this.isConstructed = true; - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - for (int i = 0; i != vec.size(); i++) - { - try - { - bOut.write(((ASN1Object)vec.get(i)).getEncoded(ASN1Encoding.DER)); - } - catch (IOException e) - { - throw new ASN1ParsingException("malformed object: " + e, e); - } - } - this.octets = bOut.toByteArray(); - } - - public static DERApplicationSpecific getInstance(Object obj) - { - if (obj == null || obj instanceof DERApplicationSpecific) - { - return (DERApplicationSpecific)obj; - } - else if (obj instanceof byte[]) - { - try - { - return DERApplicationSpecific.getInstance(ASN1Primitive.fromByteArray((byte[])obj)); - } - catch (IOException e) - { - throw new IllegalArgumentException("failed to construct object from byte[]: " + e.getMessage()); - } - } - else if (obj instanceof ASN1Encodable) - { - ASN1Primitive primitive = ((ASN1Encodable)obj).toASN1Primitive(); - - if (primitive instanceof ASN1Sequence) - { - return (DERApplicationSpecific)primitive; - } - } - - throw new IllegalArgumentException("unknown object in getInstance: " + obj.getClass().getName()); - } - - private int getLengthOfHeader(byte[] data) - { - int length = data[1] & 0xff; // TODO: assumes 1 byte tag - - if (length == 0x80) - { - return 2; // indefinite-length encoding - } - - if (length > 127) - { - int size = length & 0x7f; - - // Note: The invalid long form "0xff" (see X.690 8.1.3.5c) will be caught here - if (size > 4) - { - throw new IllegalStateException("DER length more than 4 bytes: " + size); - } - - return size + 2; - } - - return 2; - } - - public boolean isConstructed() - { - return isConstructed; - } - - public byte[] getContents() - { - return octets; - } - - public int getApplicationTag() - { - return tag; - } - - /** - * Return the enclosed object assuming explicit tagging. - * - * @return the resulting object - * @throws IOException if reconstruction fails. - */ - public ASN1Primitive getObject() - throws IOException - { - return new ASN1InputStream(getContents()).readObject(); - } - - /** - * Return the enclosed object assuming implicit tagging. - * - * @param derTagNo the type tag that should be applied to the object's contents. - * @return the resulting object - * @throws IOException if reconstruction fails. - */ - public ASN1Primitive getObject(int derTagNo) - throws IOException - { - if (derTagNo >= 0x1f) - { - throw new IOException("unsupported tag number"); - } - - byte[] orig = this.getEncoded(); - byte[] tmp = replaceTagNumber(derTagNo, orig); - - if ((orig[0] & BERTags.CONSTRUCTED) != 0) - { - tmp[0] |= BERTags.CONSTRUCTED; - } - - return new ASN1InputStream(tmp).readObject(); - } - - int encodedLength() - throws IOException - { - return StreamUtil.calculateTagLength(tag) + StreamUtil.calculateBodyLength(octets.length) + octets.length; - } - - /* (non-Javadoc) - * @see org.spongycastle.asn1.ASN1Primitive#encode(org.spongycastle.asn1.DEROutputStream) - */ - void encode(ASN1OutputStream out) throws IOException - { - int classBits = BERTags.APPLICATION; - if (isConstructed) - { - classBits |= BERTags.CONSTRUCTED; - } - - out.writeEncoded(classBits, tag, octets); - } - - boolean asn1Equals( - ASN1Primitive o) - { - if (!(o instanceof DERApplicationSpecific)) - { - return false; - } - - DERApplicationSpecific other = (DERApplicationSpecific)o; - - return isConstructed == other.isConstructed - && tag == other.tag - && Arrays.areEqual(octets, other.octets); - } - - public int hashCode() - { - return (isConstructed ? 1 : 0) ^ tag ^ Arrays.hashCode(octets); - } - - private byte[] replaceTagNumber(int newTag, byte[] input) - throws IOException - { - int tagNo = input[0] & 0x1f; - int index = 1; - // - // with tagged object tag number is bottom 5 bits, or stored at the start of the content - // - if (tagNo == 0x1f) - { - tagNo = 0; - - int b = input[index++] & 0xff; - - // X.690-0207 8.1.2.4.2 - // "c) bits 7 to 1 of the first subsequent octet shall not all be zero." - if ((b & 0x7f) == 0) // Note: -1 will pass - { - throw new ASN1ParsingException("corrupted stream - invalid high tag number found"); - } - - while ((b >= 0) && ((b & 0x80) != 0)) - { - tagNo |= (b & 0x7f); - tagNo <<= 7; - b = input[index++] & 0xff; - } - - tagNo |= (b & 0x7f); - } - - byte[] tmp = new byte[input.length - index + 1]; - - System.arraycopy(input, index, tmp, 1, tmp.length - 1); - - tmp[0] = (byte)newTag; - - return tmp; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/x500/style/BCStyle.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/x500/style/BCStyle.java deleted file mode 100644 index 2591e4cdc..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/x500/style/BCStyle.java +++ /dev/null @@ -1,481 +0,0 @@ -package org.spongycastle.asn1.x500.style; - -import java.io.IOException; -import java.util.Enumeration; -import java.util.Hashtable; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1GeneralizedTime; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DERIA5String; -import org.spongycastle.asn1.DERPrintableString; -import org.spongycastle.asn1.DERUTF8String; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.x500.AttributeTypeAndValue; -import org.spongycastle.asn1.x500.RDN; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x500.X500NameStyle; -import org.spongycastle.asn1.x509.X509ObjectIdentifiers; - -public class BCStyle - implements X500NameStyle -{ - /** - * country code - StringType(SIZE(2)) - */ - public static final ASN1ObjectIdentifier C = new ASN1ObjectIdentifier("2.5.4.6"); - - /** - * organization - StringType(SIZE(1..64)) - */ - public static final ASN1ObjectIdentifier O = new ASN1ObjectIdentifier("2.5.4.10"); - - /** - * organizational unit name - StringType(SIZE(1..64)) - */ - public static final ASN1ObjectIdentifier OU = new ASN1ObjectIdentifier("2.5.4.11"); - - /** - * Title - */ - public static final ASN1ObjectIdentifier T = new ASN1ObjectIdentifier("2.5.4.12"); - - /** - * common name - StringType(SIZE(1..64)) - */ - public static final ASN1ObjectIdentifier CN = new ASN1ObjectIdentifier("2.5.4.3"); - - /** - * device serial number name - StringType(SIZE(1..64)) - */ - public static final ASN1ObjectIdentifier SN = new ASN1ObjectIdentifier("2.5.4.5"); - - /** - * street - StringType(SIZE(1..64)) - */ - public static final ASN1ObjectIdentifier STREET = new ASN1ObjectIdentifier("2.5.4.9"); - - /** - * device serial number name - StringType(SIZE(1..64)) - */ - public static final ASN1ObjectIdentifier SERIALNUMBER = SN; - - /** - * locality name - StringType(SIZE(1..64)) - */ - public static final ASN1ObjectIdentifier L = new ASN1ObjectIdentifier("2.5.4.7"); - - /** - * state, or province name - StringType(SIZE(1..64)) - */ - public static final ASN1ObjectIdentifier ST = new ASN1ObjectIdentifier("2.5.4.8"); - - /** - * Naming attributes of type X520name - */ - public static final ASN1ObjectIdentifier SURNAME = new ASN1ObjectIdentifier("2.5.4.4"); - public static final ASN1ObjectIdentifier GIVENNAME = new ASN1ObjectIdentifier("2.5.4.42"); - public static final ASN1ObjectIdentifier INITIALS = new ASN1ObjectIdentifier("2.5.4.43"); - public static final ASN1ObjectIdentifier GENERATION = new ASN1ObjectIdentifier("2.5.4.44"); - public static final ASN1ObjectIdentifier UNIQUE_IDENTIFIER = new ASN1ObjectIdentifier("2.5.4.45"); - - /** - * businessCategory - DirectoryString(SIZE(1..128) - */ - public static final ASN1ObjectIdentifier BUSINESS_CATEGORY = new ASN1ObjectIdentifier( - "2.5.4.15"); - - /** - * postalCode - DirectoryString(SIZE(1..40) - */ - public static final ASN1ObjectIdentifier POSTAL_CODE = new ASN1ObjectIdentifier( - "2.5.4.17"); - - /** - * dnQualifier - DirectoryString(SIZE(1..64) - */ - public static final ASN1ObjectIdentifier DN_QUALIFIER = new ASN1ObjectIdentifier( - "2.5.4.46"); - - /** - * RFC 3039 Pseudonym - DirectoryString(SIZE(1..64) - */ - public static final ASN1ObjectIdentifier PSEUDONYM = new ASN1ObjectIdentifier( - "2.5.4.65"); - - - /** - * RFC 3039 DateOfBirth - GeneralizedTime - YYYYMMDD000000Z - */ - public static final ASN1ObjectIdentifier DATE_OF_BIRTH = new ASN1ObjectIdentifier( - "1.3.6.1.5.5.7.9.1"); - - /** - * RFC 3039 PlaceOfBirth - DirectoryString(SIZE(1..128) - */ - public static final ASN1ObjectIdentifier PLACE_OF_BIRTH = new ASN1ObjectIdentifier( - "1.3.6.1.5.5.7.9.2"); - - /** - * RFC 3039 Gender - PrintableString (SIZE(1)) -- "M", "F", "m" or "f" - */ - public static final ASN1ObjectIdentifier GENDER = new ASN1ObjectIdentifier( - "1.3.6.1.5.5.7.9.3"); - - /** - * RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166 - * codes only - */ - public static final ASN1ObjectIdentifier COUNTRY_OF_CITIZENSHIP = new ASN1ObjectIdentifier( - "1.3.6.1.5.5.7.9.4"); - - /** - * RFC 3039 CountryOfResidence - PrintableString (SIZE (2)) -- ISO 3166 - * codes only - */ - public static final ASN1ObjectIdentifier COUNTRY_OF_RESIDENCE = new ASN1ObjectIdentifier( - "1.3.6.1.5.5.7.9.5"); - - - /** - * ISIS-MTT NameAtBirth - DirectoryString(SIZE(1..64) - */ - public static final ASN1ObjectIdentifier NAME_AT_BIRTH = new ASN1ObjectIdentifier("1.3.36.8.3.14"); - - /** - * RFC 3039 PostalAddress - SEQUENCE SIZE (1..6) OF - * DirectoryString(SIZE(1..30)) - */ - public static final ASN1ObjectIdentifier POSTAL_ADDRESS = new ASN1ObjectIdentifier("2.5.4.16"); - - /** - * RFC 2256 dmdName - */ - public static final ASN1ObjectIdentifier DMD_NAME = new ASN1ObjectIdentifier("2.5.4.54"); - - /** - * id-at-telephoneNumber - */ - public static final ASN1ObjectIdentifier TELEPHONE_NUMBER = X509ObjectIdentifiers.id_at_telephoneNumber; - - /** - * id-at-name - */ - public static final ASN1ObjectIdentifier NAME = X509ObjectIdentifiers.id_at_name; - - /** - * Email address (RSA PKCS#9 extension) - IA5String. - *

Note: if you're trying to be ultra orthodox, don't use this! It shouldn't be in here. - */ - public static final ASN1ObjectIdentifier EmailAddress = PKCSObjectIdentifiers.pkcs_9_at_emailAddress; - - /** - * more from PKCS#9 - */ - public static final ASN1ObjectIdentifier UnstructuredName = PKCSObjectIdentifiers.pkcs_9_at_unstructuredName; - public static final ASN1ObjectIdentifier UnstructuredAddress = PKCSObjectIdentifiers.pkcs_9_at_unstructuredAddress; - - /** - * email address in Verisign certificates - */ - public static final ASN1ObjectIdentifier E = EmailAddress; - - /* - * others... - */ - public static final ASN1ObjectIdentifier DC = new ASN1ObjectIdentifier("0.9.2342.19200300.100.1.25"); - - /** - * LDAP User id. - */ - public static final ASN1ObjectIdentifier UID = new ASN1ObjectIdentifier("0.9.2342.19200300.100.1.1"); - - /** - * default look up table translating OID values into their common symbols following - * the convention in RFC 2253 with a few extras - */ - private static final Hashtable DefaultSymbols = new Hashtable(); - - /** - * look up table translating common symbols into their OIDS. - */ - private static final Hashtable DefaultLookUp = new Hashtable(); - - static - { - DefaultSymbols.put(C, "C"); - DefaultSymbols.put(O, "O"); - DefaultSymbols.put(T, "T"); - DefaultSymbols.put(OU, "OU"); - DefaultSymbols.put(CN, "CN"); - DefaultSymbols.put(L, "L"); - DefaultSymbols.put(ST, "ST"); - DefaultSymbols.put(SN, "SERIALNUMBER"); - DefaultSymbols.put(EmailAddress, "E"); - DefaultSymbols.put(DC, "DC"); - DefaultSymbols.put(UID, "UID"); - DefaultSymbols.put(STREET, "STREET"); - DefaultSymbols.put(SURNAME, "SURNAME"); - DefaultSymbols.put(GIVENNAME, "GIVENNAME"); - DefaultSymbols.put(INITIALS, "INITIALS"); - DefaultSymbols.put(GENERATION, "GENERATION"); - DefaultSymbols.put(UnstructuredAddress, "unstructuredAddress"); - DefaultSymbols.put(UnstructuredName, "unstructuredName"); - DefaultSymbols.put(UNIQUE_IDENTIFIER, "UniqueIdentifier"); - DefaultSymbols.put(DN_QUALIFIER, "DN"); - DefaultSymbols.put(PSEUDONYM, "Pseudonym"); - DefaultSymbols.put(POSTAL_ADDRESS, "PostalAddress"); - DefaultSymbols.put(NAME_AT_BIRTH, "NameAtBirth"); - DefaultSymbols.put(COUNTRY_OF_CITIZENSHIP, "CountryOfCitizenship"); - DefaultSymbols.put(COUNTRY_OF_RESIDENCE, "CountryOfResidence"); - DefaultSymbols.put(GENDER, "Gender"); - DefaultSymbols.put(PLACE_OF_BIRTH, "PlaceOfBirth"); - DefaultSymbols.put(DATE_OF_BIRTH, "DateOfBirth"); - DefaultSymbols.put(POSTAL_CODE, "PostalCode"); - DefaultSymbols.put(BUSINESS_CATEGORY, "BusinessCategory"); - DefaultSymbols.put(TELEPHONE_NUMBER, "TelephoneNumber"); - DefaultSymbols.put(NAME, "Name"); - - DefaultLookUp.put("c", C); - DefaultLookUp.put("o", O); - DefaultLookUp.put("t", T); - DefaultLookUp.put("ou", OU); - DefaultLookUp.put("cn", CN); - DefaultLookUp.put("l", L); - DefaultLookUp.put("st", ST); - DefaultLookUp.put("sn", SN); - DefaultLookUp.put("serialnumber", SN); - DefaultLookUp.put("street", STREET); - DefaultLookUp.put("emailaddress", E); - DefaultLookUp.put("dc", DC); - DefaultLookUp.put("e", E); - DefaultLookUp.put("uid", UID); - DefaultLookUp.put("surname", SURNAME); - DefaultLookUp.put("givenname", GIVENNAME); - DefaultLookUp.put("initials", INITIALS); - DefaultLookUp.put("generation", GENERATION); - DefaultLookUp.put("unstructuredaddress", UnstructuredAddress); - DefaultLookUp.put("unstructuredname", UnstructuredName); - DefaultLookUp.put("uniqueidentifier", UNIQUE_IDENTIFIER); - DefaultLookUp.put("dn", DN_QUALIFIER); - DefaultLookUp.put("pseudonym", PSEUDONYM); - DefaultLookUp.put("postaladdress", POSTAL_ADDRESS); - DefaultLookUp.put("nameofbirth", NAME_AT_BIRTH); - DefaultLookUp.put("countryofcitizenship", COUNTRY_OF_CITIZENSHIP); - DefaultLookUp.put("countryofresidence", COUNTRY_OF_RESIDENCE); - DefaultLookUp.put("gender", GENDER); - DefaultLookUp.put("placeofbirth", PLACE_OF_BIRTH); - DefaultLookUp.put("dateofbirth", DATE_OF_BIRTH); - DefaultLookUp.put("postalcode", POSTAL_CODE); - DefaultLookUp.put("businesscategory", BUSINESS_CATEGORY); - DefaultLookUp.put("telephonenumber", TELEPHONE_NUMBER); - DefaultLookUp.put("name", NAME); - } - - /** - * Singleton instance. - */ - public static final X500NameStyle INSTANCE = new BCStyle(); - - protected Hashtable defaultLookUp; - protected Hashtable defaultSymbols; - - protected BCStyle() - { - defaultSymbols = copyHashTable(DefaultSymbols); - defaultLookUp = copyHashTable(DefaultLookUp); - } - - public ASN1Encodable stringToValue(ASN1ObjectIdentifier oid, String value) - { - if (value.length() != 0 && value.charAt(0) == '#') - { - try - { - return IETFUtils.valueFromHexString(value, 1); - } - catch (IOException e) - { - throw new RuntimeException("can't recode value for oid " + oid.getId()); - } - } - else - { - if (value.length() != 0 && value.charAt(0) == '\\') - { - value = value.substring(1); - } - if (oid.equals(EmailAddress) || oid.equals(DC)) - { - return new DERIA5String(value); - } - else if (oid.equals(DATE_OF_BIRTH)) // accept time string as well as # (for compatibility) - { - return new ASN1GeneralizedTime(value); - } - else if (oid.equals(C) || oid.equals(SN) || oid.equals(DN_QUALIFIER) - || oid.equals(TELEPHONE_NUMBER)) - { - return new DERPrintableString(value); - } - } - - return new DERUTF8String(value); - } - - public String oidToDisplayName(ASN1ObjectIdentifier oid) - { - return (String)DefaultSymbols.get(oid); - } - - public String[] oidToAttrNames(ASN1ObjectIdentifier oid) - { - return IETFUtils.findAttrNamesForOID(oid, defaultLookUp); - } - - public ASN1ObjectIdentifier attrNameToOID(String attrName) - { - return IETFUtils.decodeAttrName(attrName, defaultLookUp); - } - - public boolean areEqual(X500Name name1, X500Name name2) - { - RDN[] rdns1 = name1.getRDNs(); - RDN[] rdns2 = name2.getRDNs(); - - if (rdns1.length != rdns2.length) - { - return false; - } - - boolean reverse = false; - - if (rdns1[0].getFirst() != null && rdns2[0].getFirst() != null) - { - reverse = !rdns1[0].getFirst().getType().equals(rdns2[0].getFirst().getType()); // guess forward - } - - for (int i = 0; i != rdns1.length; i++) - { - if (!foundMatch(reverse, rdns1[i], rdns2)) - { - return false; - } - } - - return true; - } - - private boolean foundMatch(boolean reverse, RDN rdn, RDN[] possRDNs) - { - if (reverse) - { - for (int i = possRDNs.length - 1; i >= 0; i--) - { - if (possRDNs[i] != null && rdnAreEqual(rdn, possRDNs[i])) - { - possRDNs[i] = null; - return true; - } - } - } - else - { - for (int i = 0; i != possRDNs.length; i++) - { - if (possRDNs[i] != null && rdnAreEqual(rdn, possRDNs[i])) - { - possRDNs[i] = null; - return true; - } - } - } - - return false; - } - - protected boolean rdnAreEqual(RDN rdn1, RDN rdn2) - { - return IETFUtils.rDNAreEqual(rdn1, rdn2); - } - - public RDN[] fromString(String dirName) - { - return IETFUtils.rDNsFromString(dirName, this); - } - - public int calculateHashCode(X500Name name) - { - int hashCodeValue = 0; - RDN[] rdns = name.getRDNs(); - - // this needs to be order independent, like equals - for (int i = 0; i != rdns.length; i++) - { - if (rdns[i].isMultiValued()) - { - AttributeTypeAndValue[] atv = rdns[i].getTypesAndValues(); - - for (int j = 0; j != atv.length; j++) - { - hashCodeValue ^= atv[j].getType().hashCode(); - hashCodeValue ^= calcHashCode(atv[j].getValue()); - } - } - else - { - hashCodeValue ^= rdns[i].getFirst().getType().hashCode(); - hashCodeValue ^= calcHashCode(rdns[i].getFirst().getValue()); - } - } - - return hashCodeValue; - } - - private int calcHashCode(ASN1Encodable enc) - { - String value = IETFUtils.valueToString(enc); - - value = IETFUtils.canonicalize(value); - - return value.hashCode(); - } - - public String toString(X500Name name) - { - StringBuffer buf = new StringBuffer(); - boolean first = true; - - RDN[] rdns = name.getRDNs(); - - for (int i = 0; i < rdns.length; i++) - { - if (first) - { - first = false; - } - else - { - buf.append(','); - } - - IETFUtils.appendRDN(buf, rdns[i], defaultSymbols); - } - - return buf.toString(); - } - - private static Hashtable copyHashTable(Hashtable paramsMap) - { - Hashtable newTable = new Hashtable(); - - Enumeration keys = paramsMap.keys(); - while (keys.hasMoreElements()) - { - Object key = keys.nextElement(); - newTable.put(key, paramsMap.get(key)); - } - - return newTable; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/x500/style/RFC4519Style.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/x500/style/RFC4519Style.java deleted file mode 100644 index 0fd117850..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/asn1/x500/style/RFC4519Style.java +++ /dev/null @@ -1,380 +0,0 @@ -package org.spongycastle.asn1.x500.style; - -import java.io.IOException; -import java.util.Enumeration; -import java.util.Hashtable; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DERIA5String; -import org.spongycastle.asn1.DERPrintableString; -import org.spongycastle.asn1.DERUTF8String; -import org.spongycastle.asn1.x500.AttributeTypeAndValue; -import org.spongycastle.asn1.x500.RDN; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x500.X500NameStyle; - -public class RFC4519Style - implements X500NameStyle -{ - public static final ASN1ObjectIdentifier businessCategory = new ASN1ObjectIdentifier("2.5.4.15"); - public static final ASN1ObjectIdentifier c = new ASN1ObjectIdentifier("2.5.4.6"); - public static final ASN1ObjectIdentifier cn = new ASN1ObjectIdentifier("2.5.4.3"); - public static final ASN1ObjectIdentifier dc = new ASN1ObjectIdentifier("0.9.2342.19200300.100.1.25"); - public static final ASN1ObjectIdentifier description = new ASN1ObjectIdentifier("2.5.4.13"); - public static final ASN1ObjectIdentifier destinationIndicator = new ASN1ObjectIdentifier("2.5.4.27"); - public static final ASN1ObjectIdentifier distinguishedName = new ASN1ObjectIdentifier("2.5.4.49"); - public static final ASN1ObjectIdentifier dnQualifier = new ASN1ObjectIdentifier("2.5.4.46"); - public static final ASN1ObjectIdentifier enhancedSearchGuide = new ASN1ObjectIdentifier("2.5.4.47"); - public static final ASN1ObjectIdentifier facsimileTelephoneNumber = new ASN1ObjectIdentifier("2.5.4.23"); - public static final ASN1ObjectIdentifier generationQualifier = new ASN1ObjectIdentifier("2.5.4.44"); - public static final ASN1ObjectIdentifier givenName = new ASN1ObjectIdentifier("2.5.4.42"); - public static final ASN1ObjectIdentifier houseIdentifier = new ASN1ObjectIdentifier("2.5.4.51"); - public static final ASN1ObjectIdentifier initials = new ASN1ObjectIdentifier("2.5.4.43"); - public static final ASN1ObjectIdentifier internationalISDNNumber = new ASN1ObjectIdentifier("2.5.4.25"); - public static final ASN1ObjectIdentifier l = new ASN1ObjectIdentifier("2.5.4.7"); - public static final ASN1ObjectIdentifier member = new ASN1ObjectIdentifier("2.5.4.31"); - public static final ASN1ObjectIdentifier name = new ASN1ObjectIdentifier("2.5.4.41"); - public static final ASN1ObjectIdentifier o = new ASN1ObjectIdentifier("2.5.4.10"); - public static final ASN1ObjectIdentifier ou = new ASN1ObjectIdentifier("2.5.4.11"); - public static final ASN1ObjectIdentifier owner = new ASN1ObjectIdentifier("2.5.4.32"); - public static final ASN1ObjectIdentifier physicalDeliveryOfficeName = new ASN1ObjectIdentifier("2.5.4.19"); - public static final ASN1ObjectIdentifier postalAddress = new ASN1ObjectIdentifier("2.5.4.16"); - public static final ASN1ObjectIdentifier postalCode = new ASN1ObjectIdentifier("2.5.4.17"); - public static final ASN1ObjectIdentifier postOfficeBox = new ASN1ObjectIdentifier("2.5.4.18"); - public static final ASN1ObjectIdentifier preferredDeliveryMethod = new ASN1ObjectIdentifier("2.5.4.28"); - public static final ASN1ObjectIdentifier registeredAddress = new ASN1ObjectIdentifier("2.5.4.26"); - public static final ASN1ObjectIdentifier roleOccupant = new ASN1ObjectIdentifier("2.5.4.33"); - public static final ASN1ObjectIdentifier searchGuide = new ASN1ObjectIdentifier("2.5.4.14"); - public static final ASN1ObjectIdentifier seeAlso = new ASN1ObjectIdentifier("2.5.4.34"); - public static final ASN1ObjectIdentifier serialNumber = new ASN1ObjectIdentifier("2.5.4.5"); - public static final ASN1ObjectIdentifier sn = new ASN1ObjectIdentifier("2.5.4.4"); - public static final ASN1ObjectIdentifier st = new ASN1ObjectIdentifier("2.5.4.8"); - public static final ASN1ObjectIdentifier street = new ASN1ObjectIdentifier("2.5.4.9"); - public static final ASN1ObjectIdentifier telephoneNumber = new ASN1ObjectIdentifier("2.5.4.20"); - public static final ASN1ObjectIdentifier teletexTerminalIdentifier = new ASN1ObjectIdentifier("2.5.4.22"); - public static final ASN1ObjectIdentifier telexNumber = new ASN1ObjectIdentifier("2.5.4.21"); - public static final ASN1ObjectIdentifier title = new ASN1ObjectIdentifier("2.5.4.12"); - public static final ASN1ObjectIdentifier uid = new ASN1ObjectIdentifier("0.9.2342.19200300.100.1.1"); - public static final ASN1ObjectIdentifier uniqueMember = new ASN1ObjectIdentifier("2.5.4.50"); - public static final ASN1ObjectIdentifier userPassword = new ASN1ObjectIdentifier("2.5.4.35"); - public static final ASN1ObjectIdentifier x121Address = new ASN1ObjectIdentifier("2.5.4.24"); - public static final ASN1ObjectIdentifier x500UniqueIdentifier = new ASN1ObjectIdentifier("2.5.4.45"); - - /** - * default look up table translating OID values into their common symbols following - * the convention in RFC 2253 with a few extras - */ - private static final Hashtable DefaultSymbols = new Hashtable(); - - /** - * look up table translating common symbols into their OIDS. - */ - private static final Hashtable DefaultLookUp = new Hashtable(); - - static - { - DefaultSymbols.put(businessCategory, "businessCategory"); - DefaultSymbols.put(c, "c"); - DefaultSymbols.put(cn, "cn"); - DefaultSymbols.put(dc, "dc"); - DefaultSymbols.put(description, "description"); - DefaultSymbols.put(destinationIndicator, "destinationIndicator"); - DefaultSymbols.put(distinguishedName, "distinguishedName"); - DefaultSymbols.put(dnQualifier, "dnQualifier"); - DefaultSymbols.put(enhancedSearchGuide, "enhancedSearchGuide"); - DefaultSymbols.put(facsimileTelephoneNumber, "facsimileTelephoneNumber"); - DefaultSymbols.put(generationQualifier, "generationQualifier"); - DefaultSymbols.put(givenName, "givenName"); - DefaultSymbols.put(houseIdentifier, "houseIdentifier"); - DefaultSymbols.put(initials, "initials"); - DefaultSymbols.put(internationalISDNNumber, "internationalISDNNumber"); - DefaultSymbols.put(l, "l"); - DefaultSymbols.put(member, "member"); - DefaultSymbols.put(name, "name"); - DefaultSymbols.put(o, "o"); - DefaultSymbols.put(ou, "ou"); - DefaultSymbols.put(owner, "owner"); - DefaultSymbols.put(physicalDeliveryOfficeName, "physicalDeliveryOfficeName"); - DefaultSymbols.put(postalAddress, "postalAddress"); - DefaultSymbols.put(postalCode, "postalCode"); - DefaultSymbols.put(postOfficeBox, "postOfficeBox"); - DefaultSymbols.put(preferredDeliveryMethod, "preferredDeliveryMethod"); - DefaultSymbols.put(registeredAddress, "registeredAddress"); - DefaultSymbols.put(roleOccupant, "roleOccupant"); - DefaultSymbols.put(searchGuide, "searchGuide"); - DefaultSymbols.put(seeAlso, "seeAlso"); - DefaultSymbols.put(serialNumber, "serialNumber"); - DefaultSymbols.put(sn, "sn"); - DefaultSymbols.put(st, "st"); - DefaultSymbols.put(street, "street"); - DefaultSymbols.put(telephoneNumber, "telephoneNumber"); - DefaultSymbols.put(teletexTerminalIdentifier, "teletexTerminalIdentifier"); - DefaultSymbols.put(telexNumber, "telexNumber"); - DefaultSymbols.put(title, "title"); - DefaultSymbols.put(uid, "uid"); - DefaultSymbols.put(uniqueMember, "uniqueMember"); - DefaultSymbols.put(userPassword, "userPassword"); - DefaultSymbols.put(x121Address, "x121Address"); - DefaultSymbols.put(x500UniqueIdentifier, "x500UniqueIdentifier"); - - DefaultLookUp.put("businesscategory", businessCategory); - DefaultLookUp.put("c", c); - DefaultLookUp.put("cn", cn); - DefaultLookUp.put("dc", dc); - DefaultLookUp.put("description", description); - DefaultLookUp.put("destinationindicator", destinationIndicator); - DefaultLookUp.put("distinguishedname", distinguishedName); - DefaultLookUp.put("dnqualifier", dnQualifier); - DefaultLookUp.put("enhancedsearchguide", enhancedSearchGuide); - DefaultLookUp.put("facsimiletelephonenumber", facsimileTelephoneNumber); - DefaultLookUp.put("generationqualifier", generationQualifier); - DefaultLookUp.put("givenname", givenName); - DefaultLookUp.put("houseidentifier", houseIdentifier); - DefaultLookUp.put("initials", initials); - DefaultLookUp.put("internationalisdnnumber", internationalISDNNumber); - DefaultLookUp.put("l", l); - DefaultLookUp.put("member", member); - DefaultLookUp.put("name", name); - DefaultLookUp.put("o", o); - DefaultLookUp.put("ou", ou); - DefaultLookUp.put("owner", owner); - DefaultLookUp.put("physicaldeliveryofficename", physicalDeliveryOfficeName); - DefaultLookUp.put("postaladdress", postalAddress); - DefaultLookUp.put("postalcode", postalCode); - DefaultLookUp.put("postofficebox", postOfficeBox); - DefaultLookUp.put("preferreddeliverymethod", preferredDeliveryMethod); - DefaultLookUp.put("registeredaddress", registeredAddress); - DefaultLookUp.put("roleoccupant", roleOccupant); - DefaultLookUp.put("searchguide", searchGuide); - DefaultLookUp.put("seealso", seeAlso); - DefaultLookUp.put("serialnumber", serialNumber); - DefaultLookUp.put("sn", sn); - DefaultLookUp.put("st", st); - DefaultLookUp.put("street", street); - DefaultLookUp.put("telephonenumber", telephoneNumber); - DefaultLookUp.put("teletexterminalidentifier", teletexTerminalIdentifier); - DefaultLookUp.put("telexnumber", telexNumber); - DefaultLookUp.put("title", title); - DefaultLookUp.put("uid", uid); - DefaultLookUp.put("uniquemember", uniqueMember); - DefaultLookUp.put("userpassword", userPassword); - DefaultLookUp.put("x121address", x121Address); - DefaultLookUp.put("x500uniqueidentifier", x500UniqueIdentifier); - - // TODO: need to add correct matching for equality comparisons. - } - - /** - * Singleton instance. - */ - public static final X500NameStyle INSTANCE = new RFC4519Style(); - - protected Hashtable defaultLookUp; - protected Hashtable defaultSymbols; - - protected RFC4519Style() - { - defaultSymbols = copyHashTable(DefaultSymbols); - defaultLookUp = copyHashTable(DefaultLookUp); - } - - public ASN1Encodable stringToValue(ASN1ObjectIdentifier oid, String value) - { - if (value.length() != 0 && value.charAt(0) == '#') - { - try - { - return IETFUtils.valueFromHexString(value, 1); - } - catch (IOException e) - { - throw new RuntimeException("can't recode value for oid " + oid.getId()); - } - } - else - { - if (value.length() != 0 && value.charAt(0) == '\\') - { - value = value.substring(1); - } - if (oid.equals(dc)) - { - return new DERIA5String(value); - } - else if (oid.equals(c) || oid.equals(serialNumber) || oid.equals(dnQualifier) - || oid.equals(telephoneNumber)) - { - return new DERPrintableString(value); - } - } - - return new DERUTF8String(value); - } - - public String oidToDisplayName(ASN1ObjectIdentifier oid) - { - return (String)DefaultSymbols.get(oid); - } - - public String[] oidToAttrNames(ASN1ObjectIdentifier oid) - { - return IETFUtils.findAttrNamesForOID(oid, defaultLookUp); - } - - public ASN1ObjectIdentifier attrNameToOID(String attrName) - { - return IETFUtils.decodeAttrName(attrName, defaultLookUp); - } - - public boolean areEqual(X500Name name1, X500Name name2) - { - RDN[] rdns1 = name1.getRDNs(); - RDN[] rdns2 = name2.getRDNs(); - - if (rdns1.length != rdns2.length) - { - return false; - } - - boolean reverse = false; - - if (rdns1[0].getFirst() != null && rdns2[0].getFirst() != null) - { - reverse = !rdns1[0].getFirst().getType().equals(rdns2[0].getFirst().getType()); // guess forward - } - - for (int i = 0; i != rdns1.length; i++) - { - if (!foundMatch(reverse, rdns1[i], rdns2)) - { - return false; - } - } - - return true; - } - - private boolean foundMatch(boolean reverse, RDN rdn, RDN[] possRDNs) - { - if (reverse) - { - for (int i = possRDNs.length - 1; i >= 0; i--) - { - if (possRDNs[i] != null && rdnAreEqual(rdn, possRDNs[i])) - { - possRDNs[i] = null; - return true; - } - } - } - else - { - for (int i = 0; i != possRDNs.length; i++) - { - if (possRDNs[i] != null && rdnAreEqual(rdn, possRDNs[i])) - { - possRDNs[i] = null; - return true; - } - } - } - - return false; - } - - protected boolean rdnAreEqual(RDN rdn1, RDN rdn2) - { - return IETFUtils.rDNAreEqual(rdn1, rdn2); - } - - // parse backwards - public RDN[] fromString(String dirName) - { - RDN[] tmp = IETFUtils.rDNsFromString(dirName, this); - RDN[] res = new RDN[tmp.length]; - - for (int i = 0; i != tmp.length; i++) - { - res[res.length - i - 1] = tmp[i]; - } - - return res; - } - - public int calculateHashCode(X500Name name) - { - int hashCodeValue = 0; - RDN[] rdns = name.getRDNs(); - - // this needs to be order independent, like equals - for (int i = 0; i != rdns.length; i++) - { - if (rdns[i].isMultiValued()) - { - AttributeTypeAndValue[] atv = rdns[i].getTypesAndValues(); - - for (int j = 0; j != atv.length; j++) - { - hashCodeValue ^= atv[j].getType().hashCode(); - hashCodeValue ^= calcHashCode(atv[j].getValue()); - } - } - else - { - hashCodeValue ^= rdns[i].getFirst().getType().hashCode(); - hashCodeValue ^= calcHashCode(rdns[i].getFirst().getValue()); - } - } - - return hashCodeValue; - } - - private int calcHashCode(ASN1Encodable enc) - { - String value = IETFUtils.valueToString(enc); - - value = IETFUtils.canonicalize(value); - - return value.hashCode(); - } - - // convert in reverse - public String toString(X500Name name) - { - StringBuffer buf = new StringBuffer(); - boolean first = true; - - RDN[] rdns = name.getRDNs(); - - for (int i = rdns.length - 1; i >= 0; i--) - { - if (first) - { - first = false; - } - else - { - buf.append(','); - } - - IETFUtils.appendRDN(buf, rdns[i], defaultSymbols); - } - - return buf.toString(); - } - - private static Hashtable copyHashTable(Hashtable paramsMap) - { - Hashtable newTable = new Hashtable(); - - Enumeration keys = paramsMap.keys(); - while (keys.hasMoreElements()) - { - Object key = keys.nextElement(); - newTable.put(key, paramsMap.get(key)); - } - - return newTable; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/agreement/jpake/JPAKEParticipant.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/agreement/jpake/JPAKEParticipant.java deleted file mode 100644 index 17554b960..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/agreement/jpake/JPAKEParticipant.java +++ /dev/null @@ -1,573 +0,0 @@ -package org.spongycastle.crypto.agreement.jpake; - -import java.math.BigInteger; -import java.security.SecureRandom; - -import org.spongycastle.crypto.CryptoException; -import org.spongycastle.crypto.Digest; -import org.spongycastle.crypto.digests.SHA256Digest; -import org.spongycastle.util.Arrays; - -/** - * A participant in a Password Authenticated Key Exchange by Juggling (J-PAKE) exchange. - *

- *

- * The J-PAKE exchange is defined by Feng Hao and Peter Ryan in the paper - * - * "Password Authenticated Key Exchange by Juggling, 2008." - *

- *

- * The J-PAKE protocol is symmetric. - * There is no notion of a client or server, but rather just two participants. - * An instance of {@link JPAKEParticipant} represents one participant, and - * is the primary interface for executing the exchange. - *

- *

- * To execute an exchange, construct a {@link JPAKEParticipant} on each end, - * and call the following 7 methods - * (once and only once, in the given order, for each participant, sending messages between them as described): - *

    - *
  1. {@link #createRound1PayloadToSend()} - and send the payload to the other participant
  2. - *
  3. {@link #validateRound1PayloadReceived(JPAKERound1Payload)} - use the payload received from the other participant
  4. - *
  5. {@link #createRound2PayloadToSend()} - and send the payload to the other participant
  6. - *
  7. {@link #validateRound2PayloadReceived(JPAKERound2Payload)} - use the payload received from the other participant
  8. - *
  9. {@link #calculateKeyingMaterial()}
  10. - *
  11. {@link #createRound3PayloadToSend(BigInteger)} - and send the payload to the other participant
  12. - *
  13. {@link #validateRound3PayloadReceived(JPAKERound3Payload, BigInteger)} - use the payload received from the other participant
  14. - *
- *

- *

- * Each side should derive a session key from the keying material returned by {@link #calculateKeyingMaterial()}. - * The caller is responsible for deriving the session key using a secure key derivation function (KDF). - *

- *

- * Round 3 is an optional key confirmation process. - * If you do not execute round 3, then there is no assurance that both participants are using the same key. - * (i.e. if the participants used different passwords, then their session keys will differ.) - *

- *

- * If the round 3 validation succeeds, then the keys are guaranteed to be the same on both sides. - *

- *

- * The symmetric design can easily support the asymmetric cases when one party initiates the communication. - * e.g. Sometimes the round1 payload and round2 payload may be sent in one pass. - * Also, in some cases, the key confirmation payload can be sent together with the round2 payload. - * These are the trivial techniques to optimize the communication. - *

- *

- * The key confirmation process is implemented as specified in - * NIST SP 800-56A Revision 1, - * Section 8.2 Unilateral Key Confirmation for Key Agreement Schemes. - *

- *

- * This class is stateful and NOT threadsafe. - * Each instance should only be used for ONE complete J-PAKE exchange - * (i.e. a new {@link JPAKEParticipant} should be constructed for each new J-PAKE exchange). - *

- *

- * See {@link JPAKEExample} for example usage. - */ -public class JPAKEParticipant -{ - /* - * Possible internal states. Used for state checking. - */ - - public static final int STATE_INITIALIZED = 0; - public static final int STATE_ROUND_1_CREATED = 10; - public static final int STATE_ROUND_1_VALIDATED = 20; - public static final int STATE_ROUND_2_CREATED = 30; - public static final int STATE_ROUND_2_VALIDATED = 40; - public static final int STATE_KEY_CALCULATED = 50; - public static final int STATE_ROUND_3_CREATED = 60; - public static final int STATE_ROUND_3_VALIDATED = 70; - - /** - * Unique identifier of this participant. - * The two participants in the exchange must NOT share the same id. - */ - private String participantId; - - /** - * Shared secret. This only contains the secret between construction - * and the call to {@link #calculateKeyingMaterial()}. - *

- * i.e. When {@link #calculateKeyingMaterial()} is called, this buffer overwritten with 0's, - * and the field is set to null. - */ - private char[] password; - - /** - * Digest to use during calculations. - */ - private Digest digest; - - /** - * Source of secure random data. - */ - private SecureRandom random; - - private BigInteger p; - private BigInteger q; - private BigInteger g; - - /** - * The participantId of the other participant in this exchange. - */ - private String partnerParticipantId; - - /** - * Alice's x1 or Bob's x3. - */ - private BigInteger x1; - /** - * Alice's x2 or Bob's x4. - */ - private BigInteger x2; - /** - * Alice's g^x1 or Bob's g^x3. - */ - private BigInteger gx1; - /** - * Alice's g^x2 or Bob's g^x4. - */ - private BigInteger gx2; - /** - * Alice's g^x3 or Bob's g^x1. - */ - private BigInteger gx3; - /** - * Alice's g^x4 or Bob's g^x2. - */ - private BigInteger gx4; - /** - * Alice's B or Bob's A. - */ - private BigInteger b; - - /** - * The current state. - * See the STATE_* constants for possible values. - */ - private int state; - - /** - * Convenience constructor for a new {@link JPAKEParticipant} that uses - * the {@link JPAKEPrimeOrderGroups#NIST_3072} prime order group, - * a SHA-256 digest, and a default {@link SecureRandom} implementation. - *

- * After construction, the {@link #getState() state} will be {@link #STATE_INITIALIZED}. - * - * @param participantId unique identifier of this participant. - * The two participants in the exchange must NOT share the same id. - * @param password shared secret. - * A defensive copy of this array is made (and cleared once {@link #calculateKeyingMaterial()} is called). - * Caller should clear the input password as soon as possible. - * @throws NullPointerException if any argument is null - * @throws IllegalArgumentException if password is empty - */ - public JPAKEParticipant( - String participantId, - char[] password) - { - this( - participantId, - password, - JPAKEPrimeOrderGroups.NIST_3072); - } - - - /** - * Convenience constructor for a new {@link JPAKEParticipant} that uses - * a SHA-256 digest and a default {@link SecureRandom} implementation. - *

- * After construction, the {@link #getState() state} will be {@link #STATE_INITIALIZED}. - * - * @param participantId unique identifier of this participant. - * The two participants in the exchange must NOT share the same id. - * @param password shared secret. - * A defensive copy of this array is made (and cleared once {@link #calculateKeyingMaterial()} is called). - * Caller should clear the input password as soon as possible. - * @param group prime order group. - * See {@link JPAKEPrimeOrderGroups} for standard groups - * @throws NullPointerException if any argument is null - * @throws IllegalArgumentException if password is empty - */ - public JPAKEParticipant( - String participantId, - char[] password, - JPAKEPrimeOrderGroup group) - { - this( - participantId, - password, - group, - new SHA256Digest(), - new SecureRandom()); - } - - - /** - * Construct a new {@link JPAKEParticipant}. - *

- * After construction, the {@link #getState() state} will be {@link #STATE_INITIALIZED}. - * - * @param participantId unique identifier of this participant. - * The two participants in the exchange must NOT share the same id. - * @param password shared secret. - * A defensive copy of this array is made (and cleared once {@link #calculateKeyingMaterial()} is called). - * Caller should clear the input password as soon as possible. - * @param group prime order group. - * See {@link JPAKEPrimeOrderGroups} for standard groups - * @param digest digest to use during zero knowledge proofs and key confirmation (SHA-256 or stronger preferred) - * @param random source of secure random data for x1 and x2, and for the zero knowledge proofs - * @throws NullPointerException if any argument is null - * @throws IllegalArgumentException if password is empty - */ - public JPAKEParticipant( - String participantId, - char[] password, - JPAKEPrimeOrderGroup group, - Digest digest, - SecureRandom random) - { - JPAKEUtil.validateNotNull(participantId, "participantId"); - JPAKEUtil.validateNotNull(password, "password"); - JPAKEUtil.validateNotNull(group, "p"); - JPAKEUtil.validateNotNull(digest, "digest"); - JPAKEUtil.validateNotNull(random, "random"); - if (password.length == 0) - { - throw new IllegalArgumentException("Password must not be empty."); - } - - this.participantId = participantId; - - /* - * Create a defensive copy so as to fully encapsulate the password. - * - * This array will contain the password for the lifetime of this - * participant BEFORE {@link #calculateKeyingMaterial()} is called. - * - * i.e. When {@link #calculateKeyingMaterial()} is called, the array will be cleared - * in order to remove the password from memory. - * - * The caller is responsible for clearing the original password array - * given as input to this constructor. - */ - this.password = Arrays.copyOf(password, password.length); - - this.p = group.getP(); - this.q = group.getQ(); - this.g = group.getG(); - - this.digest = digest; - this.random = random; - - this.state = STATE_INITIALIZED; - } - - /** - * Gets the current state of this participant. - * See the STATE_* constants for possible values. - */ - public int getState() - { - return this.state; - } - - /** - * Creates and returns the payload to send to the other participant during round 1. - *

- *

- * After execution, the {@link #getState() state} will be {@link #STATE_ROUND_1_CREATED}. - */ - public JPAKERound1Payload createRound1PayloadToSend() - { - if (this.state >= STATE_ROUND_1_CREATED) - { - throw new IllegalStateException("Round1 payload already created for " + participantId); - } - - this.x1 = JPAKEUtil.generateX1(q, random); - this.x2 = JPAKEUtil.generateX2(q, random); - - this.gx1 = JPAKEUtil.calculateGx(p, g, x1); - this.gx2 = JPAKEUtil.calculateGx(p, g, x2); - BigInteger[] knowledgeProofForX1 = JPAKEUtil.calculateZeroKnowledgeProof(p, q, g, gx1, x1, participantId, digest, random); - BigInteger[] knowledgeProofForX2 = JPAKEUtil.calculateZeroKnowledgeProof(p, q, g, gx2, x2, participantId, digest, random); - - this.state = STATE_ROUND_1_CREATED; - - return new JPAKERound1Payload(participantId, gx1, gx2, knowledgeProofForX1, knowledgeProofForX2); - } - - /** - * Validates the payload received from the other participant during round 1. - *

- *

- * Must be called prior to {@link #createRound2PayloadToSend()}. - *

- *

- * After execution, the {@link #getState() state} will be {@link #STATE_ROUND_1_VALIDATED}. - * - * @throws CryptoException if validation fails. - * @throws IllegalStateException if called multiple times. - */ - public void validateRound1PayloadReceived(JPAKERound1Payload round1PayloadReceived) - throws CryptoException - { - if (this.state >= STATE_ROUND_1_VALIDATED) - { - throw new IllegalStateException("Validation already attempted for round1 payload for" + participantId); - } - this.partnerParticipantId = round1PayloadReceived.getParticipantId(); - this.gx3 = round1PayloadReceived.getGx1(); - this.gx4 = round1PayloadReceived.getGx2(); - - BigInteger[] knowledgeProofForX3 = round1PayloadReceived.getKnowledgeProofForX1(); - BigInteger[] knowledgeProofForX4 = round1PayloadReceived.getKnowledgeProofForX2(); - - JPAKEUtil.validateParticipantIdsDiffer(participantId, round1PayloadReceived.getParticipantId()); - JPAKEUtil.validateGx4(gx4); - JPAKEUtil.validateZeroKnowledgeProof(p, q, g, gx3, knowledgeProofForX3, round1PayloadReceived.getParticipantId(), digest); - JPAKEUtil.validateZeroKnowledgeProof(p, q, g, gx4, knowledgeProofForX4, round1PayloadReceived.getParticipantId(), digest); - - this.state = STATE_ROUND_1_VALIDATED; - } - - /** - * Creates and returns the payload to send to the other participant during round 2. - *

- *

- * {@link #validateRound1PayloadReceived(JPAKERound1Payload)} must be called prior to this method. - *

- *

- * After execution, the {@link #getState() state} will be {@link #STATE_ROUND_2_CREATED}. - * - * @throws IllegalStateException if called prior to {@link #validateRound1PayloadReceived(JPAKERound1Payload)}, or multiple times - */ - public JPAKERound2Payload createRound2PayloadToSend() - { - if (this.state >= STATE_ROUND_2_CREATED) - { - throw new IllegalStateException("Round2 payload already created for " + this.participantId); - } - if (this.state < STATE_ROUND_1_VALIDATED) - { - throw new IllegalStateException("Round1 payload must be validated prior to creating Round2 payload for " + this.participantId); - } - BigInteger gA = JPAKEUtil.calculateGA(p, gx1, gx3, gx4); - BigInteger s = JPAKEUtil.calculateS(password); - BigInteger x2s = JPAKEUtil.calculateX2s(q, x2, s); - BigInteger A = JPAKEUtil.calculateA(p, q, gA, x2s); - BigInteger[] knowledgeProofForX2s = JPAKEUtil.calculateZeroKnowledgeProof(p, q, gA, A, x2s, participantId, digest, random); - - this.state = STATE_ROUND_2_CREATED; - - return new JPAKERound2Payload(participantId, A, knowledgeProofForX2s); - } - - /** - * Validates the payload received from the other participant during round 2. - *

- *

- * Note that this DOES NOT detect a non-common password. - * The only indication of a non-common password is through derivation - * of different keys (which can be detected explicitly by executing round 3 and round 4) - *

- *

- * Must be called prior to {@link #calculateKeyingMaterial()}. - *

- *

- * After execution, the {@link #getState() state} will be {@link #STATE_ROUND_2_VALIDATED}. - * - * @throws CryptoException if validation fails. - * @throws IllegalStateException if called prior to {@link #validateRound1PayloadReceived(JPAKERound1Payload)}, or multiple times - */ - public void validateRound2PayloadReceived(JPAKERound2Payload round2PayloadReceived) - throws CryptoException - { - if (this.state >= STATE_ROUND_2_VALIDATED) - { - throw new IllegalStateException("Validation already attempted for round2 payload for" + participantId); - } - if (this.state < STATE_ROUND_1_VALIDATED) - { - throw new IllegalStateException("Round1 payload must be validated prior to validating Round2 payload for " + this.participantId); - } - BigInteger gB = JPAKEUtil.calculateGA(p, gx3, gx1, gx2); - this.b = round2PayloadReceived.getA(); - BigInteger[] knowledgeProofForX4s = round2PayloadReceived.getKnowledgeProofForX2s(); - - JPAKEUtil.validateParticipantIdsDiffer(participantId, round2PayloadReceived.getParticipantId()); - JPAKEUtil.validateParticipantIdsEqual(this.partnerParticipantId, round2PayloadReceived.getParticipantId()); - JPAKEUtil.validateGa(gB); - JPAKEUtil.validateZeroKnowledgeProof(p, q, gB, b, knowledgeProofForX4s, round2PayloadReceived.getParticipantId(), digest); - - this.state = STATE_ROUND_2_VALIDATED; - } - - /** - * Calculates and returns the key material. - * A session key must be derived from this key material using a secure key derivation function (KDF). - * The KDF used to derive the key is handled externally (i.e. not by {@link JPAKEParticipant}). - *

- *

- * The keying material will be identical for each participant if and only if - * each participant's password is the same. i.e. If the participants do not - * share the same password, then each participant will derive a different key. - * Therefore, if you immediately start using a key derived from - * the keying material, then you must handle detection of incorrect keys. - * If you want to handle this detection explicitly, you can optionally perform - * rounds 3 and 4. See {@link JPAKEParticipant} for details on how to execute - * rounds 3 and 4. - *

- *

- * The keying material will be in the range [0, p-1]. - *

- *

- * {@link #validateRound2PayloadReceived(JPAKERound2Payload)} must be called prior to this method. - *

- *

- * As a side effect, the internal {@link #password} array is cleared, since it is no longer needed. - *

- *

- * After execution, the {@link #getState() state} will be {@link #STATE_KEY_CALCULATED}. - * - * @throws IllegalStateException if called prior to {@link #validateRound2PayloadReceived(JPAKERound2Payload)}, - * or if called multiple times. - */ - public BigInteger calculateKeyingMaterial() - { - if (this.state >= STATE_KEY_CALCULATED) - { - throw new IllegalStateException("Key already calculated for " + participantId); - } - if (this.state < STATE_ROUND_2_VALIDATED) - { - throw new IllegalStateException("Round2 payload must be validated prior to creating key for " + participantId); - } - BigInteger s = JPAKEUtil.calculateS(password); - - /* - * Clear the password array from memory, since we don't need it anymore. - * - * Also set the field to null as a flag to indicate that the key has already been calculated. - */ - Arrays.fill(password, (char)0); - this.password = null; - - BigInteger keyingMaterial = JPAKEUtil.calculateKeyingMaterial(p, q, gx4, x2, s, b); - - /* - * Clear the ephemeral private key fields as well. - * Note that we're relying on the garbage collector to do its job to clean these up. - * The old objects will hang around in memory until the garbage collector destroys them. - * - * If the ephemeral private keys x1 and x2 are leaked, - * the attacker might be able to brute-force the password. - */ - this.x1 = null; - this.x2 = null; - this.b = null; - - /* - * Do not clear gx* yet, since those are needed by round 3. - */ - - this.state = STATE_KEY_CALCULATED; - - return keyingMaterial; - } - - - /** - * Creates and returns the payload to send to the other participant during round 3. - *

- *

- * See {@link JPAKEParticipant} for more details on round 3. - *

- *

- * After execution, the {@link #getState() state} will be {@link #STATE_ROUND_3_CREATED}. - * - * @param keyingMaterial The keying material as returned from {@link #calculateKeyingMaterial()}. - * @throws IllegalStateException if called prior to {@link #calculateKeyingMaterial()}, or multiple times - */ - public JPAKERound3Payload createRound3PayloadToSend(BigInteger keyingMaterial) - { - if (this.state >= STATE_ROUND_3_CREATED) - { - throw new IllegalStateException("Round3 payload already created for " + this.participantId); - } - if (this.state < STATE_KEY_CALCULATED) - { - throw new IllegalStateException("Keying material must be calculated prior to creating Round3 payload for " + this.participantId); - } - - BigInteger macTag = JPAKEUtil.calculateMacTag( - this.participantId, - this.partnerParticipantId, - this.gx1, - this.gx2, - this.gx3, - this.gx4, - keyingMaterial, - this.digest); - - this.state = STATE_ROUND_3_CREATED; - - return new JPAKERound3Payload(participantId, macTag); - } - - /** - * Validates the payload received from the other participant during round 3. - *

- *

- * See {@link JPAKEParticipant} for more details on round 3. - *

- *

- * After execution, the {@link #getState() state} will be {@link #STATE_ROUND_3_VALIDATED}. - * - * @param keyingMaterial The keying material as returned from {@link #calculateKeyingMaterial()}. - * @throws CryptoException if validation fails. - * @throws IllegalStateException if called prior to {@link #calculateKeyingMaterial()}, or multiple times - */ - public void validateRound3PayloadReceived(JPAKERound3Payload round3PayloadReceived, BigInteger keyingMaterial) - throws CryptoException - { - if (this.state >= STATE_ROUND_3_VALIDATED) - { - throw new IllegalStateException("Validation already attempted for round3 payload for" + participantId); - } - if (this.state < STATE_KEY_CALCULATED) - { - throw new IllegalStateException("Keying material must be calculated validated prior to validating Round3 payload for " + this.participantId); - } - JPAKEUtil.validateParticipantIdsDiffer(participantId, round3PayloadReceived.getParticipantId()); - JPAKEUtil.validateParticipantIdsEqual(this.partnerParticipantId, round3PayloadReceived.getParticipantId()); - - JPAKEUtil.validateMacTag( - this.participantId, - this.partnerParticipantId, - this.gx1, - this.gx2, - this.gx3, - this.gx4, - keyingMaterial, - this.digest, - round3PayloadReceived.getMacTag()); - - - /* - * Clear the rest of the fields. - */ - this.gx1 = null; - this.gx2 = null; - this.gx3 = null; - this.gx4 = null; - - this.state = STATE_ROUND_3_VALIDATED; - } - -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/agreement/jpake/JPAKEPrimeOrderGroup.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/agreement/jpake/JPAKEPrimeOrderGroup.java deleted file mode 100644 index 59e93385c..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/agreement/jpake/JPAKEPrimeOrderGroup.java +++ /dev/null @@ -1,122 +0,0 @@ -package org.spongycastle.crypto.agreement.jpake; - -import java.math.BigInteger; - -/** - * A pre-computed prime order group for use during a J-PAKE exchange. - *

- *

- * Typically a Schnorr group is used. In general, J-PAKE can use any prime order group - * that is suitable for public key cryptography, including elliptic curve cryptography. - *

- *

- * See {@link JPAKEPrimeOrderGroups} for convenient standard groups. - *

- *

- * NIST publishes - * many groups that can be used for the desired level of security. - */ -public class JPAKEPrimeOrderGroup -{ - private BigInteger p; - private BigInteger q; - private BigInteger g; - - /** - * Constructs a new {@link JPAKEPrimeOrderGroup}. - *

- *

- * In general, you should use one of the pre-approved groups from - * {@link JPAKEPrimeOrderGroups}, rather than manually constructing one. - *

- *

- * The following basic checks are performed: - *

    - *
  • p-1 must be evenly divisible by q
  • - *
  • g must be in [2, p-1]
  • - *
  • g^q mod p must equal 1
  • - *
  • p must be prime (within reasonably certainty)
  • - *
  • q must be prime (within reasonably certainty)
  • - *
- *

- *

- * The prime checks are performed using {@link BigInteger#isProbablePrime(int)}, - * and are therefore subject to the same probability guarantees. - *

- *

- * These checks prevent trivial mistakes. - * However, due to the small uncertainties if p and q are not prime, - * advanced attacks are not prevented. - * Use it at your own risk. - * - * @throws NullPointerException if any argument is null - * @throws IllegalArgumentException if any of the above validations fail - */ - public JPAKEPrimeOrderGroup(BigInteger p, BigInteger q, BigInteger g) - { - /* - * Don't skip the checks on user-specified groups. - */ - this(p, q, g, false); - } - - /** - * Internal package-private constructor used by the pre-approved - * groups in {@link JPAKEPrimeOrderGroups}. - * These pre-approved groups can avoid the expensive checks. - */ - JPAKEPrimeOrderGroup(BigInteger p, BigInteger q, BigInteger g, boolean skipChecks) - { - JPAKEUtil.validateNotNull(p, "p"); - JPAKEUtil.validateNotNull(q, "q"); - JPAKEUtil.validateNotNull(g, "g"); - - if (!skipChecks) - { - if (!p.subtract(JPAKEUtil.ONE).mod(q).equals(JPAKEUtil.ZERO)) - { - throw new IllegalArgumentException("p-1 must be evenly divisible by q"); - } - if (g.compareTo(BigInteger.valueOf(2)) == -1 || g.compareTo(p.subtract(JPAKEUtil.ONE)) == 1) - { - throw new IllegalArgumentException("g must be in [2, p-1]"); - } - if (!g.modPow(q, p).equals(JPAKEUtil.ONE)) - { - throw new IllegalArgumentException("g^q mod p must equal 1"); - } - /* - * Note that these checks do not guarantee that p and q are prime. - * We just have reasonable certainty that they are prime. - */ - if (!p.isProbablePrime(20)) - { - throw new IllegalArgumentException("p must be prime"); - } - if (!q.isProbablePrime(20)) - { - throw new IllegalArgumentException("q must be prime"); - } - } - - this.p = p; - this.q = q; - this.g = g; - } - - public BigInteger getP() - { - return p; - } - - public BigInteger getQ() - { - return q; - } - - public BigInteger getG() - { - return g; - } - -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/digests/SkeinEngine.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/digests/SkeinEngine.java deleted file mode 100644 index a278ff4e4..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/digests/SkeinEngine.java +++ /dev/null @@ -1,817 +0,0 @@ -package org.spongycastle.crypto.digests; - -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Vector; - -import org.spongycastle.crypto.DataLengthException; -import org.spongycastle.crypto.engines.ThreefishEngine; -import org.spongycastle.crypto.macs.SkeinMac; -import org.spongycastle.crypto.params.SkeinParameters; -import org.spongycastle.util.Arrays; -import org.spongycastle.util.Memoable; - -/** - * Implementation of the Skein family of parameterised hash functions in 256, 512 and 1024 bit block - * sizes, based on the {@link ThreefishEngine Threefish} tweakable block cipher. - *

- * This is the 1.3 version of Skein defined in the Skein hash function submission to the NIST SHA-3 - * competition in October 2010. - *

- * Skein was designed by Niels Ferguson - Stefan Lucks - Bruce Schneier - Doug Whiting - Mihir - * Bellare - Tadayoshi Kohno - Jon Callas - Jesse Walker. - *

- * This implementation is the basis for {@link SkeinDigest} and {@link SkeinMac}, implementing the - * parameter based configuration system that allows Skein to be adapted to multiple applications.
- * Initialising the engine with {@link SkeinParameters} allows standard and arbitrary parameters to - * be applied during the Skein hash function. - *

- * Implemented: - *

    - *
  • 256, 512 and 1024 bit internal states.
  • - *
  • Full 96 bit input length.
  • - *
  • Parameters defined in the Skein specification, and arbitrary other pre and post message - * parameters.
  • - *
  • Arbitrary output size in 1 byte intervals.
  • - *
- *

- * Not implemented: - *

    - *
  • Sub-byte length input (bit padding).
  • - *
  • Tree hashing.
  • - *
- * - * @see SkeinParameters - */ -public class SkeinEngine - implements Memoable -{ - /** - * 256 bit block size - Skein 256 - */ - public static final int SKEIN_256 = ThreefishEngine.BLOCKSIZE_256; - /** - * 512 bit block size - Skein 512 - */ - public static final int SKEIN_512 = ThreefishEngine.BLOCKSIZE_512; - /** - * 1024 bit block size - Skein 1024 - */ - public static final int SKEIN_1024 = ThreefishEngine.BLOCKSIZE_1024; - - // Minimal at present, but more complex when tree hashing is implemented - private static class Configuration - { - private byte[] bytes = new byte[32]; - - public Configuration(long outputSizeBits) - { - // 0..3 = ASCII SHA3 - bytes[0] = (byte)'S'; - bytes[1] = (byte)'H'; - bytes[2] = (byte)'A'; - bytes[3] = (byte)'3'; - - // 4..5 = version number in LSB order - bytes[4] = 1; - bytes[5] = 0; - - // 8..15 = output length - ThreefishEngine.wordToBytes(outputSizeBits, bytes, 8); - } - - public byte[] getBytes() - { - return bytes; - } - - } - - public static class Parameter - { - private int type; - private byte[] value; - - public Parameter(int type, byte[] value) - { - this.type = type; - this.value = value; - } - - public int getType() - { - return type; - } - - public byte[] getValue() - { - return value; - } - - } - - /** - * The parameter type for the Skein key. - */ - private static final int PARAM_TYPE_KEY = 0; - - /** - * The parameter type for the Skein configuration block. - */ - private static final int PARAM_TYPE_CONFIG = 4; - - /** - * The parameter type for the message. - */ - private static final int PARAM_TYPE_MESSAGE = 48; - - /** - * The parameter type for the output transformation. - */ - private static final int PARAM_TYPE_OUTPUT = 63; - - /** - * Precalculated UBI(CFG) states for common state/output combinations without key or other - * pre-message params. - */ - private static final Hashtable INITIAL_STATES = new Hashtable(); - - static - { - // From Appendix C of the Skein 1.3 NIST submission - initialState(SKEIN_256, 128, new long[]{ - 0xe1111906964d7260L, - 0x883daaa77c8d811cL, - 0x10080df491960f7aL, - 0xccf7dde5b45bc1c2L}); - - initialState(SKEIN_256, 160, new long[]{ - 0x1420231472825e98L, - 0x2ac4e9a25a77e590L, - 0xd47a58568838d63eL, - 0x2dd2e4968586ab7dL}); - - initialState(SKEIN_256, 224, new long[]{ - 0xc6098a8c9ae5ea0bL, - 0x876d568608c5191cL, - 0x99cb88d7d7f53884L, - 0x384bddb1aeddb5deL}); - - initialState(SKEIN_256, 256, new long[]{ - 0xfc9da860d048b449L, - 0x2fca66479fa7d833L, - 0xb33bc3896656840fL, - 0x6a54e920fde8da69L}); - - initialState(SKEIN_512, 128, new long[]{ - 0xa8bc7bf36fbf9f52L, - 0x1e9872cebd1af0aaL, - 0x309b1790b32190d3L, - 0xbcfbb8543f94805cL, - 0x0da61bcd6e31b11bL, - 0x1a18ebead46a32e3L, - 0xa2cc5b18ce84aa82L, - 0x6982ab289d46982dL}); - - initialState(SKEIN_512, 160, new long[]{ - 0x28b81a2ae013bd91L, - 0xc2f11668b5bdf78fL, - 0x1760d8f3f6a56f12L, - 0x4fb747588239904fL, - 0x21ede07f7eaf5056L, - 0xd908922e63ed70b8L, - 0xb8ec76ffeccb52faL, - 0x01a47bb8a3f27a6eL}); - - initialState(SKEIN_512, 224, new long[]{ - 0xccd0616248677224L, - 0xcba65cf3a92339efL, - 0x8ccd69d652ff4b64L, - 0x398aed7b3ab890b4L, - 0x0f59d1b1457d2bd0L, - 0x6776fe6575d4eb3dL, - 0x99fbc70e997413e9L, - 0x9e2cfccfe1c41ef7L}); - - initialState(SKEIN_512, 384, new long[]{ - 0xa3f6c6bf3a75ef5fL, - 0xb0fef9ccfd84faa4L, - 0x9d77dd663d770cfeL, - 0xd798cbf3b468fddaL, - 0x1bc4a6668a0e4465L, - 0x7ed7d434e5807407L, - 0x548fc1acd4ec44d6L, - 0x266e17546aa18ff8L}); - - initialState(SKEIN_512, 512, new long[]{ - 0x4903adff749c51ceL, - 0x0d95de399746df03L, - 0x8fd1934127c79bceL, - 0x9a255629ff352cb1L, - 0x5db62599df6ca7b0L, - 0xeabe394ca9d5c3f4L, - 0x991112c71a75b523L, - 0xae18a40b660fcc33L}); - } - - private static void initialState(int blockSize, int outputSize, long[] state) - { - INITIAL_STATES.put(variantIdentifier(blockSize / 8, outputSize / 8), state); - } - - private static Integer variantIdentifier(int blockSizeBytes, int outputSizeBytes) - { - return new Integer((outputSizeBytes << 16) | blockSizeBytes); - } - - private static class UbiTweak - { - /** - * Point at which position might overflow long, so switch to add with carry logic - */ - private static final long LOW_RANGE = Long.MAX_VALUE - Integer.MAX_VALUE; - - /** - * Bit 127 = final - */ - private static final long T1_FINAL = 1L << 63; - - /** - * Bit 126 = first - */ - private static final long T1_FIRST = 1L << 62; - - /** - * UBI uses a 128 bit tweak - */ - private long tweak[] = new long[2]; - - /** - * Whether 64 bit position exceeded - */ - private boolean extendedPosition; - - public UbiTweak() - { - reset(); - } - - public void reset(UbiTweak tweak) - { - this.tweak = Arrays.clone(tweak.tweak, this.tweak); - this.extendedPosition = tweak.extendedPosition; - } - - public void reset() - { - tweak[0] = 0; - tweak[1] = 0; - extendedPosition = false; - setFirst(true); - } - - public void setType(int type) - { - // Bits 120..125 = type - tweak[1] = (tweak[1] & 0xFFFFFFC000000000L) | ((type & 0x3FL) << 56); - } - - public int getType() - { - return (int)((tweak[1] >>> 56) & 0x3FL); - } - - public void setFirst(boolean first) - { - if (first) - { - tweak[1] |= T1_FIRST; - } - else - { - tweak[1] &= ~T1_FIRST; - } - } - - public boolean isFirst() - { - return ((tweak[1] & T1_FIRST) != 0); - } - - public void setFinal(boolean last) - { - if (last) - { - tweak[1] |= T1_FINAL; - } - else - { - tweak[1] &= ~T1_FINAL; - } - } - - public boolean isFinal() - { - return ((tweak[1] & T1_FINAL) != 0); - } - - /** - * Advances the position in the tweak by the specified value. - */ - public void advancePosition(int advance) - { - // Bits 0..95 = position - if (extendedPosition) - { - long[] parts = new long[3]; - parts[0] = tweak[0] & 0xFFFFFFFFL; - parts[1] = (tweak[0] >>> 32) & 0xFFFFFFFFL; - parts[2] = tweak[1] & 0xFFFFFFFFL; - - long carry = advance; - for (int i = 0; i < parts.length; i++) - { - carry += parts[i]; - parts[i] = carry; - carry >>>= 32; - } - tweak[0] = ((parts[1] & 0xFFFFFFFFL) << 32) | (parts[0] & 0xFFFFFFFFL); - tweak[1] = (tweak[1] & 0xFFFFFFFF00000000L) | (parts[2] & 0xFFFFFFFFL); - } - else - { - long position = tweak[0]; - position += advance; - tweak[0] = position; - if (position > LOW_RANGE) - { - extendedPosition = true; - } - } - } - - public long[] getWords() - { - return tweak; - } - - public String toString() - { - return getType() + " first: " + isFirst() + ", final: " + isFinal(); - } - - } - - /** - * The Unique Block Iteration chaining mode. - */ - // TODO: This might be better as methods... - private class UBI - { - private final UbiTweak tweak = new UbiTweak(); - - /** - * Buffer for the current block of message data - */ - private byte[] currentBlock; - - /** - * Offset into the current message block - */ - private int currentOffset; - - /** - * Buffer for message words for feedback into encrypted block - */ - private long[] message; - - public UBI(int blockSize) - { - currentBlock = new byte[blockSize]; - message = new long[currentBlock.length / 8]; - } - - public void reset(UBI ubi) - { - currentBlock = Arrays.clone(ubi.currentBlock, currentBlock); - currentOffset = ubi.currentOffset; - message = Arrays.clone(ubi.message, this.message); - tweak.reset(ubi.tweak); - } - - public void reset(int type) - { - tweak.reset(); - tweak.setType(type); - currentOffset = 0; - } - - public void update(byte[] value, int offset, int len, long[] output) - { - /* - * Buffer complete blocks for the underlying Threefish cipher, only flushing when there - * are subsequent bytes (last block must be processed in doFinal() with final=true set). - */ - int copied = 0; - while (len > copied) - { - if (currentOffset == currentBlock.length) - { - processBlock(output); - tweak.setFirst(false); - currentOffset = 0; - } - - int toCopy = Math.min((len - copied), currentBlock.length - currentOffset); - System.arraycopy(value, offset + copied, currentBlock, currentOffset, toCopy); - copied += toCopy; - currentOffset += toCopy; - tweak.advancePosition(toCopy); - } - } - - private void processBlock(long[] output) - { - threefish.init(true, chain, tweak.getWords()); - for (int i = 0; i < message.length; i++) - { - message[i] = ThreefishEngine.bytesToWord(currentBlock, i * 8); - } - - threefish.processBlock(message, output); - - for (int i = 0; i < output.length; i++) - { - output[i] ^= message[i]; - } - } - - public void doFinal(long[] output) - { - // Pad remainder of current block with zeroes - for (int i = currentOffset; i < currentBlock.length; i++) - { - currentBlock[i] = 0; - } - - tweak.setFinal(true); - processBlock(output); - } - - } - - /** - * Underlying Threefish tweakable block cipher - */ - private ThreefishEngine threefish; - - /** - * Size of the digest output, in bytes - */ - private int outputSizeBytes; - - /** - * The current chaining/state value - */ - long[] chain; - - /** - * The initial state value - */ - private long[] initialState; - - /** - * The (optional) key parameter - */ - private byte[] key; - - /** - * Parameters to apply prior to the message - */ - private Parameter[] preMessageParameters; - - /** - * Parameters to apply after the message, but prior to output - */ - private Parameter[] postMessageParameters; - - /** - * The current UBI operation - */ - private UBI ubi; - - /** - * Buffer for single byte update method - */ - private final byte[] singleByte = new byte[1]; - - /** - * Constructs a Skein engine. - * - * @param blockSizeBits the internal state size in bits - one of {@link #SKEIN_256}, {@link #SKEIN_512} or - * {@link #SKEIN_1024}. - * @param outputSizeBits the output/digest size to produce in bits, which must be an integral number of - * bytes. - */ - public SkeinEngine(int blockSizeBits, int outputSizeBits) - { - if (outputSizeBits % 8 != 0) - { - throw new IllegalArgumentException("Output size must be a multiple of 8 bits. :" + outputSizeBits); - } - // TODO: Prevent digest sizes > block size? - this.outputSizeBytes = outputSizeBits / 8; - - this.threefish = new ThreefishEngine(blockSizeBits); - this.ubi = new UBI(threefish.getBlockSize()); - } - - /** - * Creates a SkeinEngine as an exact copy of an existing instance. - */ - public SkeinEngine(SkeinEngine engine) - { - this(engine.getBlockSize() * 8, engine.getOutputSize() * 8); - copyIn(engine); - } - - private void copyIn(SkeinEngine engine) - { - this.ubi.reset(engine.ubi); - this.chain = Arrays.clone(engine.chain, this.chain); - this.initialState = Arrays.clone(engine.initialState, this.initialState); - this.key = Arrays.clone(engine.key, this.key); - this.preMessageParameters = clone(engine.preMessageParameters, this.preMessageParameters); - this.postMessageParameters = clone(engine.postMessageParameters, this.postMessageParameters); - } - - private static Parameter[] clone(Parameter[] data, Parameter[] existing) - { - if (data == null) - { - return null; - } - if ((existing == null) || (existing.length != data.length)) - { - existing = new Parameter[data.length]; - } - System.arraycopy(data, 0, existing, 0, existing.length); - return existing; - } - - public Memoable copy() - { - return new SkeinEngine(this); - } - - public void reset(Memoable other) - { - SkeinEngine s = (SkeinEngine)other; - if ((getBlockSize() != s.getBlockSize()) || (outputSizeBytes != s.outputSizeBytes)) - { - throw new IllegalArgumentException("Incompatible parameters in provided SkeinEngine."); - } - copyIn(s); - } - - public int getOutputSize() - { - return outputSizeBytes; - } - - public int getBlockSize() - { - return threefish.getBlockSize(); - } - - /** - * Initialises the Skein engine with the provided parameters. See {@link SkeinParameters} for - * details on the parameterisation of the Skein hash function. - * - * @param params the parameters to apply to this engine, or null to use no parameters. - */ - public void init(SkeinParameters params) - { - this.chain = null; - this.key = null; - this.preMessageParameters = null; - this.postMessageParameters = null; - - if (params != null) - { - byte[] key = params.getKey(); - if (key.length < 16) - { - throw new IllegalArgumentException("Skein key must be at least 128 bits."); - } - initParams(params.getParameters()); - } - createInitialState(); - - // Initialise message block - ubiInit(PARAM_TYPE_MESSAGE); - } - - private void initParams(Hashtable parameters) - { - Enumeration keys = parameters.keys(); - final Vector pre = new Vector(); - final Vector post = new Vector(); - - while (keys.hasMoreElements()) - { - Integer type = (Integer)keys.nextElement(); - byte[] value = (byte[])parameters.get(type); - - if (type.intValue() == PARAM_TYPE_KEY) - { - this.key = value; - } - else if (type.intValue() < PARAM_TYPE_MESSAGE) - { - pre.addElement(new Parameter(type.intValue(), value)); - } - else - { - post.addElement(new Parameter(type.intValue(), value)); - } - } - preMessageParameters = new Parameter[pre.size()]; - pre.copyInto(preMessageParameters); - sort(preMessageParameters); - - postMessageParameters = new Parameter[post.size()]; - post.copyInto(postMessageParameters); - sort(postMessageParameters); - } - - private static void sort(Parameter[] params) - { - if (params == null) - { - return; - } - // Insertion sort, for Java 1.1 compatibility - for (int i = 1; i < params.length; i++) - { - Parameter param = params[i]; - int hole = i; - while (hole > 0 && param.getType() < params[hole - 1].getType()) - { - params[hole] = params[hole - 1]; - hole = hole - 1; - } - params[hole] = param; - } - } - - /** - * Calculate the initial (pre message block) chaining state. - */ - private void createInitialState() - { - long[] precalc = (long[])INITIAL_STATES.get(variantIdentifier(getBlockSize(), getOutputSize())); - if ((key == null) && (precalc != null)) - { - // Precalculated UBI(CFG) - chain = Arrays.clone(precalc); - } - else - { - // Blank initial state - chain = new long[getBlockSize() / 8]; - - // Process key block - if (key != null) - { - ubiComplete(SkeinParameters.PARAM_TYPE_KEY, key); - } - - // Process configuration block - ubiComplete(PARAM_TYPE_CONFIG, new Configuration(outputSizeBytes * 8).getBytes()); - } - - // Process additional pre-message parameters - if (preMessageParameters != null) - { - for (int i = 0; i < preMessageParameters.length; i++) - { - Parameter param = preMessageParameters[i]; - ubiComplete(param.getType(), param.getValue()); - } - } - initialState = Arrays.clone(chain); - } - - /** - * Reset the engine to the initial state (with the key and any pre-message parameters , ready to - * accept message input. - */ - public void reset() - { - System.arraycopy(initialState, 0, chain, 0, chain.length); - - ubiInit(PARAM_TYPE_MESSAGE); - } - - private void ubiComplete(int type, byte[] value) - { - ubiInit(type); - this.ubi.update(value, 0, value.length, chain); - ubiFinal(); - } - - private void ubiInit(int type) - { - this.ubi.reset(type); - } - - private void ubiFinal() - { - ubi.doFinal(chain); - } - - private void checkInitialised() - { - if (this.ubi == null) - { - throw new IllegalArgumentException("Skein engine is not initialised."); - } - } - - public void update(byte in) - { - singleByte[0] = in; - update(singleByte, 0, 1); - } - - public void update(byte[] in, int inOff, int len) - { - checkInitialised(); - ubi.update(in, inOff, len, chain); - } - - public int doFinal(byte[] out, int outOff) - { - checkInitialised(); - if (out.length < (outOff + outputSizeBytes)) - { - throw new DataLengthException("Output buffer is too short to hold output of " + outputSizeBytes + " bytes"); - } - - // Finalise message block - ubiFinal(); - - // Process additional post-message parameters - if (postMessageParameters != null) - { - for (int i = 0; i < postMessageParameters.length; i++) - { - Parameter param = postMessageParameters[i]; - ubiComplete(param.getType(), param.getValue()); - } - } - - // Perform the output transform - final int blockSize = getBlockSize(); - final int blocksRequired = ((outputSizeBytes + blockSize - 1) / blockSize); - for (int i = 0; i < blocksRequired; i++) - { - final int toWrite = Math.min(blockSize, outputSizeBytes - (i * blockSize)); - output(i, out, outOff + (i * blockSize), toWrite); - } - - reset(); - - return outputSizeBytes; - } - - private void output(long outputSequence, byte[] out, int outOff, int outputBytes) - { - byte[] currentBytes = new byte[8]; - ThreefishEngine.wordToBytes(outputSequence, currentBytes, 0); - - // Output is a sequence of UBI invocations all of which use and preserve the pre-output - // state - long[] outputWords = new long[chain.length]; - ubiInit(PARAM_TYPE_OUTPUT); - this.ubi.update(currentBytes, 0, currentBytes.length, outputWords); - ubi.doFinal(outputWords); - - final int wordsRequired = ((outputBytes + 8 - 1) / 8); - for (int i = 0; i < wordsRequired; i++) - { - int toWrite = Math.min(8, outputBytes - (i * 8)); - if (toWrite == 8) - { - ThreefishEngine.wordToBytes(outputWords[i], out, outOff + (i * 8)); - } - else - { - ThreefishEngine.wordToBytes(outputWords[i], currentBytes, 0); - System.arraycopy(currentBytes, 0, out, outOff + (i * 8), toWrite); - } - } - } - -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/encodings/PKCS1Encoding.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/encodings/PKCS1Encoding.java deleted file mode 100644 index 7af31f36e..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/encodings/PKCS1Encoding.java +++ /dev/null @@ -1,410 +0,0 @@ -package org.spongycastle.crypto.encodings; - -import java.security.SecureRandom; - -import org.spongycastle.crypto.AsymmetricBlockCipher; -import org.spongycastle.crypto.CipherParameters; -import org.spongycastle.crypto.InvalidCipherTextException; -import org.spongycastle.crypto.params.AsymmetricKeyParameter; -import org.spongycastle.crypto.params.ParametersWithRandom; - -/** - * this does your basic PKCS 1 v1.5 padding - whether or not you should be using this - * depends on your application - see PKCS1 Version 2 for details. - */ -public class PKCS1Encoding - implements AsymmetricBlockCipher -{ - /** - * some providers fail to include the leading zero in PKCS1 encoded blocks. If you need to - * work with one of these set the system property org.spongycastle.pkcs1.strict to false. - *

- * The system property is checked during construction of the encoding object, it is set to - * true by default. - *

- */ - public static final String STRICT_LENGTH_ENABLED_PROPERTY = "org.spongycastle.pkcs1.strict"; - - private static final int HEADER_LENGTH = 10; - - private SecureRandom random; - private AsymmetricBlockCipher engine; - private boolean forEncryption; - private boolean forPrivateKey; - private boolean useStrictLength; - private int pLen = -1; - private byte[] fallback = null; - - /** - * Basic constructor. - * @param cipher - */ - public PKCS1Encoding( - AsymmetricBlockCipher cipher) - { - this.engine = cipher; - this.useStrictLength = useStrict(); - } - - /** - * Constructor for decryption with a fixed plaintext length. - * - * @param cipher The cipher to use for cryptographic operation. - * @param pLen Length of the expected plaintext. - */ - public PKCS1Encoding( - AsymmetricBlockCipher cipher, - int pLen) - { - this.engine = cipher; - this.useStrictLength = useStrict(); - this.pLen = pLen; - } - - /** - * Constructor for decryption with a fixed plaintext length and a fallback - * value that is returned, if the padding is incorrect. - * - * @param cipher - * The cipher to use for cryptographic operation. - * @param fallback - * The fallback value, we don't to a arraycopy here. - */ - public PKCS1Encoding( - AsymmetricBlockCipher cipher, - byte[] fallback) - { - this.engine = cipher; - this.useStrictLength = useStrict(); - this.fallback = fallback; - this.pLen = fallback.length; - } - - - - // - // for J2ME compatibility - // - private boolean useStrict() - { - // required if security manager has been installed. - String strict = System.getProperty(STRICT_LENGTH_ENABLED_PROPERTY); - - return strict == null || strict.equals("true"); - } - - public AsymmetricBlockCipher getUnderlyingCipher() - { - return engine; - } - - public void init( - boolean forEncryption, - CipherParameters param) - { - AsymmetricKeyParameter kParam; - - if (param instanceof ParametersWithRandom) - { - ParametersWithRandom rParam = (ParametersWithRandom)param; - - this.random = rParam.getRandom(); - kParam = (AsymmetricKeyParameter)rParam.getParameters(); - } - else - { - this.random = new SecureRandom(); - kParam = (AsymmetricKeyParameter)param; - } - - engine.init(forEncryption, param); - - this.forPrivateKey = kParam.isPrivate(); - this.forEncryption = forEncryption; - } - - public int getInputBlockSize() - { - int baseBlockSize = engine.getInputBlockSize(); - - if (forEncryption) - { - return baseBlockSize - HEADER_LENGTH; - } - else - { - return baseBlockSize; - } - } - - public int getOutputBlockSize() - { - int baseBlockSize = engine.getOutputBlockSize(); - - if (forEncryption) - { - return baseBlockSize; - } - else - { - return baseBlockSize - HEADER_LENGTH; - } - } - - public byte[] processBlock( - byte[] in, - int inOff, - int inLen) - throws InvalidCipherTextException - { - if (forEncryption) - { - return encodeBlock(in, inOff, inLen); - } - else - { - return decodeBlock(in, inOff, inLen); - } - } - - private byte[] encodeBlock( - byte[] in, - int inOff, - int inLen) - throws InvalidCipherTextException - { - if (inLen > getInputBlockSize()) - { - throw new IllegalArgumentException("input data too large"); - } - - byte[] block = new byte[engine.getInputBlockSize()]; - - if (forPrivateKey) - { - block[0] = 0x01; // type code 1 - - for (int i = 1; i != block.length - inLen - 1; i++) - { - block[i] = (byte)0xFF; - } - } - else - { - random.nextBytes(block); // random fill - - block[0] = 0x02; // type code 2 - - // - // a zero byte marks the end of the padding, so all - // the pad bytes must be non-zero. - // - for (int i = 1; i != block.length - inLen - 1; i++) - { - while (block[i] == 0) - { - block[i] = (byte)random.nextInt(); - } - } - } - - block[block.length - inLen - 1] = 0x00; // mark the end of the padding - System.arraycopy(in, inOff, block, block.length - inLen, inLen); - - return engine.processBlock(block, 0, block.length); - } - - /** - * Checks if the argument is a correctly PKCS#1.5 encoded Plaintext - * for encryption. - * - * @param encoded The Plaintext. - * @param pLen Expected length of the plaintext. - * @return Either 0, if the encoding is correct, or -1, if it is incorrect. - */ - private static int checkPkcs1Encoding(byte[] encoded, int pLen) { - int correct = 0; - /* - * Check if the first two bytes are 0 2 - */ - correct |= (encoded[0] ^ 2); - - /* - * Now the padding check, check for no 0 byte in the padding - */ - int plen = encoded.length - ( - pLen /* Lenght of the PMS */ - + 1 /* Final 0-byte before PMS */ - ); - - for (int i = 1; i < plen; i++) { - int tmp = encoded[i]; - tmp |= tmp >> 1; - tmp |= tmp >> 2; - tmp |= tmp >> 4; - correct |= (tmp & 1) - 1; - } - - /* - * Make sure the padding ends with a 0 byte. - */ - correct |= encoded[encoded.length - (pLen +1)]; - - /* - * Return 0 or 1, depending on the result. - */ - correct |= correct >> 1; - correct |= correct >> 2; - correct |= correct >> 4; - return ~((correct & 1) - 1); - } - - - /** - * Decode PKCS#1.5 encoding, and return a random value if the padding is not correct. - * - * @param in The encrypted block. - * @param inOff Offset in the encrypted block. - * @param inLen Length of the encrypted block. - * //@param pLen Length of the desired output. - * @return The plaintext without padding, or a random value if the padding was incorrect. - * - * @throws InvalidCipherTextException - */ - private byte[] decodeBlockOrRandom(byte[] in, int inOff, int inLen) - throws InvalidCipherTextException - { - if (!forPrivateKey) - { - throw new InvalidCipherTextException("sorry, this method is only for decryption, not for signing"); - } - - byte[] block = engine.processBlock(in, inOff, inLen); - byte[] random = null; - if (this.fallback == null) - { - random = new byte[this.pLen]; - this.random.nextBytes(random); - } - else - { - random = fallback; - } - - /* - * TODO: This is a potential dangerous side channel. However, you can - * fix this by changing the RSA engine in a way, that it will always - * return blocks of the same length and prepend them with 0 bytes if - * needed. - */ - if (block.length < getOutputBlockSize()) - { - throw new InvalidCipherTextException("block truncated"); - } - - /* - * TODO: Potential side channel. Fix it by making the engine always - * return blocks of the correct length. - */ - if (useStrictLength && block.length != engine.getOutputBlockSize()) - { - throw new InvalidCipherTextException("block incorrect size"); - } - - /* - * Check the padding. - */ - int correct = PKCS1Encoding.checkPkcs1Encoding(block, this.pLen); - - /* - * Now, to a constant time constant memory copy of the decrypted value - * or the random value, depending on the validity of the padding. - */ - byte[] result = new byte[this.pLen]; - for (int i = 0; i < this.pLen; i++) - { - result[i] = (byte)((block[i + (block.length - pLen)] & (~correct)) | (random[i] & correct)); - } - - return result; - } - - /** - * @exception InvalidCipherTextException if the decrypted block is not in PKCS1 format. - */ - private byte[] decodeBlock( - byte[] in, - int inOff, - int inLen) - throws InvalidCipherTextException - { - /* - * If the length of the expected plaintext is known, we use a constant-time decryption. - * If the decryption fails, we return a random value. - */ - if (this.pLen != -1) { - return this.decodeBlockOrRandom(in, inOff, inLen); - } - - byte[] block = engine.processBlock(in, inOff, inLen); - - if (block.length < getOutputBlockSize()) - { - throw new InvalidCipherTextException("block truncated"); - } - - byte type = block[0]; - - if (forPrivateKey) - { - if (type != 2) - { - throw new InvalidCipherTextException("unknown block type"); - } - } - else - { - if (type != 1) - { - throw new InvalidCipherTextException("unknown block type"); - } - } - - if (useStrictLength && block.length != engine.getOutputBlockSize()) - { - throw new InvalidCipherTextException("block incorrect size"); - } - - // - // find and extract the message block. - // - int start; - - for (start = 1; start != block.length; start++) - { - byte pad = block[start]; - - if (pad == 0) - { - break; - } - if (type == 1 && pad != (byte)0xff) - { - throw new InvalidCipherTextException("block padding incorrect"); - } - } - - start++; // data should start at the next byte - - if (start > block.length || start < HEADER_LENGTH) - { - throw new InvalidCipherTextException("no data in block"); - } - - byte[] result = new byte[block.length - start]; - - System.arraycopy(block, start, result, 0, result.length); - - return result; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/engines/NullEngine.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/engines/NullEngine.java deleted file mode 100644 index 219272722..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/engines/NullEngine.java +++ /dev/null @@ -1,96 +0,0 @@ -package org.spongycastle.crypto.engines; - -import org.spongycastle.crypto.BlockCipher; -import org.spongycastle.crypto.CipherParameters; -import org.spongycastle.crypto.DataLengthException; -import org.spongycastle.crypto.OutputLengthException; - -/** - * The no-op engine that just copies bytes through, irrespective of whether encrypting and decrypting. - * Provided for the sake of completeness. - */ -public class NullEngine implements BlockCipher -{ - private boolean initialised; - protected static final int DEFAULT_BLOCK_SIZE = 1; - private int blockSize; - - /** - * Constructs a null engine with a block size of 1 byte. - */ - public NullEngine() - { - this(DEFAULT_BLOCK_SIZE); - } - - /** - * Constructs a null engine with a specific block size. - * - * @param blockSize the block size in bytes. - */ - public NullEngine(int blockSize) - { - this.blockSize = blockSize; - } - - /* (non-Javadoc) - * @see org.spongycastle.crypto.BlockCipher#init(boolean, org.spongycastle.crypto.CipherParameters) - */ - public void init(boolean forEncryption, CipherParameters params) throws IllegalArgumentException - { - // we don't mind any parameters that may come in - this.initialised = true; - } - - /* (non-Javadoc) - * @see org.spongycastle.crypto.BlockCipher#getAlgorithmName() - */ - public String getAlgorithmName() - { - return "Null"; - } - - /* (non-Javadoc) - * @see org.spongycastle.crypto.BlockCipher#getBlockSize() - */ - public int getBlockSize() - { - return blockSize; - } - - /* (non-Javadoc) - * @see org.spongycastle.crypto.BlockCipher#processBlock(byte[], int, byte[], int) - */ - public int processBlock(byte[] in, int inOff, byte[] out, int outOff) - throws DataLengthException, IllegalStateException - { - if (!initialised) - { - throw new IllegalStateException("Null engine not initialised"); - } - if ((inOff + blockSize) > in.length) - { - throw new DataLengthException("input buffer too short"); - } - - if ((outOff + blockSize) > out.length) - { - throw new OutputLengthException("output buffer too short"); - } - - for (int i = 0; i < blockSize; ++i) - { - out[outOff + i] = in[inOff + i]; - } - - return blockSize; - } - - /* (non-Javadoc) - * @see org.spongycastle.crypto.BlockCipher#reset() - */ - public void reset() - { - // nothing needs to be done - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/params/DSAParameterGenerationParameters.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/params/DSAParameterGenerationParameters.java deleted file mode 100644 index 2b57f23c0..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/params/DSAParameterGenerationParameters.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.spongycastle.crypto.params; - -import java.security.SecureRandom; - -public class DSAParameterGenerationParameters -{ - public static final int DIGITAL_SIGNATURE_USAGE = 1; - public static final int KEY_ESTABLISHMENT_USAGE = 2; - - private int l; - private int n; - private int usageIndex; - private int certainty; - private SecureRandom random; - - /** - * Construct without a usage index, this will do a random construction of G. - * - * @param L desired length of prime P in bits (the effective key size). - * @param N desired length of prime Q in bits. - * @param certainty certainty level for prime number generation. - * @param random the source of randomness to use. - */ - public DSAParameterGenerationParameters( - int L, - int N, - int certainty, - SecureRandom random) - { - this(L, N, certainty, random, -1); - } - - /** - * Construct for a specific usage index - this has the effect of using verifiable canonical generation of G. - * - * @param L desired length of prime P in bits (the effective key size). - * @param N desired length of prime Q in bits. - * @param certainty certainty level for prime number generation. - * @param random the source of randomness to use. - * @param usageIndex a valid usage index. - */ - public DSAParameterGenerationParameters( - int L, - int N, - int certainty, - SecureRandom random, - int usageIndex) - { - this.l = L; - this.n = N; - this.certainty = certainty; - this.usageIndex = usageIndex; - this.random = random; - } - - public int getL() - { - return l; - } - - public int getN() - { - return n; - } - - public int getCertainty() - { - return certainty; - } - - public SecureRandom getRandom() - { - return random; - } - - public int getUsageIndex() - { - return usageIndex; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/params/HKDFParameters.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/params/HKDFParameters.java deleted file mode 100644 index 4b125a7c1..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/params/HKDFParameters.java +++ /dev/null @@ -1,123 +0,0 @@ -package org.spongycastle.crypto.params; - -import org.spongycastle.crypto.DerivationParameters; -import org.spongycastle.util.Arrays; - -/** - * Parameter class for the HKDFBytesGenerator class. - */ -public class HKDFParameters - implements DerivationParameters -{ - private byte[] ikm; - private boolean skipExpand; - private byte[] salt; - private byte[] info; - - private HKDFParameters(final byte[] ikm, final boolean skip, - final byte[] salt, final byte[] info) - { - if (ikm == null) - { - throw new IllegalArgumentException( - "IKM (input keying material) should not be null"); - } - - this.ikm = Arrays.clone(ikm); - - this.skipExpand = skip; - - if (salt == null || salt.length == 0) - { - this.salt = null; - } - else - { - this.salt = Arrays.clone(salt); - } - - if (info == null) - { - this.info = new byte[0]; - } - else - { - this.info = Arrays.clone(info); - } - } - - /** - * Generates parameters for HKDF, specifying both the optional salt and - * optional info. Step 1: Extract won't be skipped. - * - * @param ikm the input keying material or seed - * @param salt the salt to use, may be null for a salt for hashLen zeros - * @param info the info to use, may be null for an info field of zero bytes - */ - public HKDFParameters(final byte[] ikm, final byte[] salt, final byte[] info) - { - this(ikm, false, salt, info); - } - - /** - * Factory method that makes the HKDF skip the extract part of the key - * derivation function. - * - * @param ikm the input keying material or seed, directly used for step 2: - * Expand - * @param info the info to use, may be null for an info field of zero bytes - * @return HKDFParameters that makes the implementation skip step 1 - */ - public static HKDFParameters skipExtractParameters(final byte[] ikm, - final byte[] info) - { - - return new HKDFParameters(ikm, true, null, info); - } - - public static HKDFParameters defaultParameters(final byte[] ikm) - { - return new HKDFParameters(ikm, false, null, null); - } - - /** - * Returns the input keying material or seed. - * - * @return the keying material - */ - public byte[] getIKM() - { - return Arrays.clone(ikm); - } - - /** - * Returns if step 1: extract has to be skipped or not - * - * @return true for skipping, false for no skipping of step 1 - */ - public boolean skipExtract() - { - return skipExpand; - } - - /** - * Returns the salt, or null if the salt should be generated as a byte array - * of HashLen zeros. - * - * @return the salt, or null - */ - public byte[] getSalt() - { - return Arrays.clone(salt); - } - - /** - * Returns the info field, which may be empty (null is converted to empty). - * - * @return the info field, never null - */ - public byte[] getInfo() - { - return Arrays.clone(info); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/prng/BasicEntropySourceProvider.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/prng/BasicEntropySourceProvider.java deleted file mode 100644 index 31c85036d..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/prng/BasicEntropySourceProvider.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.spongycastle.crypto.prng; - -import java.security.SecureRandom; - -/** - * An EntropySourceProvider where entropy generation is based on a SecureRandom output using SecureRandom.generateSeed(). - */ -public class BasicEntropySourceProvider - implements EntropySourceProvider -{ - private SecureRandom _sr; - private boolean _predictionResistant; - - /** - * Create a entropy source provider based on the passed in SecureRandom. - * - * @param random 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 random, boolean isPredictionResistant) - { - _sr = random; - _predictionResistant = 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 EntropySource get(final int bitsRequired) - { - return new EntropySource() - { - public boolean isPredictionResistant() - { - return _predictionResistant; - } - - public byte[] getEntropy() - { - byte[] rv = new byte[(bitsRequired + 7) / 8]; - - _sr.nextBytes(rv); - - return rv; - } - - public int entropySize() - { - return bitsRequired; - } - }; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/prng/SP800SecureRandomBuilder.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/prng/SP800SecureRandomBuilder.java deleted file mode 100644 index e682f6870..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/prng/SP800SecureRandomBuilder.java +++ /dev/null @@ -1,289 +0,0 @@ -package org.spongycastle.crypto.prng; - -import java.security.SecureRandom; - -import org.spongycastle.crypto.BlockCipher; -import org.spongycastle.crypto.Digest; -import org.spongycastle.crypto.Mac; -import org.spongycastle.crypto.prng.drbg.CTRSP800DRBG; -import org.spongycastle.crypto.prng.drbg.DualECPoints; -import org.spongycastle.crypto.prng.drbg.DualECSP800DRBG; -import org.spongycastle.crypto.prng.drbg.HMacSP800DRBG; -import org.spongycastle.crypto.prng.drbg.HashSP800DRBG; -import org.spongycastle.crypto.prng.drbg.SP80090DRBG; - -/** - * Builder class for making SecureRandom objects based on SP 800-90A Deterministic Random Bit Generators (DRBG). - */ -public class SP800SecureRandomBuilder -{ - private SecureRandom random; - private EntropySourceProvider entropySourceProvider; - - private byte[] personalizationString; - private int securityStrength = 256; - private int entropyBitsRequired = 256; - - /** - * Basic constructor, creates a builder using an EntropySourceProvider based on the default SecureRandom with - * predictionResistant set to false. - *

- * 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. - *

- */ - 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. - *

- * 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. - *

- * @param entropySource - * @param predictionResistant - */ - public SP800SecureRandomBuilder(SecureRandom entropySource, boolean predictionResistant) - { - this.random = entropySource; - this.entropySourceProvider = new BasicEntropySourceProvider(random, predictionResistant); - } - - /** - * Create a builder which makes creates the SecureRandom objects from a specified entropy source provider. - *

- * Note: If this constructor is used any calls to setSeed() in the resulting SecureRandom will be ignored. - *

- * @param entropySourceProvider a provider of EntropySource objects. - */ - public SP800SecureRandomBuilder(EntropySourceProvider entropySourceProvider) - { - this.random = null; - this.entropySourceProvider = 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.personalizationString = 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.securityStrength = 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.entropyBitsRequired = 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(Digest digest, byte[] nonce, boolean predictionResistant) - { - return new SP800SecureRandom(random, entropySourceProvider.get(entropyBitsRequired), new HashDRBGProvider(digest, nonce, personalizationString, securityStrength), 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(BlockCipher cipher, int keySizeInBits, byte[] nonce, boolean predictionResistant) - { - return new SP800SecureRandom(random, entropySourceProvider.get(entropyBitsRequired), new CTRDRBGProvider(cipher, keySizeInBits, nonce, personalizationString, securityStrength), 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(Mac hMac, byte[] nonce, boolean predictionResistant) - { - return new SP800SecureRandom(random, entropySourceProvider.get(entropyBitsRequired), new HMacDRBGProvider(hMac, nonce, personalizationString, securityStrength), predictionResistant); - } - - /** - * Build a SecureRandom based on a SP 800-90A Dual EC 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 Dual EC DRBG. - */ - public SP800SecureRandom buildDualEC(Digest digest, byte[] nonce, boolean predictionResistant) - { - return new SP800SecureRandom(random, entropySourceProvider.get(entropyBitsRequired), new DualECDRBGProvider(digest, nonce, personalizationString, securityStrength), predictionResistant); - } - - /** - * Build a SecureRandom based on a SP 800-90A Dual EC DRBG. - * - * @param pointSet an array of DualECPoints to use for DRB generation. - * @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 Dual EC DRBG. - */ - public SP800SecureRandom buildDualEC(DualECPoints[] pointSet, Digest digest, byte[] nonce, boolean predictionResistant) - { - return new SP800SecureRandom(random, entropySourceProvider.get(entropyBitsRequired), new ConfigurableDualECDRBGProvider(pointSet, digest, nonce, personalizationString, securityStrength), predictionResistant); - } - - private static class HashDRBGProvider - implements DRBGProvider - { - private final Digest digest; - private final byte[] nonce; - private final byte[] personalizationString; - private final int securityStrength; - - public HashDRBGProvider(Digest digest, byte[] nonce, byte[] personalizationString, int securityStrength) - { - this.digest = digest; - this.nonce = nonce; - this.personalizationString = personalizationString; - this.securityStrength = securityStrength; - } - - public SP80090DRBG get(EntropySource entropySource) - { - return new HashSP800DRBG(digest, securityStrength, entropySource, personalizationString, nonce); - } - } - - private static class DualECDRBGProvider - implements DRBGProvider - { - private final Digest digest; - private final byte[] nonce; - private final byte[] personalizationString; - private final int securityStrength; - - public DualECDRBGProvider(Digest digest, byte[] nonce, byte[] personalizationString, int securityStrength) - { - this.digest = digest; - this.nonce = nonce; - this.personalizationString = personalizationString; - this.securityStrength = securityStrength; - } - - public SP80090DRBG get(EntropySource entropySource) - { - return new DualECSP800DRBG(digest, securityStrength, entropySource, personalizationString, nonce); - } - } - - private static class ConfigurableDualECDRBGProvider - implements DRBGProvider - { - private final DualECPoints[] pointSet; - private final Digest digest; - private final byte[] nonce; - private final byte[] personalizationString; - private final int securityStrength; - - public ConfigurableDualECDRBGProvider(DualECPoints[] pointSet, Digest digest, byte[] nonce, byte[] personalizationString, int securityStrength) - { - this.pointSet = new DualECPoints[pointSet.length]; - System.arraycopy(pointSet, 0, this.pointSet, 0, pointSet.length); - this.digest = digest; - this.nonce = nonce; - this.personalizationString = personalizationString; - this.securityStrength = securityStrength; - } - - public SP80090DRBG get(EntropySource entropySource) - { - return new DualECSP800DRBG(pointSet, digest, securityStrength, entropySource, personalizationString, nonce); - } - } - - private static class HMacDRBGProvider - implements DRBGProvider - { - private final Mac hMac; - private final byte[] nonce; - private final byte[] personalizationString; - private final int securityStrength; - - public HMacDRBGProvider(Mac hMac, byte[] nonce, byte[] personalizationString, int securityStrength) - { - this.hMac = hMac; - this.nonce = nonce; - this.personalizationString = personalizationString; - this.securityStrength = securityStrength; - } - - public SP80090DRBG get(EntropySource entropySource) - { - return new HMacSP800DRBG(hMac, securityStrength, entropySource, personalizationString, nonce); - } - } - - private static class CTRDRBGProvider - implements DRBGProvider - { - - private final BlockCipher blockCipher; - private final int keySizeInBits; - private final byte[] nonce; - private final byte[] personalizationString; - private final int securityStrength; - - public CTRDRBGProvider(BlockCipher blockCipher, int keySizeInBits, byte[] nonce, byte[] personalizationString, int securityStrength) - { - this.blockCipher = blockCipher; - this.keySizeInBits = keySizeInBits; - this.nonce = nonce; - this.personalizationString = personalizationString; - this.securityStrength = securityStrength; - } - - public SP80090DRBG get(EntropySource entropySource) - { - return new CTRSP800DRBG(blockCipher, keySizeInBits, securityStrength, entropySource, personalizationString, nonce); - } - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/signers/RSADigestSigner.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/signers/RSADigestSigner.java deleted file mode 100644 index e6a99d890..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/signers/RSADigestSigner.java +++ /dev/null @@ -1,238 +0,0 @@ -package org.spongycastle.crypto.signers; - -import java.io.IOException; -import java.util.Hashtable; - -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.nist.NISTObjectIdentifiers; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.DigestInfo; -import org.spongycastle.asn1.x509.X509ObjectIdentifiers; -import org.spongycastle.crypto.AsymmetricBlockCipher; -import org.spongycastle.crypto.CipherParameters; -import org.spongycastle.crypto.CryptoException; -import org.spongycastle.crypto.DataLengthException; -import org.spongycastle.crypto.Digest; -import org.spongycastle.crypto.Signer; -import org.spongycastle.crypto.encodings.PKCS1Encoding; -import org.spongycastle.crypto.engines.RSABlindedEngine; -import org.spongycastle.crypto.params.AsymmetricKeyParameter; -import org.spongycastle.crypto.params.ParametersWithRandom; -import org.spongycastle.util.Arrays; - -public class RSADigestSigner - implements Signer -{ - private final AsymmetricBlockCipher rsaEngine = new PKCS1Encoding(new RSABlindedEngine()); - private AlgorithmIdentifier algId; - private Digest digest; - private boolean forSigning; - - private static final Hashtable oidMap = new Hashtable(); - - /* - * Load OID table. - */ - static - { - oidMap.put("RIPEMD128", TeleTrusTObjectIdentifiers.ripemd128); - oidMap.put("RIPEMD160", TeleTrusTObjectIdentifiers.ripemd160); - oidMap.put("RIPEMD256", TeleTrusTObjectIdentifiers.ripemd256); - - oidMap.put("SHA-1", X509ObjectIdentifiers.id_SHA1); - oidMap.put("SHA-224", NISTObjectIdentifiers.id_sha224); - oidMap.put("SHA-256", NISTObjectIdentifiers.id_sha256); - oidMap.put("SHA-384", NISTObjectIdentifiers.id_sha384); - oidMap.put("SHA-512", NISTObjectIdentifiers.id_sha512); - - oidMap.put("MD2", PKCSObjectIdentifiers.md2); - oidMap.put("MD4", PKCSObjectIdentifiers.md4); - oidMap.put("MD5", PKCSObjectIdentifiers.md5); - } - - public RSADigestSigner( - Digest digest) - { - this(digest, (ASN1ObjectIdentifier)oidMap.get(digest.getAlgorithmName())); - } - - public RSADigestSigner( - Digest digest, - ASN1ObjectIdentifier digestOid) - { - this.digest = digest; - this.algId = new AlgorithmIdentifier(digestOid, DERNull.INSTANCE); - } - - /** - * @deprecated - */ - public String getAlgorithmName() - { - return digest.getAlgorithmName() + "withRSA"; - } - - /** - * initialise the signer for signing or verification. - * - * @param forSigning - * true if for signing, false otherwise - * @param parameters - * necessary parameters. - */ - public void init( - boolean forSigning, - CipherParameters parameters) - { - this.forSigning = forSigning; - AsymmetricKeyParameter k; - - if (parameters instanceof ParametersWithRandom) - { - k = (AsymmetricKeyParameter)((ParametersWithRandom)parameters).getParameters(); - } - else - { - k = (AsymmetricKeyParameter)parameters; - } - - if (forSigning && !k.isPrivate()) - { - throw new IllegalArgumentException("signing requires private key"); - } - - if (!forSigning && k.isPrivate()) - { - throw new IllegalArgumentException("verification requires public key"); - } - - reset(); - - rsaEngine.init(forSigning, parameters); - } - - /** - * update the internal digest with the byte b - */ - public void update( - byte input) - { - digest.update(input); - } - - /** - * update the internal digest with the byte array in - */ - public void update( - byte[] input, - int inOff, - int length) - { - digest.update(input, inOff, length); - } - - /** - * Generate a signature for the message we've been loaded with using the key - * we were initialised with. - */ - public byte[] generateSignature() - throws CryptoException, DataLengthException - { - if (!forSigning) - { - throw new IllegalStateException("RSADigestSigner not initialised for signature generation."); - } - - byte[] hash = new byte[digest.getDigestSize()]; - digest.doFinal(hash, 0); - - try - { - byte[] data = derEncode(hash); - return rsaEngine.processBlock(data, 0, data.length); - } - catch (IOException e) - { - throw new CryptoException("unable to encode signature: " + e.getMessage(), e); - } - } - - /** - * return true if the internal state represents the signature described in - * the passed in array. - */ - public boolean verifySignature( - byte[] signature) - { - if (forSigning) - { - throw new IllegalStateException("RSADigestSigner not initialised for verification"); - } - - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - byte[] sig; - byte[] expected; - - try - { - sig = rsaEngine.processBlock(signature, 0, signature.length); - expected = derEncode(hash); - } - catch (Exception e) - { - return false; - } - - if (sig.length == expected.length) - { - return Arrays.constantTimeAreEqual(sig, expected); - } - else if (sig.length == expected.length - 2) // NULL left out - { - int sigOffset = sig.length - hash.length - 2; - int expectedOffset = expected.length - hash.length - 2; - - expected[1] -= 2; // adjust lengths - expected[3] -= 2; - - int nonEqual = 0; - - for (int i = 0; i < hash.length; i++) - { - nonEqual |= (sig[sigOffset + i] ^ expected[expectedOffset + i]); - } - - for (int i = 0; i < sigOffset; i++) - { - nonEqual |= (sig[i] ^ expected[i]); // check header less NULL - } - - return nonEqual == 0; - } - else - { - return false; - } - } - - public void reset() - { - digest.reset(); - } - - private byte[] derEncode( - byte[] hash) - throws IOException - { - DigestInfo dInfo = new DigestInfo(algId, hash); - - return dInfo.getEncoded(ASN1Encoding.DER); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/tls/AbstractTlsContext.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/tls/AbstractTlsContext.java deleted file mode 100644 index cd6f7a8c4..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/tls/AbstractTlsContext.java +++ /dev/null @@ -1,135 +0,0 @@ -package org.spongycastle.crypto.tls; - -import java.security.SecureRandom; - -import org.spongycastle.crypto.prng.DigestRandomGenerator; -import org.spongycastle.crypto.prng.RandomGenerator; -import org.spongycastle.util.Times; - -abstract class AbstractTlsContext - implements TlsContext -{ - private static long counter = Times.nanoTime(); - - private synchronized static long nextCounterValue() - { - return ++counter; - } - - private RandomGenerator nonceRandom; - private SecureRandom secureRandom; - private SecurityParameters securityParameters; - - private ProtocolVersion clientVersion = null; - private ProtocolVersion serverVersion = null; - private TlsSession session = null; - private Object userObject = null; - - AbstractTlsContext(SecureRandom secureRandom, SecurityParameters securityParameters) - { - secureRandom.setSeed(nextCounterValue()); - secureRandom.setSeed(Times.nanoTime()); - - this.nonceRandom = new DigestRandomGenerator(TlsUtils.createHash(HashAlgorithm.sha256)); - byte[] nonceSeed = new byte[32]; - secureRandom.nextBytes(nonceSeed); - this.nonceRandom.addSeedMaterial(nonceSeed); - - this.secureRandom = secureRandom; - this.securityParameters = securityParameters; - } - - public RandomGenerator getNonceRandomGenerator() - { - return nonceRandom; - } - - public SecureRandom getSecureRandom() - { - return secureRandom; - } - - public SecurityParameters getSecurityParameters() - { - return securityParameters; - } - - public ProtocolVersion getClientVersion() - { - return clientVersion; - } - - void setClientVersion(ProtocolVersion clientVersion) - { - this.clientVersion = clientVersion; - } - - public ProtocolVersion getServerVersion() - { - return serverVersion; - } - - void setServerVersion(ProtocolVersion serverVersion) - { - this.serverVersion = serverVersion; - } - - public TlsSession getResumableSession() - { - return session; - } - - void setResumableSession(TlsSession session) - { - this.session = session; - } - - public Object getUserObject() - { - return userObject; - } - - public void setUserObject(Object userObject) - { - this.userObject = userObject; - } - - public byte[] exportKeyingMaterial(String asciiLabel, byte[] context_value, int length) - { - if (context_value != null && !TlsUtils.isValidUint16(context_value.length)) - { - throw new IllegalArgumentException("'context_value' must have length less than 2^16 (or be null)"); - } - - SecurityParameters sp = getSecurityParameters(); - byte[] cr = sp.getClientRandom(), sr = sp.getServerRandom(); - - int seedLength = cr.length + sr.length; - if (context_value != null) - { - seedLength += (2 + context_value.length); - } - - byte[] seed = new byte[seedLength]; - int seedPos = 0; - - System.arraycopy(cr, 0, seed, seedPos, cr.length); - seedPos += cr.length; - System.arraycopy(sr, 0, seed, seedPos, sr.length); - seedPos += sr.length; - if (context_value != null) - { - TlsUtils.writeUint16(context_value.length, seed, seedPos); - seedPos += 2; - System.arraycopy(context_value, 0, seed, seedPos, context_value.length); - seedPos += context_value.length; - } - - if (seedPos != seedLength) - { - throw new IllegalStateException("error in calculation of seed for export"); - } - - return TlsUtils.PRF(this, sp.getMasterSecret(), asciiLabel, seed, length); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/tls/DTLSReassembler.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/tls/DTLSReassembler.java deleted file mode 100644 index baf9c92fd..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/tls/DTLSReassembler.java +++ /dev/null @@ -1,136 +0,0 @@ -package org.spongycastle.crypto.tls; - -import java.util.Vector; - -class DTLSReassembler -{ - - private short msg_type; - private byte[] body; - - private Vector missing = new Vector(); - - DTLSReassembler(short msg_type, int length) - { - this.msg_type = msg_type; - this.body = new byte[length]; - this.missing.addElement(new Range(0, length)); - } - - short getType() - { - return msg_type; - } - - byte[] getBodyIfComplete() - { - return missing.isEmpty() ? body : null; - } - - void contributeFragment(short msg_type, int length, byte[] buf, int off, int fragment_offset, - int fragment_length) - { - - int fragment_end = fragment_offset + fragment_length; - - if (this.msg_type != msg_type || this.body.length != length || fragment_end > length) - { - return; - } - - if (fragment_length == 0) - { - // NOTE: Empty messages still require an empty fragment to complete it - if (fragment_offset == 0 && !missing.isEmpty()) - { - Range firstRange = (Range)missing.firstElement(); - if (firstRange.getEnd() == 0) - { - missing.removeElementAt(0); - } - } - return; - } - - for (int i = 0; i < missing.size(); ++i) - { - Range range = (Range)missing.elementAt(i); - if (range.getStart() >= fragment_end) - { - break; - } - if (range.getEnd() > fragment_offset) - { - - int copyStart = Math.max(range.getStart(), fragment_offset); - int copyEnd = Math.min(range.getEnd(), fragment_end); - int copyLength = copyEnd - copyStart; - - System.arraycopy(buf, off + copyStart - fragment_offset, body, copyStart, - copyLength); - - if (copyStart == range.getStart()) - { - if (copyEnd == range.getEnd()) - { - missing.removeElementAt(i--); - } - else - { - range.setStart(copyEnd); - } - } - else - { - if (copyEnd == range.getEnd()) - { - range.setEnd(copyStart); - } - else - { - missing.insertElementAt(new Range(copyEnd, range.getEnd()), ++i); - range.setEnd(copyStart); - } - } - } - } - } - - void reset() - { - this.missing.removeAllElements(); - this.missing.addElement(new Range(0, body.length)); - } - - private static class Range - { - - private int start, end; - - Range(int start, int end) - { - this.start = start; - this.end = end; - } - - public int getStart() - { - return start; - } - - public void setStart(int start) - { - this.start = start; - } - - public int getEnd() - { - return end; - } - - public void setEnd(int end) - { - this.end = end; - } - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/tls/DTLSReliableHandshake.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/tls/DTLSReliableHandshake.java deleted file mode 100644 index 1a9911619..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/tls/DTLSReliableHandshake.java +++ /dev/null @@ -1,457 +0,0 @@ -package org.spongycastle.crypto.tls; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Vector; - -import org.spongycastle.crypto.Digest; -import org.spongycastle.util.Integers; - -class DTLSReliableHandshake -{ - private final static int MAX_RECEIVE_AHEAD = 10; - - private DTLSRecordLayer recordLayer; - - private TlsHandshakeHash handshakeHash; - - private Hashtable currentInboundFlight = new Hashtable(); - private Hashtable previousInboundFlight = null; - private Vector outboundFlight = new Vector(); - private boolean sending = true; - - private int message_seq = 0, next_receive_seq = 0; - - DTLSReliableHandshake(TlsContext context, DTLSRecordLayer transport) - { - this.recordLayer = transport; - this.handshakeHash = new DeferredHash(); - this.handshakeHash.init(context); - } - - void notifyHelloComplete() - { - this.handshakeHash = handshakeHash.notifyPRFDetermined(); - } - - TlsHandshakeHash getHandshakeHash() - { - return handshakeHash; - } - - TlsHandshakeHash prepareToFinish() - { - TlsHandshakeHash result = handshakeHash; - this.handshakeHash = handshakeHash.stopTracking(); - return result; - } - - void sendMessage(short msg_type, byte[] body) - throws IOException - { - TlsUtils.checkUint24(body.length); - - if (!sending) - { - checkInboundFlight(); - sending = true; - outboundFlight.removeAllElements(); - } - - Message message = new Message(message_seq++, msg_type, body); - - outboundFlight.addElement(message); - - writeMessage(message); - updateHandshakeMessagesDigest(message); - } - - byte[] receiveMessageBody(short msg_type) - throws IOException - { - Message message = receiveMessage(); - if (message.getType() != msg_type) - { - throw new TlsFatalAlert(AlertDescription.unexpected_message); - } - - return message.getBody(); - } - - Message receiveMessage() - throws IOException - { - if (sending) - { - sending = false; - prepareInboundFlight(); - } - - // Check if we already have the next message waiting - { - DTLSReassembler next = (DTLSReassembler)currentInboundFlight.get(Integers.valueOf(next_receive_seq)); - if (next != null) - { - byte[] body = next.getBodyIfComplete(); - if (body != null) - { - previousInboundFlight = null; - return updateHandshakeMessagesDigest(new Message(next_receive_seq++, next.getType(), body)); - } - } - } - - byte[] buf = null; - - // TODO Check the conditions under which we should reset this - int readTimeoutMillis = 1000; - - for (; ; ) - { - int receiveLimit = recordLayer.getReceiveLimit(); - if (buf == null || buf.length < receiveLimit) - { - buf = new byte[receiveLimit]; - } - - // TODO Handle records containing multiple handshake messages - - try - { - for (; ; ) - { - int received = recordLayer.receive(buf, 0, receiveLimit, readTimeoutMillis); - if (received < 0) - { - break; - } - if (received < 12) - { - continue; - } - int fragment_length = TlsUtils.readUint24(buf, 9); - if (received != (fragment_length + 12)) - { - continue; - } - int seq = TlsUtils.readUint16(buf, 4); - if (seq > (next_receive_seq + MAX_RECEIVE_AHEAD)) - { - continue; - } - short msg_type = TlsUtils.readUint8(buf, 0); - int length = TlsUtils.readUint24(buf, 1); - int fragment_offset = TlsUtils.readUint24(buf, 6); - if (fragment_offset + fragment_length > length) - { - continue; - } - - if (seq < next_receive_seq) - { - /* - * NOTE: If we receive the previous flight of incoming messages in full - * again, retransmit our last flight - */ - if (previousInboundFlight != null) - { - DTLSReassembler reassembler = (DTLSReassembler)previousInboundFlight.get(Integers - .valueOf(seq)); - if (reassembler != null) - { - - reassembler.contributeFragment(msg_type, length, buf, 12, fragment_offset, - fragment_length); - - if (checkAll(previousInboundFlight)) - { - - resendOutboundFlight(); - - /* - * TODO[DTLS] implementations SHOULD back off handshake packet - * size during the retransmit backoff. - */ - readTimeoutMillis = Math.min(readTimeoutMillis * 2, 60000); - - resetAll(previousInboundFlight); - } - } - } - } - else - { - - DTLSReassembler reassembler = (DTLSReassembler)currentInboundFlight.get(Integers.valueOf(seq)); - if (reassembler == null) - { - reassembler = new DTLSReassembler(msg_type, length); - currentInboundFlight.put(Integers.valueOf(seq), reassembler); - } - - reassembler.contributeFragment(msg_type, length, buf, 12, fragment_offset, fragment_length); - - if (seq == next_receive_seq) - { - byte[] body = reassembler.getBodyIfComplete(); - if (body != null) - { - previousInboundFlight = null; - return updateHandshakeMessagesDigest(new Message(next_receive_seq++, - reassembler.getType(), body)); - } - } - } - } - } - catch (IOException e) - { - // NOTE: Assume this is a timeout for the moment - } - - resendOutboundFlight(); - - /* - * TODO[DTLS] implementations SHOULD back off handshake packet size during the - * retransmit backoff. - */ - readTimeoutMillis = Math.min(readTimeoutMillis * 2, 60000); - } - } - - void finish() - { - DTLSHandshakeRetransmit retransmit = null; - if (!sending) - { - checkInboundFlight(); - } - else if (currentInboundFlight != null) - { - /* - * RFC 6347 4.2.4. In addition, for at least twice the default MSL defined for [TCP], - * when in the FINISHED state, the node that transmits the last flight (the server in an - * ordinary handshake or the client in a resumed handshake) MUST respond to a retransmit - * of the peer's last flight with a retransmit of the last flight. - */ - retransmit = new DTLSHandshakeRetransmit() - { - public void receivedHandshakeRecord(int epoch, byte[] buf, int off, int len) - throws IOException - { - /* - * TODO Need to handle the case where the previous inbound flight contains - * messages from two epochs. - */ - if (len < 12) - { - return; - } - int fragment_length = TlsUtils.readUint24(buf, off + 9); - if (len != (fragment_length + 12)) - { - return; - } - int seq = TlsUtils.readUint16(buf, off + 4); - if (seq >= next_receive_seq) - { - return; - } - - short msg_type = TlsUtils.readUint8(buf, off); - - // TODO This is a hack that only works until we try to support renegotiation - int expectedEpoch = msg_type == HandshakeType.finished ? 1 : 0; - if (epoch != expectedEpoch) - { - return; - } - - int length = TlsUtils.readUint24(buf, off + 1); - int fragment_offset = TlsUtils.readUint24(buf, off + 6); - if (fragment_offset + fragment_length > length) - { - return; - } - - DTLSReassembler reassembler = (DTLSReassembler)currentInboundFlight.get(Integers.valueOf(seq)); - if (reassembler != null) - { - reassembler.contributeFragment(msg_type, length, buf, off + 12, fragment_offset, - fragment_length); - if (checkAll(currentInboundFlight)) - { - resendOutboundFlight(); - resetAll(currentInboundFlight); - } - } - } - }; - } - - recordLayer.handshakeSuccessful(retransmit); - } - - void resetHandshakeMessagesDigest() - { - handshakeHash.reset(); - } - - /** - * Check that there are no "extra" messages left in the current inbound flight - */ - private void checkInboundFlight() - { - Enumeration e = currentInboundFlight.keys(); - while (e.hasMoreElements()) - { - Integer key = (Integer)e.nextElement(); - if (key.intValue() >= next_receive_seq) - { - // TODO Should this be considered an error? - } - } - } - - private void prepareInboundFlight() - { - resetAll(currentInboundFlight); - previousInboundFlight = currentInboundFlight; - currentInboundFlight = new Hashtable(); - } - - private void resendOutboundFlight() - throws IOException - { - recordLayer.resetWriteEpoch(); - for (int i = 0; i < outboundFlight.size(); ++i) - { - writeMessage((Message)outboundFlight.elementAt(i)); - } - } - - private Message updateHandshakeMessagesDigest(Message message) - throws IOException - { - if (message.getType() != HandshakeType.hello_request) - { - byte[] body = message.getBody(); - byte[] buf = new byte[12]; - TlsUtils.writeUint8(message.getType(), buf, 0); - TlsUtils.writeUint24(body.length, buf, 1); - TlsUtils.writeUint16(message.getSeq(), buf, 4); - TlsUtils.writeUint24(0, buf, 6); - TlsUtils.writeUint24(body.length, buf, 9); - handshakeHash.update(buf, 0, buf.length); - handshakeHash.update(body, 0, body.length); - } - return message; - } - - private void writeMessage(Message message) - throws IOException - { - int sendLimit = recordLayer.getSendLimit(); - int fragmentLimit = sendLimit - 12; - - // TODO Support a higher minimum fragment size? - if (fragmentLimit < 1) - { - // TODO Should we be throwing an exception here? - throw new TlsFatalAlert(AlertDescription.internal_error); - } - - int length = message.getBody().length; - - // NOTE: Must still send a fragment if body is empty - int fragment_offset = 0; - do - { - int fragment_length = Math.min(length - fragment_offset, fragmentLimit); - writeHandshakeFragment(message, fragment_offset, fragment_length); - fragment_offset += fragment_length; - } - while (fragment_offset < length); - } - - private void writeHandshakeFragment(Message message, int fragment_offset, int fragment_length) - throws IOException - { - RecordLayerBuffer fragment = new RecordLayerBuffer(12 + fragment_length); - TlsUtils.writeUint8(message.getType(), fragment); - TlsUtils.writeUint24(message.getBody().length, fragment); - TlsUtils.writeUint16(message.getSeq(), fragment); - TlsUtils.writeUint24(fragment_offset, fragment); - TlsUtils.writeUint24(fragment_length, fragment); - fragment.write(message.getBody(), fragment_offset, fragment_length); - - fragment.sendToRecordLayer(recordLayer); - } - - private static boolean checkAll(Hashtable inboundFlight) - { - Enumeration e = inboundFlight.elements(); - while (e.hasMoreElements()) - { - if (((DTLSReassembler)e.nextElement()).getBodyIfComplete() == null) - { - return false; - } - } - return true; - } - - private static void resetAll(Hashtable inboundFlight) - { - Enumeration e = inboundFlight.elements(); - while (e.hasMoreElements()) - { - ((DTLSReassembler)e.nextElement()).reset(); - } - } - - static class Message - { - private final int message_seq; - private final short msg_type; - private final byte[] body; - - private Message(int message_seq, short msg_type, byte[] body) - { - this.message_seq = message_seq; - this.msg_type = msg_type; - this.body = body; - } - - public int getSeq() - { - return message_seq; - } - - public short getType() - { - return msg_type; - } - - public byte[] getBody() - { - return body; - } - } - - static class RecordLayerBuffer extends ByteArrayOutputStream - { - RecordLayerBuffer(int size) - { - super(size); - } - - void sendToRecordLayer(DTLSRecordLayer recordLayer) throws IOException - { - recordLayer.send(buf, 0, count); - buf = null; - } - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/tls/UDPTransport.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/tls/UDPTransport.java deleted file mode 100644 index 913c1e552..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/crypto/tls/UDPTransport.java +++ /dev/null @@ -1,106 +0,0 @@ -package org.spongycastle.crypto.tls; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; - -public class UDPTransport - implements DatagramTransport -{ - protected final static int MIN_IP_OVERHEAD = 20; - protected final static int MAX_IP_OVERHEAD = MIN_IP_OVERHEAD + 64; - protected final static int UDP_OVERHEAD = 8; - - protected final DatagramSocket socket; - protected final int receiveLimit, sendLimit; - - public UDPTransport(DatagramSocket socket, int mtu) - throws IOException - { - // - // In 1.3 and earlier sockets were bound and connected during creation - // - //if (!socket.isBound() || !socket.isConnected()) - //{ - // throw new IllegalArgumentException("'socket' must be bound and connected"); - //} - - this.socket = socket; - - // NOTE: As of JDK 1.6, can use NetworkInterface.getMTU - - this.receiveLimit = mtu - MIN_IP_OVERHEAD - UDP_OVERHEAD; - this.sendLimit = mtu - MAX_IP_OVERHEAD - UDP_OVERHEAD; - } - - public int getReceiveLimit() - { - return receiveLimit; - } - - public int getSendLimit() - { - // TODO[DTLS] Implement Path-MTU discovery? - return sendLimit; - } - - public int receive(byte[] buf, int off, int len, int waitMillis) - throws IOException - { - socket.setSoTimeout(waitMillis); - - if (off == 0) - { - DatagramPacket packet = new DatagramPacket(buf, len); - socket.receive(packet); - - return packet.getLength(); - } - else - { - byte[] rv = new byte[len]; - - DatagramPacket packet = new DatagramPacket(rv, len); - socket.receive(packet); - - System.arraycopy(rv, 0, buf, off, packet.getLength()); - - return packet.getLength(); - } - } - - public void send(byte[] buf, int off, int len) - throws IOException - { - if (len > getSendLimit()) - { - /* - * RFC 4347 4.1.1. "If the application attempts to send a record larger than the MTU, - * the DTLS implementation SHOULD generate an error, thus avoiding sending a packet - * which will be fragmented." - */ - throw new TlsFatalAlert(AlertDescription.internal_error); - } - - if (off == 0) - { - DatagramPacket packet = new DatagramPacket(buf, len); - socket.send(packet); - } - else - { - byte[] data = new byte[len]; - - System.arraycopy(buf, off, data, 0, len); - - DatagramPacket packet = new DatagramPacket(data, len); - socket.send(packet); - } - } - - public void close() - throws IOException - { - socket.close(); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/i18n/LocalizedMessage.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/i18n/LocalizedMessage.java deleted file mode 100644 index 1eab110cb..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/i18n/LocalizedMessage.java +++ /dev/null @@ -1,464 +0,0 @@ -package org.spongycastle.i18n; - -import org.spongycastle.i18n.filter.Filter; -import org.spongycastle.i18n.filter.TrustedInput; -import org.spongycastle.i18n.filter.UntrustedInput; -import org.spongycastle.i18n.filter.UntrustedUrlInput; - -import java.io.UnsupportedEncodingException; -import java.text.DateFormat; -import java.text.Format; -import java.text.MessageFormat; -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.ResourceBundle; -import java.util.TimeZone; - -public class LocalizedMessage -{ - protected static final int NO_FILTER = 0; - protected static final int FILTER = 1; - protected static final int FILTER_URL = 2; - - protected String id; - protected String resource; - - // ISO-8859-1 is the default encoding - public static final String DEFAULT_ENCODING = "ISO-8859-1"; - protected String encoding = DEFAULT_ENCODING; - - protected FilteredArguments arguments; - protected FilteredArguments extraArgs = null; - - protected Filter filter = null; - - protected ClassLoader loader = null; - - /** - * Constructs a new LocalizedMessage using resource as the base name for the - * RessourceBundle and id as the message bundle id the resource file. - * @param resource base name of the resource file - * @param id the id of the corresponding bundle in the resource file - * @throws NullPointerException if resource or id is null - */ - public LocalizedMessage(String resource,String id) throws NullPointerException - { - if (resource == null || id == null) - { - throw new NullPointerException(); - } - this.id = id; - this.resource = resource; - arguments = new FilteredArguments(); - } - - /** - * Constructs a new LocalizedMessage using resource as the base name for the - * RessourceBundle and id as the message bundle id the resource file. - * @param resource base name of the resource file - * @param id the id of the corresponding bundle in the resource file - * @param encoding the encoding of the resource file - * @throws NullPointerException if resource or id is null - * @throws UnsupportedEncodingException if the encoding is not supported - */ - public LocalizedMessage(String resource,String id, String encoding) throws NullPointerException, UnsupportedEncodingException - { - if (resource == null || id == null) - { - throw new NullPointerException(); - } - this.id = id; - this.resource = resource; - arguments = new FilteredArguments(); - this.encoding = encoding; - } - - /** - * Constructs a new LocalizedMessage using resource as the base name for the - * RessourceBundle and id as the message bundle id the resource file. - * @param resource base name of the resource file - * @param id the id of the corresponding bundle in the resource file - * @param arguments an array containing the arguments for the message - * @throws NullPointerException if resource or id is null - */ - public LocalizedMessage(String resource, String id, Object[] arguments) throws NullPointerException - { - if (resource == null || id == null || arguments == null) - { - throw new NullPointerException(); - } - this.id = id; - this.resource = resource; - this.arguments = new FilteredArguments(arguments); - } - - /** - * Constructs a new LocalizedMessage using resource as the base name for the - * RessourceBundle and id as the message bundle id the resource file. - * @param resource base name of the resource file - * @param id the id of the corresponding bundle in the resource file - * @param encoding the encoding of the resource file - * @param arguments an array containing the arguments for the message - * @throws NullPointerException if resource or id is null - * @throws UnsupportedEncodingException if the encoding is not supported - */ - public LocalizedMessage(String resource, String id, String encoding, Object[] arguments) throws NullPointerException, UnsupportedEncodingException - { - if (resource == null || id == null || arguments == null) - { - throw new NullPointerException(); - } - this.id = id; - this.resource = resource; - this.arguments = new FilteredArguments(arguments); - this.encoding = encoding; - } - - /** - * Reads the entry id + "." + key from the resource file and returns a - * formated message for the given Locale and TimeZone. - * @param key second part of the entry id - * @param loc the used {@link Locale} - * @param timezone the used {@link TimeZone} - * @return a Strng containing the localized message - * @throws MissingEntryException if the resource file is not available or the entry does not exist. - */ - public String getEntry(String key,Locale loc, TimeZone timezone) throws MissingEntryException - { - String entry = id; - if (key != null) - { - entry += "." + key; - } - - try - { - ResourceBundle bundle; - if (loader == null) - { - bundle = ResourceBundle.getBundle(resource,loc); - } - else - { - bundle = ResourceBundle.getBundle(resource, loc); - } - String result = bundle.getString(entry); - if (!encoding.equals(DEFAULT_ENCODING)) - { - result = new String(result.getBytes(DEFAULT_ENCODING), encoding); - } - if (!arguments.isEmpty()) - { - result = formatWithTimeZone(result,arguments.getFilteredArgs(loc),loc,timezone); - } - result = addExtraArgs(result, loc); - return result; - } - catch (MissingResourceException mre) - { - throw new MissingEntryException("Can't find entry " + entry + " in resource file " + resource + ".", - resource, - entry, - loc, - loader != null ? loader : this.getClassLoader()); - } - catch (UnsupportedEncodingException use) - { - // should never occur - cause we already test this in the constructor - throw new RuntimeException(use.toString()); - } - } - - protected String formatWithTimeZone( - String template, - Object[] arguments, - Locale locale, - TimeZone timezone) - { - MessageFormat mf = new MessageFormat(" "); - mf.setLocale(locale); - mf.applyPattern(template); - if (!timezone.equals(TimeZone.getDefault())) - { - Format[] formats = mf.getFormats(); - for (int i = 0; i < formats.length; i++) - { - if (formats[i] instanceof DateFormat) - { - DateFormat temp = (DateFormat) formats[i]; - temp.setTimeZone(timezone); - mf.setFormat(i,temp); - } - } - } - return mf.format(arguments); - } - - protected String addExtraArgs(String msg, Locale locale) - { - if (extraArgs != null) - { - StringBuffer sb = new StringBuffer(msg); - Object[] filteredArgs = extraArgs.getFilteredArgs(locale); - for (int i = 0; i < filteredArgs.length; i++) - { - sb.append(filteredArgs[i]); - } - msg = sb.toString(); - } - return msg; - } - - /** - * Sets the {@link Filter} that is used to filter the arguments of this message - * @param filter the {@link Filter} to use. null to disable filtering. - */ - public void setFilter(Filter filter) - { - arguments.setFilter(filter); - if (extraArgs != null) - { - extraArgs.setFilter(filter); - } - this.filter = filter; - } - - /** - * Returns the current filter. - * @return the current filter - */ - public Filter getFilter() - { - return filter; - } - - /** - * Set the {@link ClassLoader} which loads the resource files. If it is set to null - * then the default {@link ClassLoader} is used. - * @param loader the {@link ClassLoader} which loads the resource files - */ - public void setClassLoader(ClassLoader loader) - { - this.loader = loader; - } - - /** - * Returns the {@link ClassLoader} which loads the resource files or null - * if the default ClassLoader is used. - * @return the {@link ClassLoader} which loads the resource files - */ - public ClassLoader getClassLoader() - { - return loader; - } - - /** - * Returns the id of the message in the resource bundle. - * @return the id of the message - */ - public String getId() - { - return id; - } - - /** - * Returns the name of the resource bundle for this message - * @return name of the resource file - */ - public String getResource() - { - return resource; - } - - /** - * Returns an Object[] containing the message arguments. - * @return the message arguments - */ - public Object[] getArguments() - { - return arguments.getArguments(); - } - - /** - * - * @param extraArg - */ - public void setExtraArgument(Object extraArg) - { - setExtraArguments(new Object[] {extraArg}); - } - - /** - * - * @param extraArgs - */ - public void setExtraArguments(Object[] extraArgs) - { - if (extraArgs != null) - { - this.extraArgs = new FilteredArguments(extraArgs); - this.extraArgs.setFilter(filter); - } - else - { - this.extraArgs = null; - } - } - - /** - * - * @return - */ - public Object[] getExtraArgs() - { - return (extraArgs == null) ? null : extraArgs.getArguments(); - } - - protected class FilteredArguments - { - - protected Filter filter = null; - - protected boolean[] isLocaleSpecific; - protected int[] argFilterType; - protected Object[] arguments; - protected Object[] unpackedArgs; - protected Object[] filteredArgs; - - FilteredArguments() - { - this(new Object[0]); - } - - FilteredArguments(Object[] args) - { - this.arguments = args; - this.unpackedArgs = new Object[args.length]; - this.filteredArgs = new Object[args.length]; - this.isLocaleSpecific = new boolean[args.length]; - this.argFilterType = new int[args.length]; - for (int i = 0; i < args.length; i++) - { - if (args[i] instanceof TrustedInput) - { - this.unpackedArgs[i] = ((TrustedInput) args[i]).getInput(); - argFilterType[i] = NO_FILTER; - } - else if (args[i] instanceof UntrustedInput) - { - this.unpackedArgs[i] = ((UntrustedInput) args[i]).getInput(); - if (args[i] instanceof UntrustedUrlInput) - { - argFilterType[i] = FILTER_URL; - } - else - { - argFilterType[i] = FILTER; - } - } - else - { - this.unpackedArgs[i] = args[i]; - argFilterType[i] = FILTER; - } - - // locale specific - this.isLocaleSpecific[i] = (this.unpackedArgs[i] instanceof LocaleString); - } - } - - public boolean isEmpty() - { - return unpackedArgs.length == 0; - } - - public Object[] getArguments() - { - return arguments; - } - - public Object[] getFilteredArgs(Locale locale) - { - Object[] result = new Object[unpackedArgs.length]; - for (int i = 0; i < unpackedArgs.length; i++) - { - Object arg; - if (filteredArgs[i] != null) - { - arg = filteredArgs[i]; - } - else - { - arg = unpackedArgs[i]; - if (isLocaleSpecific[i]) - { - // get locale - arg = ((LocaleString) arg).getLocaleString(locale); - arg = filter(argFilterType[i], arg); - } - else - { - arg = filter(argFilterType[i], arg); - filteredArgs[i] = arg; - } - } - result[i] = arg; - } - return result; - } - - private Object filter(int type, Object obj) - { - if (filter != null) - { - Object o = (null == obj) ? "null" : obj; - switch (type) - { - case NO_FILTER: - return o; - case FILTER: - return filter.doFilter(o.toString()); - case FILTER_URL: - return filter.doFilterUrl(o.toString()); - default: - return null; - } - } - else - { - return obj; - } - } - - public Filter getFilter() - { - return filter; - } - - public void setFilter(Filter filter) - { - if (filter != this.filter) - { - for (int i = 0; i < unpackedArgs.length; i++) - { - filteredArgs[i] = null; - } - } - this.filter = filter; - } - - } - - public String toString() - { - StringBuffer sb = new StringBuffer(); - sb.append("Resource: \"").append(resource); - sb.append("\" Id: \"").append(id).append("\""); - sb.append(" Arguments: ").append(arguments.getArguments().length).append(" normal, ") - .append(extraArgs.getArguments().length).append(" extra"); - sb.append(" Encoding: ").append(encoding); - sb.append(" ClassLoader: ").append(loader); - return sb.toString(); - } - -} diff --git a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/i18n/MissingEntryException.java b/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/i18n/MissingEntryException.java deleted file mode 100644 index d876a91af..000000000 --- a/extern/spongycastle/core/src/main/jdk1.1/org/spongycastle/i18n/MissingEntryException.java +++ /dev/null @@ -1,63 +0,0 @@ -package org.spongycastle.i18n; - -import java.net.URL; -import java.util.Locale; - -public class MissingEntryException extends RuntimeException -{ - - protected final String resource; - protected final String key; - protected final ClassLoader loader; - protected final Locale locale; - - private String debugMsg; - - public MissingEntryException(String message, String resource, String key, Locale locale, ClassLoader loader) - { - super(message); - this.resource = resource; - this.key = key; - this.locale = locale; - this.loader = loader; - } - - public MissingEntryException(String message, Throwable cause, String resource, String key, Locale locale, ClassLoader loader) - { - super(message + ": " + cause); - this.resource = resource; - this.key = key; - this.locale = locale; - this.loader = loader; - } - - public String getKey() - { - return key; - } - - public String getResource() - { - return resource; - } - - public ClassLoader getClassLoader() - { - return loader; - } - - public Locale getLocale() - { - return locale; - } - - public String getDebugMsg() - { - if (debugMsg == null) - { - debugMsg = "Can not find entry " + key + " in resource file " + resource + " for the locale " + locale + "."; - } - return debugMsg; - } - -} diff --git a/extern/spongycastle/core/src/main/jdk1.2/java/security/interfaces/RSAMultiPrimePrivateCrtKey.java b/extern/spongycastle/core/src/main/jdk1.2/java/security/interfaces/RSAMultiPrimePrivateCrtKey.java deleted file mode 100644 index 042eb3eb2..000000000 --- a/extern/spongycastle/core/src/main/jdk1.2/java/security/interfaces/RSAMultiPrimePrivateCrtKey.java +++ /dev/null @@ -1,67 +0,0 @@ - -package java.security.interfaces; - -import java.math.BigInteger; -import java.security.spec.RSAOtherPrimeInfo; - -/** - * The interface to an RSA multi-prime private key, as defined in the - * PKCS#1 v2.1, using the Chinese Remainder Theorem (CRT) information values. - * - * @since 1.4 - * @see RSAPrivateKeySpec, RSAMultiPrimePrivateCrtKeySpec, RSAPrivateKey, - * RSAPrivateCrtKey - */ -public interface RSAMultiPrimePrivateCrtKey -extends RSAPrivateKey -{ - /** - * Returns the public exponent. - * - * @returns the public exponent. - */ - public BigInteger getPublicExponent(); - - /** - * Returns the primeP. - * - * @returns the primeP. - */ - public BigInteger getPrimeP(); - - /** - * Returns the primeQ. - * - * @returns the primeQ. - */ - public BigInteger getPrimeQ(); - - /** - * Returns the primeExponentP. - * - * @returns the primeExponentP. - */ - public BigInteger getPrimeExponentP(); - - /** - * Returns the primeExponentQ. - * - * @returns the primeExponentQ. - */ - public BigInteger getPrimeExponentQ(); - - /** - * Returns the crtCoefficient. - * - * @returns the crtCoefficient. - */ - public BigInteger getCrtCoefficient(); - - /** - * Returns the otherPrimeInfo or null if there are only two prime - * factors (p and q). - * - * @returns the otherPrimeInfo. - */ - public RSAOtherPrimeInfo[] getOtherPrimeInfo(); -} diff --git a/extern/spongycastle/core/src/main/jdk1.2/java/security/spec/PSSParameterSpec.java b/extern/spongycastle/core/src/main/jdk1.2/java/security/spec/PSSParameterSpec.java deleted file mode 100644 index f58d83b78..000000000 --- a/extern/spongycastle/core/src/main/jdk1.2/java/security/spec/PSSParameterSpec.java +++ /dev/null @@ -1,45 +0,0 @@ - -package java.security.spec; - -/** - * This class specifies a parameter spec for RSA PSS encoding scheme, - * as defined in the PKCS#1 v2.1. - * - * @since 1.4 - * @see AlgorithmParameterSpec, Signature - */ -public class PSSParameterSpec - extends Object - implements AlgorithmParameterSpec -{ - private int saltLen; - - /** - * Creates a new PSSParameterSpec given the salt length as defined - * in PKCS#1. - * - * @param saltLen - the length of salt in bits to be used in PKCS#1 - * PSS encoding. - * @throws IllegalArgumentException - if saltLen is less than 0. - */ - public PSSParameterSpec(int saltLen) - { - if ( saltLen < 0 ) - { - throw new IllegalArgumentException("Salt length must be >= 0"); - } - - this.saltLen = saltLen; - } - - /** - * Returns the salt length in bits. - * - * @returns the salt length. - */ - public int getSaltLength() - { - return saltLen; - } -} - diff --git a/extern/spongycastle/core/src/main/jdk1.2/java/security/spec/RSAKeyGenParameterSpec.java b/extern/spongycastle/core/src/main/jdk1.2/java/security/spec/RSAKeyGenParameterSpec.java deleted file mode 100644 index 756c6c0fd..000000000 --- a/extern/spongycastle/core/src/main/jdk1.2/java/security/spec/RSAKeyGenParameterSpec.java +++ /dev/null @@ -1,35 +0,0 @@ -package java.security.spec; - -import java.math.BigInteger; - -/** - * specifies parameters to be used for the generation of - * a RSA key pair. - */ -public class RSAKeyGenParameterSpec - implements AlgorithmParameterSpec -{ - static BigInteger F0 = BigInteger.valueOf(3); - static BigInteger F4 = BigInteger.valueOf(65537); - - private int keysize; - private BigInteger publicExponent; - - public RSAKeyGenParameterSpec( - int keysize, - BigInteger publicExponent) - { - this.keysize = keysize; - this.publicExponent = publicExponent; - } - - public int getKeysize() - { - return keysize; - } - - public BigInteger getPublicExponent() - { - return publicExponent; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.2/java/security/spec/RSAMultiPrimePrivateCrtKeySpec.java b/extern/spongycastle/core/src/main/jdk1.2/java/security/spec/RSAMultiPrimePrivateCrtKeySpec.java deleted file mode 100644 index 1339b4f6d..000000000 --- a/extern/spongycastle/core/src/main/jdk1.2/java/security/spec/RSAMultiPrimePrivateCrtKeySpec.java +++ /dev/null @@ -1,159 +0,0 @@ - -package java.security.spec; - -import java.math.BigInteger; - -/** - * This class specifies an RSA multi-prime private key, as defined in - * the PKCS#1 v2.1, using the Chinese Remainder Theorem (CRT) information - * values for efficiency. - * - * @since 1.4 - * @see Key, KeyFactory, KeySpec, PKCS8EncodedKeySpec, RSAPrivateKeySpec, - * RSAPublicKeySpec, RSAOtherPrimeInfo - */ -public class RSAMultiPrimePrivateCrtKeySpec - extends RSAPrivateKeySpec -{ - private BigInteger publicExponent; - private BigInteger privateExponent; - private BigInteger primeP; - private BigInteger primeQ; - private BigInteger primeExponentP; - private BigInteger primeExponentQ; - private BigInteger crtCoefficient; - private RSAOtherPrimeInfo[] otherPrimeInfo; - - /** - * Creates a new RSAMultiPrimePrivateCrtKeySpec given the modulus, - * publicExponent, privateExponent, primeP, primeQ, primeExponentP, - * primeExponentQ, crtCoefficient, and otherPrimeInfo as defined in - * PKCS#1 v2.1. - * - * Note that otherPrimeInfo is cloned when constructing this object. - * - * @param modulus - the modulus n. - * @param publicExponent - the public exponent e. - * @param privateExponent - the private exponent d. - * @param primeP - the prime factor p of n. - * @param primeQ - the prime factor q of n. - * @param primeExponentP - this is d mod (p-1). - * @param primeExponentQ - this is d mod (q-1). - * @param crtCoefficient - the Chinese Remainder Theorem coefficient q-1 - * mod p. - * @param otherPrimeInfo - triplets of the rest of primes, null can be - * specified if there are only two prime factors (p and q). - * @throws NullPointerException - if any of the parameters, i.e. modulus, - * publicExponent, privateExponent, primeP, primeQ, primeExponentP, - * primeExponentQ, crtCoefficient, is null. - * @throws IllegalArgumentException - if an empty, i.e. 0-length, - * otherPrimeInfo is specified. - */ - public RSAMultiPrimePrivateCrtKeySpec( - BigInteger modulus, - BigInteger publicExponent, - BigInteger privateExponent, - BigInteger primeP, - BigInteger primeQ, - BigInteger primeExponentP, - BigInteger primeExponentQ, - BigInteger crtCoefficient, - RSAOtherPrimeInfo[] otherPrimeInfo) - { - super(modulus, privateExponent); - - if ( publicExponent == null || primeP == null || primeQ == null - || primeExponentP == null || primeExponentQ == null - || crtCoefficient == null ) - { - throw new NullPointerException("Invalid null argument"); - } - - if ( otherPrimeInfo != null ) - { - if ( otherPrimeInfo.length == 0 ) - { - throw new IllegalArgumentException("Invalid length for otherPrimeInfo"); - } - - this.otherPrimeInfo = (RSAOtherPrimeInfo[])otherPrimeInfo.clone(); - } - } - - /** - * Returns the public exponent. - * - * @returns the public exponent. - */ - public BigInteger getPublicExponent() - { - return publicExponent; - } - - /** - * Returns the primeP. - * - * @returns the primeP. - */ - public BigInteger getPrimeP() - { - return primeP; - } - - /** - * Returns the primeQ. - * - * @returns the primeQ. - */ - public BigInteger getPrimeQ() - { - return primeQ; - } - - /** - * Returns the primeExponentP. - * - * @returns the primeExponentP. - */ - public BigInteger getPrimeExponentP() - { - return primeExponentP; - } - - /** - * Returns the primeExponentQ. - * - * @returns the primeExponentQ. - */ - public BigInteger getPrimeExponentQ() - { - return primeExponentQ; - } - - /** - * Returns the crtCofficient. - * - * @returns the crtCofficient. - */ - public BigInteger getCrtCoefficient() - { - return crtCoefficient; - } - - /** - * Returns a copy of the otherPrimeInfo or null if there are only - * two prime factors (p and q). - * - * @returns the otherPrimeInfo. - */ - public RSAOtherPrimeInfo[] getOtherPrimeInfo() - { - if ( otherPrimeInfo != null ) - { - return (RSAOtherPrimeInfo[])otherPrimeInfo.clone(); - } - - return null; - } -} - diff --git a/extern/spongycastle/core/src/main/jdk1.2/java/security/spec/RSAOtherPrimeInfo.java b/extern/spongycastle/core/src/main/jdk1.2/java/security/spec/RSAOtherPrimeInfo.java deleted file mode 100644 index 42a4fce6d..000000000 --- a/extern/spongycastle/core/src/main/jdk1.2/java/security/spec/RSAOtherPrimeInfo.java +++ /dev/null @@ -1,80 +0,0 @@ - -package java.security.spec; - -import java.math.BigInteger; - -/** - * This class represents the triplet (prime, exponent, and coefficient) - * inside RSA's OtherPrimeInfo structure, as defined in the PKCS#1 v2.1. - * The ASN.1 syntax of RSA's OtherPrimeInfo is as follows: - * - *
- * OtherPrimeInfo ::= SEQUENCE {
- *    prime INTEGER,
- *    exponent INTEGER,
- *    coefficient INTEGER
- * }
- * 
- */ -public class RSAOtherPrimeInfo -extends Object -{ - private BigInteger prime; - private BigInteger primeExponent; - private BigInteger crtCoefficient; - - /** - * Creates a new RSAOtherPrimeInfo given the prime, primeExponent, - * and crtCoefficient as defined in PKCS#1. - * - * @param prime - the prime factor of n. - * @param primeExponent - the exponent. - * @param crtCoefficient - the Chinese Remainder Theorem coefficient. - * @throws NullPointerException - if any of the parameters, i.e. prime, - * primeExponent, crtCoefficient, is null. - */ - public RSAOtherPrimeInfo( - BigInteger prime, - BigInteger primeExponent, - BigInteger crtCoefficient) - { - if ( prime == null || primeExponent == null || crtCoefficient == null ) - { - throw new NullPointerException("Null parameter"); - } - - this.prime = prime; - this.primeExponent = primeExponent; - this.crtCoefficient = crtCoefficient; - } - - /** - * Returns the prime. - * - * @returns the prime. - */ - public final BigInteger getPrime() - { - return prime; - } - - /** - * Returns the prime's exponent. - * - * @returns the primeExponent. - */ - public final BigInteger getExponent() - { - return primeExponent; - } - - /** - * Returns the prime's crtCoefficient. - * - * @returns the crtCoefficient. - */ - public final BigInteger getCrtCoefficient() - { - return crtCoefficient; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.2/org/spongycastle/i18n/LocalizedMessage.java b/extern/spongycastle/core/src/main/jdk1.2/org/spongycastle/i18n/LocalizedMessage.java deleted file mode 100644 index 1eab110cb..000000000 --- a/extern/spongycastle/core/src/main/jdk1.2/org/spongycastle/i18n/LocalizedMessage.java +++ /dev/null @@ -1,464 +0,0 @@ -package org.spongycastle.i18n; - -import org.spongycastle.i18n.filter.Filter; -import org.spongycastle.i18n.filter.TrustedInput; -import org.spongycastle.i18n.filter.UntrustedInput; -import org.spongycastle.i18n.filter.UntrustedUrlInput; - -import java.io.UnsupportedEncodingException; -import java.text.DateFormat; -import java.text.Format; -import java.text.MessageFormat; -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.ResourceBundle; -import java.util.TimeZone; - -public class LocalizedMessage -{ - protected static final int NO_FILTER = 0; - protected static final int FILTER = 1; - protected static final int FILTER_URL = 2; - - protected String id; - protected String resource; - - // ISO-8859-1 is the default encoding - public static final String DEFAULT_ENCODING = "ISO-8859-1"; - protected String encoding = DEFAULT_ENCODING; - - protected FilteredArguments arguments; - protected FilteredArguments extraArgs = null; - - protected Filter filter = null; - - protected ClassLoader loader = null; - - /** - * Constructs a new LocalizedMessage using resource as the base name for the - * RessourceBundle and id as the message bundle id the resource file. - * @param resource base name of the resource file - * @param id the id of the corresponding bundle in the resource file - * @throws NullPointerException if resource or id is null - */ - public LocalizedMessage(String resource,String id) throws NullPointerException - { - if (resource == null || id == null) - { - throw new NullPointerException(); - } - this.id = id; - this.resource = resource; - arguments = new FilteredArguments(); - } - - /** - * Constructs a new LocalizedMessage using resource as the base name for the - * RessourceBundle and id as the message bundle id the resource file. - * @param resource base name of the resource file - * @param id the id of the corresponding bundle in the resource file - * @param encoding the encoding of the resource file - * @throws NullPointerException if resource or id is null - * @throws UnsupportedEncodingException if the encoding is not supported - */ - public LocalizedMessage(String resource,String id, String encoding) throws NullPointerException, UnsupportedEncodingException - { - if (resource == null || id == null) - { - throw new NullPointerException(); - } - this.id = id; - this.resource = resource; - arguments = new FilteredArguments(); - this.encoding = encoding; - } - - /** - * Constructs a new LocalizedMessage using resource as the base name for the - * RessourceBundle and id as the message bundle id the resource file. - * @param resource base name of the resource file - * @param id the id of the corresponding bundle in the resource file - * @param arguments an array containing the arguments for the message - * @throws NullPointerException if resource or id is null - */ - public LocalizedMessage(String resource, String id, Object[] arguments) throws NullPointerException - { - if (resource == null || id == null || arguments == null) - { - throw new NullPointerException(); - } - this.id = id; - this.resource = resource; - this.arguments = new FilteredArguments(arguments); - } - - /** - * Constructs a new LocalizedMessage using resource as the base name for the - * RessourceBundle and id as the message bundle id the resource file. - * @param resource base name of the resource file - * @param id the id of the corresponding bundle in the resource file - * @param encoding the encoding of the resource file - * @param arguments an array containing the arguments for the message - * @throws NullPointerException if resource or id is null - * @throws UnsupportedEncodingException if the encoding is not supported - */ - public LocalizedMessage(String resource, String id, String encoding, Object[] arguments) throws NullPointerException, UnsupportedEncodingException - { - if (resource == null || id == null || arguments == null) - { - throw new NullPointerException(); - } - this.id = id; - this.resource = resource; - this.arguments = new FilteredArguments(arguments); - this.encoding = encoding; - } - - /** - * Reads the entry id + "." + key from the resource file and returns a - * formated message for the given Locale and TimeZone. - * @param key second part of the entry id - * @param loc the used {@link Locale} - * @param timezone the used {@link TimeZone} - * @return a Strng containing the localized message - * @throws MissingEntryException if the resource file is not available or the entry does not exist. - */ - public String getEntry(String key,Locale loc, TimeZone timezone) throws MissingEntryException - { - String entry = id; - if (key != null) - { - entry += "." + key; - } - - try - { - ResourceBundle bundle; - if (loader == null) - { - bundle = ResourceBundle.getBundle(resource,loc); - } - else - { - bundle = ResourceBundle.getBundle(resource, loc); - } - String result = bundle.getString(entry); - if (!encoding.equals(DEFAULT_ENCODING)) - { - result = new String(result.getBytes(DEFAULT_ENCODING), encoding); - } - if (!arguments.isEmpty()) - { - result = formatWithTimeZone(result,arguments.getFilteredArgs(loc),loc,timezone); - } - result = addExtraArgs(result, loc); - return result; - } - catch (MissingResourceException mre) - { - throw new MissingEntryException("Can't find entry " + entry + " in resource file " + resource + ".", - resource, - entry, - loc, - loader != null ? loader : this.getClassLoader()); - } - catch (UnsupportedEncodingException use) - { - // should never occur - cause we already test this in the constructor - throw new RuntimeException(use.toString()); - } - } - - protected String formatWithTimeZone( - String template, - Object[] arguments, - Locale locale, - TimeZone timezone) - { - MessageFormat mf = new MessageFormat(" "); - mf.setLocale(locale); - mf.applyPattern(template); - if (!timezone.equals(TimeZone.getDefault())) - { - Format[] formats = mf.getFormats(); - for (int i = 0; i < formats.length; i++) - { - if (formats[i] instanceof DateFormat) - { - DateFormat temp = (DateFormat) formats[i]; - temp.setTimeZone(timezone); - mf.setFormat(i,temp); - } - } - } - return mf.format(arguments); - } - - protected String addExtraArgs(String msg, Locale locale) - { - if (extraArgs != null) - { - StringBuffer sb = new StringBuffer(msg); - Object[] filteredArgs = extraArgs.getFilteredArgs(locale); - for (int i = 0; i < filteredArgs.length; i++) - { - sb.append(filteredArgs[i]); - } - msg = sb.toString(); - } - return msg; - } - - /** - * Sets the {@link Filter} that is used to filter the arguments of this message - * @param filter the {@link Filter} to use. null to disable filtering. - */ - public void setFilter(Filter filter) - { - arguments.setFilter(filter); - if (extraArgs != null) - { - extraArgs.setFilter(filter); - } - this.filter = filter; - } - - /** - * Returns the current filter. - * @return the current filter - */ - public Filter getFilter() - { - return filter; - } - - /** - * Set the {@link ClassLoader} which loads the resource files. If it is set to null - * then the default {@link ClassLoader} is used. - * @param loader the {@link ClassLoader} which loads the resource files - */ - public void setClassLoader(ClassLoader loader) - { - this.loader = loader; - } - - /** - * Returns the {@link ClassLoader} which loads the resource files or null - * if the default ClassLoader is used. - * @return the {@link ClassLoader} which loads the resource files - */ - public ClassLoader getClassLoader() - { - return loader; - } - - /** - * Returns the id of the message in the resource bundle. - * @return the id of the message - */ - public String getId() - { - return id; - } - - /** - * Returns the name of the resource bundle for this message - * @return name of the resource file - */ - public String getResource() - { - return resource; - } - - /** - * Returns an Object[] containing the message arguments. - * @return the message arguments - */ - public Object[] getArguments() - { - return arguments.getArguments(); - } - - /** - * - * @param extraArg - */ - public void setExtraArgument(Object extraArg) - { - setExtraArguments(new Object[] {extraArg}); - } - - /** - * - * @param extraArgs - */ - public void setExtraArguments(Object[] extraArgs) - { - if (extraArgs != null) - { - this.extraArgs = new FilteredArguments(extraArgs); - this.extraArgs.setFilter(filter); - } - else - { - this.extraArgs = null; - } - } - - /** - * - * @return - */ - public Object[] getExtraArgs() - { - return (extraArgs == null) ? null : extraArgs.getArguments(); - } - - protected class FilteredArguments - { - - protected Filter filter = null; - - protected boolean[] isLocaleSpecific; - protected int[] argFilterType; - protected Object[] arguments; - protected Object[] unpackedArgs; - protected Object[] filteredArgs; - - FilteredArguments() - { - this(new Object[0]); - } - - FilteredArguments(Object[] args) - { - this.arguments = args; - this.unpackedArgs = new Object[args.length]; - this.filteredArgs = new Object[args.length]; - this.isLocaleSpecific = new boolean[args.length]; - this.argFilterType = new int[args.length]; - for (int i = 0; i < args.length; i++) - { - if (args[i] instanceof TrustedInput) - { - this.unpackedArgs[i] = ((TrustedInput) args[i]).getInput(); - argFilterType[i] = NO_FILTER; - } - else if (args[i] instanceof UntrustedInput) - { - this.unpackedArgs[i] = ((UntrustedInput) args[i]).getInput(); - if (args[i] instanceof UntrustedUrlInput) - { - argFilterType[i] = FILTER_URL; - } - else - { - argFilterType[i] = FILTER; - } - } - else - { - this.unpackedArgs[i] = args[i]; - argFilterType[i] = FILTER; - } - - // locale specific - this.isLocaleSpecific[i] = (this.unpackedArgs[i] instanceof LocaleString); - } - } - - public boolean isEmpty() - { - return unpackedArgs.length == 0; - } - - public Object[] getArguments() - { - return arguments; - } - - public Object[] getFilteredArgs(Locale locale) - { - Object[] result = new Object[unpackedArgs.length]; - for (int i = 0; i < unpackedArgs.length; i++) - { - Object arg; - if (filteredArgs[i] != null) - { - arg = filteredArgs[i]; - } - else - { - arg = unpackedArgs[i]; - if (isLocaleSpecific[i]) - { - // get locale - arg = ((LocaleString) arg).getLocaleString(locale); - arg = filter(argFilterType[i], arg); - } - else - { - arg = filter(argFilterType[i], arg); - filteredArgs[i] = arg; - } - } - result[i] = arg; - } - return result; - } - - private Object filter(int type, Object obj) - { - if (filter != null) - { - Object o = (null == obj) ? "null" : obj; - switch (type) - { - case NO_FILTER: - return o; - case FILTER: - return filter.doFilter(o.toString()); - case FILTER_URL: - return filter.doFilterUrl(o.toString()); - default: - return null; - } - } - else - { - return obj; - } - } - - public Filter getFilter() - { - return filter; - } - - public void setFilter(Filter filter) - { - if (filter != this.filter) - { - for (int i = 0; i < unpackedArgs.length; i++) - { - filteredArgs[i] = null; - } - } - this.filter = filter; - } - - } - - public String toString() - { - StringBuffer sb = new StringBuffer(); - sb.append("Resource: \"").append(resource); - sb.append("\" Id: \"").append(id).append("\""); - sb.append(" Arguments: ").append(arguments.getArguments().length).append(" normal, ") - .append(extraArgs.getArguments().length).append(" extra"); - sb.append(" Encoding: ").append(encoding); - sb.append(" ClassLoader: ").append(loader); - return sb.toString(); - } - -} diff --git a/extern/spongycastle/core/src/main/jdk1.2/org/spongycastle/i18n/MissingEntryException.java b/extern/spongycastle/core/src/main/jdk1.2/org/spongycastle/i18n/MissingEntryException.java deleted file mode 100644 index d876a91af..000000000 --- a/extern/spongycastle/core/src/main/jdk1.2/org/spongycastle/i18n/MissingEntryException.java +++ /dev/null @@ -1,63 +0,0 @@ -package org.spongycastle.i18n; - -import java.net.URL; -import java.util.Locale; - -public class MissingEntryException extends RuntimeException -{ - - protected final String resource; - protected final String key; - protected final ClassLoader loader; - protected final Locale locale; - - private String debugMsg; - - public MissingEntryException(String message, String resource, String key, Locale locale, ClassLoader loader) - { - super(message); - this.resource = resource; - this.key = key; - this.locale = locale; - this.loader = loader; - } - - public MissingEntryException(String message, Throwable cause, String resource, String key, Locale locale, ClassLoader loader) - { - super(message + ": " + cause); - this.resource = resource; - this.key = key; - this.locale = locale; - this.loader = loader; - } - - public String getKey() - { - return key; - } - - public String getResource() - { - return resource; - } - - public ClassLoader getClassLoader() - { - return loader; - } - - public Locale getLocale() - { - return locale; - } - - public String getDebugMsg() - { - if (debugMsg == null) - { - debugMsg = "Can not find entry " + key + " in resource file " + resource + " for the locale " + locale + "."; - } - return debugMsg; - } - -} diff --git a/extern/spongycastle/core/src/main/jdk1.3/org/spongycastle/asn1/StreamUtil.java b/extern/spongycastle/core/src/main/jdk1.3/org/spongycastle/asn1/StreamUtil.java deleted file mode 100644 index 0b0b183e6..000000000 --- a/extern/spongycastle/core/src/main/jdk1.3/org/spongycastle/asn1/StreamUtil.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.spongycastle.asn1; - -import java.io.ByteArrayInputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -class StreamUtil -{ - /** - * Find out possible longest length... - * - * @param in input stream of interest - * @return length calculation or MAX_VALUE. - */ - static int findLimit(InputStream in) - { - if (in instanceof LimitedInputStream) - { - return ((LimitedInputStream)in).getRemaining(); - } - else if (in instanceof ASN1InputStream) - { - return ((ASN1InputStream)in).getLimit(); - } - else if (in instanceof ByteArrayInputStream) - { - return ((ByteArrayInputStream)in).available(); - } - - return Integer.MAX_VALUE; - } - - static int calculateBodyLength( - int length) - { - int count = 1; - - if (length > 127) - { - int size = 1; - int val = length; - - while ((val >>>= 8) != 0) - { - size++; - } - - for (int i = (size - 1) * 8; i >= 0; i -= 8) - { - count++; - } - } - - return count; - } - - static int calculateTagLength(int tagNo) - throws IOException - { - int length = 1; - - if (tagNo >= 31) - { - if (tagNo < 128) - { - length++; - } - else - { - byte[] stack = new byte[5]; - int pos = stack.length; - - stack[--pos] = (byte)(tagNo & 0x7F); - - do - { - tagNo >>= 7; - stack[--pos] = (byte)(tagNo & 0x7F | 0x80); - } - while (tagNo > 127); - - length += stack.length - pos; - } - } - - return length; - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.3/org/spongycastle/crypto/tls/UDPTransport.java b/extern/spongycastle/core/src/main/jdk1.3/org/spongycastle/crypto/tls/UDPTransport.java deleted file mode 100644 index 9391e1d26..000000000 --- a/extern/spongycastle/core/src/main/jdk1.3/org/spongycastle/crypto/tls/UDPTransport.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.spongycastle.crypto.tls; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; - -public class UDPTransport - implements DatagramTransport -{ - protected final static int MIN_IP_OVERHEAD = 20; - protected final static int MAX_IP_OVERHEAD = MIN_IP_OVERHEAD + 64; - protected final static int UDP_OVERHEAD = 8; - - protected final DatagramSocket socket; - protected final int receiveLimit, sendLimit; - - public UDPTransport(DatagramSocket socket, int mtu) - throws IOException - { - // - // In 1.3 and earlier sockets were bound and connected during creation - // - //if (!socket.isBound() || !socket.isConnected()) - //{ - // throw new IllegalArgumentException("'socket' must be bound and connected"); - //} - - this.socket = socket; - - // NOTE: As of JDK 1.6, can use NetworkInterface.getMTU - - this.receiveLimit = mtu - MIN_IP_OVERHEAD - UDP_OVERHEAD; - this.sendLimit = mtu - MAX_IP_OVERHEAD - UDP_OVERHEAD; - } - - public int getReceiveLimit() - { - return receiveLimit; - } - - public int getSendLimit() - { - // TODO[DTLS] Implement Path-MTU discovery? - return sendLimit; - } - - public int receive(byte[] buf, int off, int len, int waitMillis) - throws IOException - { - socket.setSoTimeout(waitMillis); - DatagramPacket packet = new DatagramPacket(buf, off, len); - socket.receive(packet); - return packet.getLength(); - } - - public void send(byte[] buf, int off, int len) - throws IOException - { - if (len > getSendLimit()) - { - /* - * RFC 4347 4.1.1. "If the application attempts to send a record larger than the MTU, - * the DTLS implementation SHOULD generate an error, thus avoiding sending a packet - * which will be fragmented." - */ - throw new TlsFatalAlert(AlertDescription.internal_error); - } - - DatagramPacket packet = new DatagramPacket(buf, off, len); - socket.send(packet); - } - - public void close() - throws IOException - { - socket.close(); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.3/org/spongycastle/i18n/LocalizedMessage.java b/extern/spongycastle/core/src/main/jdk1.3/org/spongycastle/i18n/LocalizedMessage.java deleted file mode 100644 index e0a4d84ce..000000000 --- a/extern/spongycastle/core/src/main/jdk1.3/org/spongycastle/i18n/LocalizedMessage.java +++ /dev/null @@ -1,464 +0,0 @@ -package org.spongycastle.i18n; - -import org.spongycastle.i18n.filter.Filter; -import org.spongycastle.i18n.filter.TrustedInput; -import org.spongycastle.i18n.filter.UntrustedInput; -import org.spongycastle.i18n.filter.UntrustedUrlInput; - -import java.io.UnsupportedEncodingException; -import java.text.DateFormat; -import java.text.Format; -import java.text.MessageFormat; -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.ResourceBundle; -import java.util.TimeZone; - -public class LocalizedMessage -{ - - protected final String id; - protected final String resource; - - // ISO-8859-1 is the default encoding - public static final String DEFAULT_ENCODING = "ISO-8859-1"; - protected String encoding = DEFAULT_ENCODING; - - protected FilteredArguments arguments; - protected FilteredArguments extraArgs = null; - - protected Filter filter = null; - - protected ClassLoader loader = null; - - /** - * Constructs a new LocalizedMessage using resource as the base name for the - * RessourceBundle and id as the message bundle id the resource file. - * @param resource base name of the resource file - * @param id the id of the corresponding bundle in the resource file - * @throws NullPointerException if resource or id is null - */ - public LocalizedMessage(String resource,String id) throws NullPointerException - { - if (resource == null || id == null) - { - throw new NullPointerException(); - } - this.id = id; - this.resource = resource; - arguments = new FilteredArguments(); - } - - /** - * Constructs a new LocalizedMessage using resource as the base name for the - * RessourceBundle and id as the message bundle id the resource file. - * @param resource base name of the resource file - * @param id the id of the corresponding bundle in the resource file - * @param encoding the encoding of the resource file - * @throws NullPointerException if resource or id is null - * @throws UnsupportedEncodingException if the encoding is not supported - */ - public LocalizedMessage(String resource,String id, String encoding) throws NullPointerException, UnsupportedEncodingException - { - if (resource == null || id == null) - { - throw new NullPointerException(); - } - this.id = id; - this.resource = resource; - arguments = new FilteredArguments(); - this.encoding = encoding; - } - - /** - * Constructs a new LocalizedMessage using resource as the base name for the - * RessourceBundle and id as the message bundle id the resource file. - * @param resource base name of the resource file - * @param id the id of the corresponding bundle in the resource file - * @param arguments an array containing the arguments for the message - * @throws NullPointerException if resource or id is null - */ - public LocalizedMessage(String resource, String id, Object[] arguments) throws NullPointerException - { - if (resource == null || id == null || arguments == null) - { - throw new NullPointerException(); - } - this.id = id; - this.resource = resource; - this.arguments = new FilteredArguments(arguments); - } - - /** - * Constructs a new LocalizedMessage using resource as the base name for the - * RessourceBundle and id as the message bundle id the resource file. - * @param resource base name of the resource file - * @param id the id of the corresponding bundle in the resource file - * @param encoding the encoding of the resource file - * @param arguments an array containing the arguments for the message - * @throws NullPointerException if resource or id is null - * @throws UnsupportedEncodingException if the encoding is not supported - */ - public LocalizedMessage(String resource, String id, String encoding, Object[] arguments) throws NullPointerException, UnsupportedEncodingException - { - if (resource == null || id == null || arguments == null) - { - throw new NullPointerException(); - } - this.id = id; - this.resource = resource; - this.arguments = new FilteredArguments(arguments); - this.encoding = encoding; - } - - /** - * Reads the entry id + "." + key from the resource file and returns a - * formated message for the given Locale and TimeZone. - * @param key second part of the entry id - * @param loc the used {@link Locale} - * @param timezone the used {@link TimeZone} - * @return a Strng containing the localized message - * @throws MissingEntryException if the resource file is not available or the entry does not exist. - */ - public String getEntry(String key,Locale loc, TimeZone timezone) throws MissingEntryException - { - String entry = id; - if (key != null) - { - entry += "." + key; - } - - try - { - ResourceBundle bundle; - if (loader == null) - { - bundle = ResourceBundle.getBundle(resource,loc); - } - else - { - bundle = ResourceBundle.getBundle(resource, loc, loader); - } - String result = bundle.getString(entry); - if (!encoding.equals(DEFAULT_ENCODING)) - { - result = new String(result.getBytes(DEFAULT_ENCODING), encoding); - } - if (!arguments.isEmpty()) - { - result = formatWithTimeZone(result,arguments.getFilteredArgs(loc),loc,timezone); - } - result = addExtraArgs(result, loc); - return result; - } - catch (MissingResourceException mre) - { - throw new MissingEntryException("Can't find entry " + entry + " in resource file " + resource + ".", - resource, - entry, - loc, - loader != null ? loader : this.getClassLoader()); - } - catch (UnsupportedEncodingException use) - { - // should never occur - cause we already test this in the constructor - throw new RuntimeException(use.toString()); - } - } - - protected String formatWithTimeZone( - String template, - Object[] arguments, - Locale locale, - TimeZone timezone) - { - MessageFormat mf = new MessageFormat(" "); - mf.setLocale(locale); - mf.applyPattern(template); - if (!timezone.equals(TimeZone.getDefault())) - { - Format[] formats = mf.getFormats(); - for (int i = 0; i < formats.length; i++) - { - if (formats[i] instanceof DateFormat) - { - DateFormat temp = (DateFormat) formats[i]; - temp.setTimeZone(timezone); - mf.setFormat(i,temp); - } - } - } - return mf.format(arguments); - } - - protected String addExtraArgs(String msg, Locale locale) - { - if (extraArgs != null) - { - StringBuffer sb = new StringBuffer(msg); - Object[] filteredArgs = extraArgs.getFilteredArgs(locale); - for (int i = 0; i < filteredArgs.length; i++) - { - sb.append(filteredArgs[i]); - } - msg = sb.toString(); - } - return msg; - } - - /** - * Sets the {@link Filter} that is used to filter the arguments of this message - * @param filter the {@link Filter} to use. null to disable filtering. - */ - public void setFilter(Filter filter) - { - arguments.setFilter(filter); - if (extraArgs != null) - { - extraArgs.setFilter(filter); - } - this.filter = filter; - } - - /** - * Returns the current filter. - * @return the current filter - */ - public Filter getFilter() - { - return filter; - } - - /** - * Set the {@link ClassLoader} which loads the resource files. If it is set to null - * then the default {@link ClassLoader} is used. - * @param loader the {@link ClassLoader} which loads the resource files - */ - public void setClassLoader(ClassLoader loader) - { - this.loader = loader; - } - - /** - * Returns the {@link ClassLoader} which loads the resource files or null - * if the default ClassLoader is used. - * @return the {@link ClassLoader} which loads the resource files - */ - public ClassLoader getClassLoader() - { - return loader; - } - - /** - * Returns the id of the message in the resource bundle. - * @return the id of the message - */ - public String getId() - { - return id; - } - - /** - * Returns the name of the resource bundle for this message - * @return name of the resource file - */ - public String getResource() - { - return resource; - } - - /** - * Returns an Object[] containing the message arguments. - * @return the message arguments - */ - public Object[] getArguments() - { - return arguments.getArguments(); - } - - /** - * - * @param extraArg - */ - public void setExtraArgument(Object extraArg) - { - setExtraArguments(new Object[] {extraArg}); - } - - /** - * - * @param extraArgs - */ - public void setExtraArguments(Object[] extraArgs) - { - if (extraArgs != null) - { - this.extraArgs = new FilteredArguments(extraArgs); - this.extraArgs.setFilter(filter); - } - else - { - this.extraArgs = null; - } - } - - /** - * - * @return - */ - public Object[] getExtraArgs() - { - return (extraArgs == null) ? null : extraArgs.getArguments(); - } - - protected class FilteredArguments - { - protected static final int NO_FILTER = 0; - protected static final int FILTER = 1; - protected static final int FILTER_URL = 2; - - protected Filter filter = null; - - protected boolean[] isLocaleSpecific; - protected int[] argFilterType; - protected Object[] arguments; - protected Object[] unpackedArgs; - protected Object[] filteredArgs; - - FilteredArguments() - { - this(new Object[0]); - } - - FilteredArguments(Object[] args) - { - this.arguments = args; - this.unpackedArgs = new Object[args.length]; - this.filteredArgs = new Object[args.length]; - this.isLocaleSpecific = new boolean[args.length]; - this.argFilterType = new int[args.length]; - for (int i = 0; i < args.length; i++) - { - if (args[i] instanceof TrustedInput) - { - this.unpackedArgs[i] = ((TrustedInput) args[i]).getInput(); - argFilterType[i] = NO_FILTER; - } - else if (args[i] instanceof UntrustedInput) - { - this.unpackedArgs[i] = ((UntrustedInput) args[i]).getInput(); - if (args[i] instanceof UntrustedUrlInput) - { - argFilterType[i] = FILTER_URL; - } - else - { - argFilterType[i] = FILTER; - } - } - else - { - this.unpackedArgs[i] = args[i]; - argFilterType[i] = FILTER; - } - - // locale specific - this.isLocaleSpecific[i] = (this.unpackedArgs[i] instanceof LocaleString); - } - } - - public boolean isEmpty() - { - return unpackedArgs.length == 0; - } - - public Object[] getArguments() - { - return arguments; - } - - public Object[] getFilteredArgs(Locale locale) - { - Object[] result = new Object[unpackedArgs.length]; - for (int i = 0; i < unpackedArgs.length; i++) - { - Object arg; - if (filteredArgs[i] != null) - { - arg = filteredArgs[i]; - } - else - { - arg = unpackedArgs[i]; - if (isLocaleSpecific[i]) - { - // get locale - arg = ((LocaleString) arg).getLocaleString(locale); - arg = filter(argFilterType[i], arg); - } - else - { - arg = filter(argFilterType[i], arg); - filteredArgs[i] = arg; - } - } - result[i] = arg; - } - return result; - } - - private Object filter(int type, Object obj) - { - if (filter != null) - { - Object o = (null == obj) ? "null" : obj; - switch (type) - { - case NO_FILTER: - return o; - case FILTER: - return filter.doFilter(o.toString()); - case FILTER_URL: - return filter.doFilterUrl(o.toString()); - default: - return null; - } - } - else - { - return obj; - } - } - - public Filter getFilter() - { - return filter; - } - - public void setFilter(Filter filter) - { - if (filter != this.filter) - { - for (int i = 0; i < unpackedArgs.length; i++) - { - filteredArgs[i] = null; - } - } - this.filter = filter; - } - - } - - public String toString() - { - StringBuffer sb = new StringBuffer(); - sb.append("Resource: \"").append(resource); - sb.append("\" Id: \"").append(id).append("\""); - sb.append(" Arguments: ").append(arguments.getArguments().length).append(" normal, ") - .append(extraArgs.getArguments().length).append(" extra"); - sb.append(" Encoding: ").append(encoding); - sb.append(" ClassLoader: ").append(loader); - return sb.toString(); - } - -} diff --git a/extern/spongycastle/core/src/main/jdk1.3/org/spongycastle/i18n/MissingEntryException.java b/extern/spongycastle/core/src/main/jdk1.3/org/spongycastle/i18n/MissingEntryException.java deleted file mode 100644 index 582b9ab9b..000000000 --- a/extern/spongycastle/core/src/main/jdk1.3/org/spongycastle/i18n/MissingEntryException.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.spongycastle.i18n; - -import java.net.URL; -import java.net.URLClassLoader; -import java.util.Locale; - -public class MissingEntryException - extends RuntimeException -{ - - protected final String resource; - protected final String key; - protected final ClassLoader loader; - protected final Locale locale; - - private Throwable cause; - private String debugMsg; - - public MissingEntryException(String message, String resource, String key, Locale locale, ClassLoader loader) - { - super(message); - this.resource = resource; - this.key = key; - this.locale = locale; - this.loader = loader; - } - - public MissingEntryException(String message, Throwable cause, String resource, String key, Locale locale, ClassLoader loader) - { - super(message); - this.cause = cause; - this.resource = resource; - this.key = key; - this.locale = locale; - this.loader = loader; - } - - public Throwable getCause() - { - return cause; - } - - public String getKey() - { - return key; - } - - public String getResource() - { - return resource; - } - - public ClassLoader getClassLoader() - { - return loader; - } - - public Locale getLocale() - { - return locale; - } - - public String getDebugMsg() - { - if (debugMsg == null) - { - debugMsg = "Can not find entry " + key + " in resource file " + resource + " for the locale " + locale + "."; - if (loader instanceof URLClassLoader) - { - URL[] urls = ((URLClassLoader) loader).getURLs(); - debugMsg += " The following entries in the classpath were searched: "; - for (int i = 0; i != urls.length; i++) - { - debugMsg += urls[i] + " "; - } - } - } - return debugMsg; - } - -} diff --git a/extern/spongycastle/core/src/main/jdk1.4/org/spongycastle/util/Integers.java b/extern/spongycastle/core/src/main/jdk1.4/org/spongycastle/util/Integers.java deleted file mode 100644 index bf6b5e345..000000000 --- a/extern/spongycastle/core/src/main/jdk1.4/org/spongycastle/util/Integers.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.spongycastle.util; - -public class Integers -{ - public static int rotateLeft(int i, int distance) - { - return (i << distance) ^ (i >>> -distance); - } - - public static int rotateRight(int i, int distance) - { - return (i >>> distance) ^ (i << -distance); - } - - public static Integer valueOf(int value) - { - return new Integer(value); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.4/org/spongycastle/util/Shorts.java b/extern/spongycastle/core/src/main/jdk1.4/org/spongycastle/util/Shorts.java deleted file mode 100644 index 66a992f77..000000000 --- a/extern/spongycastle/core/src/main/jdk1.4/org/spongycastle/util/Shorts.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.spongycastle.util; - -public class Shorts -{ - public static Short valueOf(short value) - { - return new Short(value); - } -} diff --git a/extern/spongycastle/core/src/main/jdk1.4/org/spongycastle/util/Times.java b/extern/spongycastle/core/src/main/jdk1.4/org/spongycastle/util/Times.java deleted file mode 100644 index f88b5395c..000000000 --- a/extern/spongycastle/core/src/main/jdk1.4/org/spongycastle/util/Times.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.spongycastle.util; - -public final class Times -{ - private static long NANOS_PER_MILLI = 1000000L; - - public static long nanoTime() - { - return NANOS_PER_MILLI * System.currentTimeMillis(); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/cmp/GeneralPKIMessage.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/cmp/GeneralPKIMessage.java deleted file mode 100644 index 2f74fe551..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/cmp/GeneralPKIMessage.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.spongycastle.cert.cmp; - -import java.io.IOException; - -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.cmp.PKIBody; -import org.spongycastle.asn1.cmp.PKIHeader; -import org.spongycastle.asn1.cmp.PKIMessage; -import org.spongycastle.cert.CertIOException; - -/** - * General wrapper for a generic PKIMessage - */ -public class GeneralPKIMessage -{ - private PKIMessage pkiMessage; - - private static PKIMessage parseBytes(byte[] encoding) - throws IOException - { - try - { - return PKIMessage.getInstance(ASN1Primitive.fromByteArray(encoding)); - } - catch (ClassCastException e) - { - throw new CertIOException("malformed data: " + e.getMessage(), e); - } - catch (IllegalArgumentException e) - { - throw new CertIOException("malformed data: " + e.getMessage(), e); - } - } - - /** - * Create a PKIMessage from the passed in bytes. - * - * @param encoding BER/DER encoding of the PKIMessage - * @throws IOException in the event of corrupted data, or an incorrect structure. - */ - public GeneralPKIMessage(byte[] encoding) - throws IOException - { - this(parseBytes(encoding)); - } - - /** - * Wrap a PKIMessage ASN.1 structure. - * - * @param pkiMessage base PKI message. - */ - public GeneralPKIMessage(PKIMessage pkiMessage) - { - this.pkiMessage = pkiMessage; - } - - public PKIHeader getHeader() - { - return pkiMessage.getHeader(); - } - - public PKIBody getBody() - { - return pkiMessage.getBody(); - } - - /** - * Return true if this message has protection bits on it. A return value of true - * indicates the message can be used to construct a ProtectedPKIMessage. - * - * @return true if message has protection, false otherwise. - */ - public boolean hasProtection() - { - return pkiMessage.getHeader().getProtectionAlg() != null; - } - - public PKIMessage toASN1Structure() - { - return pkiMessage; - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/CertificateRequestMessage.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/CertificateRequestMessage.java deleted file mode 100644 index 6f582812b..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/CertificateRequestMessage.java +++ /dev/null @@ -1,309 +0,0 @@ -package org.spongycastle.cert.crmf; - -import java.io.IOException; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.DERUTF8String; -import org.spongycastle.asn1.crmf.AttributeTypeAndValue; -import org.spongycastle.asn1.crmf.CRMFObjectIdentifiers; -import org.spongycastle.asn1.crmf.CertReqMsg; -import org.spongycastle.asn1.crmf.CertTemplate; -import org.spongycastle.asn1.crmf.Controls; -import org.spongycastle.asn1.crmf.PKIArchiveOptions; -import org.spongycastle.asn1.crmf.PKMACValue; -import org.spongycastle.asn1.crmf.POPOSigningKey; -import org.spongycastle.asn1.crmf.ProofOfPossession; -import org.spongycastle.cert.CertIOException; -import org.spongycastle.operator.ContentVerifier; -import org.spongycastle.operator.ContentVerifierProvider; -import org.spongycastle.operator.OperatorCreationException; - -/** - * Carrier for a CRMF CertReqMsg. - */ -public class CertificateRequestMessage -{ - public static final int popRaVerified = ProofOfPossession.TYPE_RA_VERIFIED; - public static final int popSigningKey = ProofOfPossession.TYPE_SIGNING_KEY; - public static final int popKeyEncipherment = ProofOfPossession.TYPE_KEY_ENCIPHERMENT; - public static final int popKeyAgreement = ProofOfPossession.TYPE_KEY_AGREEMENT; - - private CertReqMsg certReqMsg; - private Controls controls; - - private static CertReqMsg parseBytes(byte[] encoding) - throws IOException - { - try - { - return CertReqMsg.getInstance(ASN1Primitive.fromByteArray(encoding)); - } - catch (ClassCastException e) - { - throw new CertIOException("malformed data: " + e.getMessage(), e); - } - catch (IllegalArgumentException e) - { - throw new CertIOException("malformed data: " + e.getMessage(), e); - } - } - - /** - * Create a CertificateRequestMessage from the passed in bytes. - * - * @param certReqMsg BER/DER encoding of the CertReqMsg structure. - * @throws IOException in the event of corrupted data, or an incorrect structure. - */ - public CertificateRequestMessage(byte[] certReqMsg) - throws IOException - { - this(parseBytes(certReqMsg)); - } - - public CertificateRequestMessage(CertReqMsg certReqMsg) - { - this.certReqMsg = certReqMsg; - this.controls = certReqMsg.getCertReq().getControls(); - } - - /** - * Return the underlying ASN.1 object defining this CertificateRequestMessage object. - * - * @return a CertReqMsg. - */ - public CertReqMsg toASN1Structure() - { - return certReqMsg; - } - - /** - * Return the certificate template contained in this message. - * - * @return a CertTemplate structure. - */ - public CertTemplate getCertTemplate() - { - return this.certReqMsg.getCertReq().getCertTemplate(); - } - - /** - * Return whether or not this request has control values associated with it. - * - * @return true if there are control values present, false otherwise. - */ - public boolean hasControls() - { - return controls != null; - } - - /** - * Return whether or not this request has a specific type of control value. - * - * @param type the type OID for the control value we are checking for. - * @return true if a control value of type is present, false otherwise. - */ - public boolean hasControl(ASN1ObjectIdentifier type) - { - return findControl(type) != null; - } - - /** - * Return a control value of the specified type. - * - * @param type the type OID for the control value we are checking for. - * @return the control value if present, null otherwise. - */ - public Control getControl(ASN1ObjectIdentifier type) - { - AttributeTypeAndValue found = findControl(type); - - if (found != null) - { - if (found.getType().equals(CRMFObjectIdentifiers.id_regCtrl_pkiArchiveOptions)) - { - return new PKIArchiveControl(PKIArchiveOptions.getInstance(found.getValue())); - } - if (found.getType().equals(CRMFObjectIdentifiers.id_regCtrl_regToken)) - { - return new RegTokenControl(DERUTF8String.getInstance(found.getValue())); - } - if (found.getType().equals(CRMFObjectIdentifiers.id_regCtrl_authenticator)) - { - return new AuthenticatorControl(DERUTF8String.getInstance(found.getValue())); - } - } - - return null; - } - - private AttributeTypeAndValue findControl(ASN1ObjectIdentifier type) - { - if (controls == null) - { - return null; - } - - AttributeTypeAndValue[] tAndVs = controls.toAttributeTypeAndValueArray(); - AttributeTypeAndValue found = null; - - for (int i = 0; i != tAndVs.length; i++) - { - if (tAndVs[i].getType().equals(type)) - { - found = tAndVs[i]; - break; - } - } - - return found; - } - - /** - * Return whether or not this request message has a proof-of-possession field in it. - * - * @return true if proof-of-possession is present, false otherwise. - */ - public boolean hasProofOfPossession() - { - return this.certReqMsg.getPopo() != null; - } - - /** - * Return the type of the proof-of-possession this request message provides. - * - * @return one of: popRaVerified, popSigningKey, popKeyEncipherment, popKeyAgreement - */ - public int getProofOfPossessionType() - { - return this.certReqMsg.getPopo().getType(); - } - - /** - * Return whether or not the proof-of-possession (POP) is of the type popSigningKey and - * it has a public key MAC associated with it. - * - * @return true if POP is popSigningKey and a PKMAC is present, false otherwise. - */ - public boolean hasSigningKeyProofOfPossessionWithPKMAC() - { - ProofOfPossession pop = certReqMsg.getPopo(); - - if (pop.getType() == popSigningKey) - { - POPOSigningKey popoSign = POPOSigningKey.getInstance(pop.getObject()); - - return popoSign.getPoposkInput().getPublicKeyMAC() != null; - } - - return false; - } - - /** - * Return whether or not a signing key proof-of-possession (POP) is valid. - * - * @param verifierProvider a provider that can produce content verifiers for the signature contained in this POP. - * @return true if the POP is valid, false otherwise. - * @throws CRMFException if there is a problem in verification or content verifier creation. - * @throws IllegalStateException if POP not appropriate. - */ - public boolean isValidSigningKeyPOP(ContentVerifierProvider verifierProvider) - throws CRMFException, IllegalStateException - { - ProofOfPossession pop = certReqMsg.getPopo(); - - if (pop.getType() == popSigningKey) - { - POPOSigningKey popoSign = POPOSigningKey.getInstance(pop.getObject()); - - if (popoSign.getPoposkInput() != null && popoSign.getPoposkInput().getPublicKeyMAC() != null) - { - throw new IllegalStateException("verification requires password check"); - } - - return verifySignature(verifierProvider, popoSign); - } - else - { - throw new IllegalStateException("not Signing Key type of proof of possession"); - } - } - - /** - * Return whether or not a signing key proof-of-possession (POP), with an associated PKMAC, is valid. - * - * @param verifierProvider a provider that can produce content verifiers for the signature contained in this POP. - * @param macBuilder a suitable PKMACBuilder to create the MAC verifier. - * @param password the password used to key the MAC calculation. - * @return true if the POP is valid, false otherwise. - * @throws CRMFException if there is a problem in verification or content verifier creation. - * @throws IllegalStateException if POP not appropriate. - */ - public boolean isValidSigningKeyPOP(ContentVerifierProvider verifierProvider, PKMACBuilder macBuilder, char[] password) - throws CRMFException, IllegalStateException - { - ProofOfPossession pop = certReqMsg.getPopo(); - - if (pop.getType() == popSigningKey) - { - POPOSigningKey popoSign = POPOSigningKey.getInstance(pop.getObject()); - - if (popoSign.getPoposkInput() == null || popoSign.getPoposkInput().getSender() != null) - { - throw new IllegalStateException("no PKMAC present in proof of possession"); - } - - PKMACValue pkMAC = popoSign.getPoposkInput().getPublicKeyMAC(); - PKMACValueVerifier macVerifier = new PKMACValueVerifier(macBuilder); - - if (macVerifier.isValid(pkMAC, password, this.getCertTemplate().getPublicKey())) - { - return verifySignature(verifierProvider, popoSign); - } - - return false; - } - else - { - throw new IllegalStateException("not Signing Key type of proof of possession"); - } - } - - private boolean verifySignature(ContentVerifierProvider verifierProvider, POPOSigningKey popoSign) - throws CRMFException - { - ContentVerifier verifier; - - try - { - verifier = verifierProvider.get(popoSign.getAlgorithmIdentifier()); - } - catch (OperatorCreationException e) - { - throw new CRMFException("unable to create verifier: " + e.getMessage(), e); - } - - if (popoSign.getPoposkInput() != null) - { - CRMFUtil.derEncodeToStream(popoSign.getPoposkInput(), verifier.getOutputStream()); - } - else - { - CRMFUtil.derEncodeToStream(certReqMsg.getCertReq(), verifier.getOutputStream()); - } - - return verifier.verify(popoSign.getSignature().getBytes()); - } - - /** - * Return the ASN.1 encoding of the certReqMsg we wrap. - * - * @return a byte array containing the binary encoding of the certReqMsg. - * @throws IOException if there is an exception creating the encoding. - */ - public byte[] getEncoded() - throws IOException - { - return certReqMsg.getEncoded(); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/FixedLengthMGF1Padder.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/FixedLengthMGF1Padder.java deleted file mode 100644 index cfb33d62e..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/FixedLengthMGF1Padder.java +++ /dev/null @@ -1,120 +0,0 @@ -package org.spongycastle.cert.crmf; - -import java.security.SecureRandom; - -import org.spongycastle.crypto.Digest; -import org.spongycastle.crypto.digests.SHA1Digest; -import org.spongycastle.crypto.generators.MGF1BytesGenerator; -import org.spongycastle.crypto.params.MGFParameters; - -/** - * An encrypted value padder that uses MGF1 as the basis of the padding. - */ -public class FixedLengthMGF1Padder - implements EncryptedValuePadder -{ - private int length; - private SecureRandom random; - private Digest dig = new SHA1Digest(); - - /** - * Create a padder to so that padded output will always be at least - * length bytes long. - * - * @param length fixed length for padded output. - */ - public FixedLengthMGF1Padder(int length) - { - this(length, null); - } - - /** - * Create a padder to so that padded output will always be at least - * length bytes long, using the passed in source of randomness to - * provide the random material for the padder. - * - * @param length fixed length for padded output. - * @param random a source of randomness. - */ - public FixedLengthMGF1Padder(int length, SecureRandom random) - { - this.length = length; - this.random = random; - } - - public byte[] getPaddedData(byte[] data) - { - byte[] bytes = new byte[length]; - byte[] seed = new byte[dig.getDigestSize()]; - byte[] mask = new byte[length - dig.getDigestSize()]; - - if (random == null) - { - random = new SecureRandom(); - } - - random.nextBytes(seed); - - MGF1BytesGenerator maskGen = new MGF1BytesGenerator(dig); - - maskGen.init(new MGFParameters(seed)); - - maskGen.generateBytes(mask, 0, mask.length); - - System.arraycopy(seed, 0, bytes, 0, seed.length); - System.arraycopy(data, 0, bytes, seed.length, data.length); - - for (int i = seed.length + data.length + 1; i != bytes.length; i++) - { - bytes[i] = (byte)(1 + Math.abs(random.nextInt()) % 254); - } - - for (int i = 0; i != mask.length; i++) - { - bytes[i + seed.length] ^= mask[i]; - } - - return bytes; - } - - public byte[] getUnpaddedData(byte[] paddedData) - { - byte[] seed = new byte[dig.getDigestSize()]; - byte[] mask = new byte[length - dig.getDigestSize()]; - - System.arraycopy(paddedData, 0, seed, 0, seed.length); - - MGF1BytesGenerator maskGen = new MGF1BytesGenerator(dig); - - maskGen.init(new MGFParameters(seed)); - - maskGen.generateBytes(mask, 0, mask.length); - - for (int i = 0; i != mask.length; i++) - { - paddedData[i + seed.length] ^= mask[i]; - } - - int end = 0; - - for (int i = paddedData.length - 1; i != seed.length; i--) - { - if (paddedData[i] == 0) - { - end = i; - break; - } - } - - if (end == 0) - { - throw new IllegalStateException("bad padding in encoding"); - } - - byte[] data = new byte[end - seed.length]; - - System.arraycopy(paddedData, seed.length, data, 0, data.length); - - return data; - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/bc/BcFixedLengthMGF1Padder.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/bc/BcFixedLengthMGF1Padder.java deleted file mode 100644 index eec071e14..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/bc/BcFixedLengthMGF1Padder.java +++ /dev/null @@ -1,134 +0,0 @@ -package org.spongycastle.cert.crmf.bc; - -import java.security.SecureRandom; - -import org.spongycastle.cert.crmf.EncryptedValuePadder; -import org.spongycastle.crypto.Digest; -import org.spongycastle.crypto.digests.SHA1Digest; -import org.spongycastle.crypto.generators.MGF1BytesGenerator; -import org.spongycastle.crypto.params.MGFParameters; - -/** - * An encrypted value padder that uses MGF1 as the basis of the padding. - */ -public class BcFixedLengthMGF1Padder - implements EncryptedValuePadder -{ - private int length; - private SecureRandom random; - private Digest dig = new SHA1Digest(); - - /** - * Create a padder to so that padded output will always be at least - * length bytes long. - * - * @param length fixed length for padded output. - */ - public BcFixedLengthMGF1Padder(int length) - { - this(length, null); - } - - /** - * Create a padder to so that padded output will always be at least - * length bytes long, using the passed in source of randomness to - * provide the random material for the padder. - * - * @param length fixed length for padded output. - * @param random a source of randomness. - */ - public BcFixedLengthMGF1Padder(int length, SecureRandom random) - { - this.length = length; - this.random = random; - } - - public byte[] getPaddedData(byte[] data) - { - byte[] bytes = new byte[length]; - byte[] seed = new byte[dig.getDigestSize()]; - byte[] mask = new byte[length - dig.getDigestSize()]; - - if (random == null) - { - random = new SecureRandom(); - } - - random.nextBytes(seed); - - MGF1BytesGenerator maskGen = new MGF1BytesGenerator(dig); - - maskGen.init(new MGFParameters(seed)); - - maskGen.generateBytes(mask, 0, mask.length); - - System.arraycopy(seed, 0, bytes, 0, seed.length); - System.arraycopy(data, 0, bytes, seed.length, data.length); - - for (int i = seed.length + data.length + 1; i != bytes.length; i++) - { - bytes[i] = (byte)(1 + nextByte(random)); - } - - for (int i = 0; i != mask.length; i++) - { - bytes[i + seed.length] ^= mask[i]; - } - - return bytes; - } - - public byte[] getUnpaddedData(byte[] paddedData) - { - byte[] seed = new byte[dig.getDigestSize()]; - byte[] mask = new byte[length - dig.getDigestSize()]; - - System.arraycopy(paddedData, 0, seed, 0, seed.length); - - MGF1BytesGenerator maskGen = new MGF1BytesGenerator(dig); - - maskGen.init(new MGFParameters(seed)); - - maskGen.generateBytes(mask, 0, mask.length); - - for (int i = 0; i != mask.length; i++) - { - paddedData[i + seed.length] ^= mask[i]; - } - - int end = 0; - - for (int i = paddedData.length - 1; i != seed.length; i--) - { - if (paddedData[i] == 0) - { - end = i; - break; - } - } - - if (end == 0) - { - throw new IllegalStateException("bad padding in encoding"); - } - - byte[] data = new byte[end - seed.length]; - - System.arraycopy(paddedData, seed.length, data, 0, data.length); - - return data; - } - - private int nextByte(SecureRandom random) - { - int bits, val; - do - { - bits = random.nextInt() & 0x7fffffff; - val = bits % 255; - } - while (bits - val + 254 < 0); - - return val; - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/jcajce/CRMFHelper.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/jcajce/CRMFHelper.java deleted file mode 100644 index afed75903..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/jcajce/CRMFHelper.java +++ /dev/null @@ -1,485 +0,0 @@ -package org.spongycastle.cert.crmf.jcajce; - -import java.io.IOException; -import java.security.AlgorithmParameterGenerator; -import java.security.AlgorithmParameters; -import java.security.GeneralSecurityException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.KeyFactory; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.InvalidParameterSpecException; -import java.security.spec.X509EncodedKeySpec; -import java.util.HashMap; -import java.util.Map; - -import javax.crypto.Cipher; -import javax.crypto.KeyGenerator; -import javax.crypto.Mac; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.RC2ParameterSpec; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Null; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.DERBitString; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.iana.IANAObjectIdentifiers; -import org.spongycastle.asn1.nist.NISTObjectIdentifiers; -import org.spongycastle.asn1.oiw.OIWObjectIdentifiers; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x9.X9ObjectIdentifiers; -import org.spongycastle.cert.crmf.CRMFException; -import org.spongycastle.cms.CMSAlgorithm; -import org.spongycastle.cms.CMSEnvelopedDataGenerator; -import org.spongycastle.jcajce.util.JcaJceHelper; - -class CRMFHelper -{ - protected static final Map BASE_CIPHER_NAMES = new HashMap(); - protected static final Map CIPHER_ALG_NAMES = new HashMap(); - protected static final Map DIGEST_ALG_NAMES = new HashMap(); - protected static final Map KEY_ALG_NAMES = new HashMap(); - protected static final Map MAC_ALG_NAMES = new HashMap(); - - static - { - BASE_CIPHER_NAMES.put(PKCSObjectIdentifiers.des_EDE3_CBC, "DESEDE"); - BASE_CIPHER_NAMES.put(NISTObjectIdentifiers.id_aes128_CBC, "AES"); - BASE_CIPHER_NAMES.put(NISTObjectIdentifiers.id_aes192_CBC, "AES"); - BASE_CIPHER_NAMES.put(NISTObjectIdentifiers.id_aes256_CBC, "AES"); - - CIPHER_ALG_NAMES.put(CMSAlgorithm.DES_EDE3_CBC, "DESEDE/CBC/PKCS5Padding"); - CIPHER_ALG_NAMES.put(CMSAlgorithm.AES128_CBC, "AES/CBC/PKCS5Padding"); - CIPHER_ALG_NAMES.put(CMSAlgorithm.AES192_CBC, "AES/CBC/PKCS5Padding"); - CIPHER_ALG_NAMES.put(CMSAlgorithm.AES256_CBC, "AES/CBC/PKCS5Padding"); - CIPHER_ALG_NAMES.put(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.rsaEncryption.getId()), "RSA/ECB/PKCS1Padding"); - - DIGEST_ALG_NAMES.put(OIWObjectIdentifiers.idSHA1, "SHA1"); - DIGEST_ALG_NAMES.put(NISTObjectIdentifiers.id_sha224, "SHA224"); - DIGEST_ALG_NAMES.put(NISTObjectIdentifiers.id_sha256, "SHA256"); - DIGEST_ALG_NAMES.put(NISTObjectIdentifiers.id_sha384, "SHA384"); - DIGEST_ALG_NAMES.put(NISTObjectIdentifiers.id_sha512, "SHA512"); - - MAC_ALG_NAMES.put(IANAObjectIdentifiers.hmacSHA1, "HMACSHA1"); - MAC_ALG_NAMES.put(PKCSObjectIdentifiers.id_hmacWithSHA1, "HMACSHA1"); - MAC_ALG_NAMES.put(PKCSObjectIdentifiers.id_hmacWithSHA224, "HMACSHA224"); - MAC_ALG_NAMES.put(PKCSObjectIdentifiers.id_hmacWithSHA256, "HMACSHA256"); - MAC_ALG_NAMES.put(PKCSObjectIdentifiers.id_hmacWithSHA384, "HMACSHA384"); - MAC_ALG_NAMES.put(PKCSObjectIdentifiers.id_hmacWithSHA512, "HMACSHA512"); - - KEY_ALG_NAMES.put(PKCSObjectIdentifiers.rsaEncryption, "RSA"); - KEY_ALG_NAMES.put(X9ObjectIdentifiers.id_dsa, "DSA"); - } - - private JcaJceHelper helper; - - CRMFHelper(JcaJceHelper helper) - { - this.helper = helper; - } - - PublicKey toPublicKey(SubjectPublicKeyInfo subjectPublicKeyInfo) - throws CRMFException - { - - try - { - X509EncodedKeySpec xspec = new X509EncodedKeySpec(new DERBitString(subjectPublicKeyInfo).getBytes()); - AlgorithmIdentifier keyAlg = subjectPublicKeyInfo.getAlgorithmId(); - return createKeyFactory(keyAlg.getAlgorithm()).generatePublic(xspec); - } - catch (IOException e) - { - throw new CRMFException("invalid key: " + e.getMessage(), e); - } - catch (InvalidKeySpecException e) - { - throw new CRMFException("invalid key: " + e.getMessage(), e); - } - } - - Cipher createCipher(ASN1ObjectIdentifier algorithm) - throws CRMFException - { - try - { - String cipherName = (String)CIPHER_ALG_NAMES.get(algorithm); - - if (cipherName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createCipher(cipherName); - } - catch (NoSuchAlgorithmException e) - { - // Ignore - } - } - return helper.createCipher(algorithm.getId()); - } - catch (NoSuchPaddingException e) - { - throw new CRMFException("cannot create cipher: " + e.getMessage(), e); - } - catch (NoSuchAlgorithmException e) - { - throw new CRMFException("cannot create cipher: " + e.getMessage(), e); - } - catch (NoSuchProviderException e) - { - throw new CRMFException("cannot create cipher: " + e.getMessage(), e); - } - } - - public KeyGenerator createKeyGenerator(ASN1ObjectIdentifier algorithm) - throws CRMFException - { - try - { - String cipherName = (String)BASE_CIPHER_NAMES.get(algorithm); - - if (cipherName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createKeyGenerator(cipherName); - } - catch (NoSuchAlgorithmException e) - { - // Ignore - } - } - return helper.createKeyGenerator(algorithm.getId()); - } - catch (NoSuchAlgorithmException e) - { - throw new CRMFException("cannot create key generator: " + e.getMessage(), e); - } - catch (NoSuchProviderException e) - { - throw new CRMFException("cannot create key generator: " + e.getMessage(), e); - } - } - - Cipher createContentCipher(final Key sKey, final AlgorithmIdentifier encryptionAlgID) - throws CRMFException - { - return (Cipher)execute(new JCECallback() - { - public Object doInJCE() - throws CRMFException, InvalidAlgorithmParameterException, - InvalidKeyException, InvalidParameterSpecException, NoSuchAlgorithmException, - NoSuchPaddingException, NoSuchProviderException - { - Cipher cipher = createCipher(encryptionAlgID.getAlgorithm()); - ASN1Primitive sParams = (ASN1Primitive)encryptionAlgID.getParameters(); - String encAlg = encryptionAlgID.getAlgorithm().getId(); - - if (sParams != null && !(sParams instanceof ASN1Null)) - { - try - { - AlgorithmParameters params = createAlgorithmParameters(encryptionAlgID.getAlgorithm()); - - try - { - params.init(sParams.getEncoded(), "ASN.1"); - } - catch (IOException e) - { - throw new CRMFException("error decoding algorithm parameters.", e); - } - - cipher.init(Cipher.DECRYPT_MODE, sKey, params); - } - catch (NoSuchAlgorithmException e) - { - if (encAlg.equals(CMSEnvelopedDataGenerator.DES_EDE3_CBC) - || encAlg.equals(CMSEnvelopedDataGenerator.IDEA_CBC) - || encAlg.equals(CMSEnvelopedDataGenerator.AES128_CBC) - || encAlg.equals(CMSEnvelopedDataGenerator.AES192_CBC) - || encAlg.equals(CMSEnvelopedDataGenerator.AES256_CBC)) - { - cipher.init(Cipher.DECRYPT_MODE, sKey, new IvParameterSpec( - ASN1OctetString.getInstance(sParams).getOctets())); - } - else - { - throw e; - } - } - } - else - { - if (encAlg.equals(CMSEnvelopedDataGenerator.DES_EDE3_CBC) - || encAlg.equals(CMSEnvelopedDataGenerator.IDEA_CBC) - || encAlg.equals(CMSEnvelopedDataGenerator.CAST5_CBC)) - { - cipher.init(Cipher.DECRYPT_MODE, sKey, new IvParameterSpec(new byte[8])); - } - else - { - cipher.init(Cipher.DECRYPT_MODE, sKey); - } - } - - return cipher; - } - }); - } - - AlgorithmParameters createAlgorithmParameters(ASN1ObjectIdentifier algorithm) - throws NoSuchAlgorithmException, NoSuchProviderException - { - String algorithmName = (String)BASE_CIPHER_NAMES.get(algorithm); - - if (algorithmName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createAlgorithmParameters(algorithmName); - } - catch (NoSuchAlgorithmException e) - { - // Ignore - } - } - return helper.createAlgorithmParameters(algorithm.getId()); - } - - KeyFactory createKeyFactory(ASN1ObjectIdentifier algorithm) - throws CRMFException - { - try - { - String algName = (String)KEY_ALG_NAMES.get(algorithm); - - if (algName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createKeyFactory(algName); - } - catch (NoSuchAlgorithmException e) - { - // Ignore - } - } - return helper.createKeyFactory(algorithm.getId()); - } - catch (NoSuchProviderException e) - { - throw new CRMFException("cannot create cipher: " + e.getMessage(), e); - } - catch (NoSuchAlgorithmException e) - { - throw new CRMFException("cannot create cipher: " + e.getMessage(), e); - } - } - - MessageDigest createDigest(ASN1ObjectIdentifier algorithm) - throws CRMFException - { - try - { - String digestName = (String)DIGEST_ALG_NAMES.get(algorithm); - - if (digestName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createDigest(digestName); - } - catch (NoSuchAlgorithmException e) - { - // Ignore - } - } - return helper.createDigest(algorithm.getId()); - } - catch (NoSuchAlgorithmException e) - { - throw new CRMFException("cannot create cipher: " + e.getMessage(), e); - } - catch (NoSuchProviderException e) - { - throw new CRMFException("cannot create cipher: " + e.getMessage(), e); - } - } - - Mac createMac(ASN1ObjectIdentifier algorithm) - throws CRMFException - { - try - { - String macName = (String)MAC_ALG_NAMES.get(algorithm); - - if (macName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createMac(macName); - } - catch (NoSuchAlgorithmException e) - { - // Ignore - } - } - return helper.createMac(algorithm.getId()); - } - catch (NoSuchProviderException e) - { - throw new CRMFException("cannot create mac: " + e.getMessage(), e); - } - catch (NoSuchAlgorithmException e) - { - throw new CRMFException("cannot create mac: " + e.getMessage(), e); - } - } - - AlgorithmParameterGenerator createAlgorithmParameterGenerator(ASN1ObjectIdentifier algorithm) - throws GeneralSecurityException - { - String algorithmName = (String)BASE_CIPHER_NAMES.get(algorithm); - - try - { - if (algorithmName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createAlgorithmParameterGenerator(algorithmName); - } - catch (NoSuchAlgorithmException e) - { - // Ignore - } - } - return helper.createAlgorithmParameterGenerator(algorithm.getId()); - } - catch (NoSuchAlgorithmException e) - { - throw new GeneralSecurityException(e.toString()); - } - catch (NoSuchProviderException e) - { - throw new GeneralSecurityException(e.toString()); - } - } - - AlgorithmParameters generateParameters(ASN1ObjectIdentifier encryptionOID, SecretKey encKey, SecureRandom rand) - throws CRMFException - { - try - { - AlgorithmParameterGenerator pGen = createAlgorithmParameterGenerator(encryptionOID); - - if (encryptionOID.equals(CMSEnvelopedDataGenerator.RC2_CBC)) - { - byte[] iv = new byte[8]; - - rand.nextBytes(iv); - - try - { - pGen.init(new RC2ParameterSpec(encKey.getEncoded().length * 8, iv), rand); - } - catch (InvalidAlgorithmParameterException e) - { - throw new CRMFException("parameters generation error: " + e, e); - } - } - - return pGen.generateParameters(); - } - catch (GeneralSecurityException e) - { - throw new CRMFException("exception creating algorithm parameter generator: " + e, e); - } - } - - AlgorithmIdentifier getAlgorithmIdentifier(ASN1ObjectIdentifier encryptionOID, AlgorithmParameters params) - throws CRMFException - { - ASN1Encodable asn1Params; - if (params != null) - { - try - { - asn1Params = ASN1Primitive.fromByteArray(params.getEncoded("ASN.1")); - } - catch (IOException e) - { - throw new CRMFException("cannot encode parameters: " + e.getMessage(), e); - } - } - else - { - asn1Params = DERNull.INSTANCE; - } - - return new AlgorithmIdentifier( - encryptionOID, - asn1Params); - } - - static Object execute(JCECallback callback) throws CRMFException - { - try - { - return callback.doInJCE(); - } - catch (NoSuchAlgorithmException e) - { - throw new CRMFException("can't find algorithm.", e); - } - catch (InvalidKeyException e) - { - throw new CRMFException("key invalid in message.", e); - } - catch (NoSuchProviderException e) - { - throw new CRMFException("can't find provider.", e); - } - catch (NoSuchPaddingException e) - { - throw new CRMFException("required padding not supported.", e); - } - catch (InvalidAlgorithmParameterException e) - { - throw new CRMFException("algorithm parameters invalid.", e); - } - catch (InvalidParameterSpecException e) - { - throw new CRMFException("MAC algorithm parameter spec invalid.", e); - } - } - - static interface JCECallback - { - Object doInJCE() - throws CRMFException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidParameterSpecException, - NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException; - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/jcajce/JceAsymmetricValueDecryptorGenerator.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/jcajce/JceAsymmetricValueDecryptorGenerator.java deleted file mode 100644 index 0cf875090..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/jcajce/JceAsymmetricValueDecryptorGenerator.java +++ /dev/null @@ -1,120 +0,0 @@ -package org.spongycastle.cert.crmf.jcajce; - -import java.io.InputStream; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.ProviderException; -import java.security.NoSuchAlgorithmException; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.CipherInputStream; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.spec.SecretKeySpec; - -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.cert.crmf.CRMFException; -import org.spongycastle.cert.crmf.ValueDecryptorGenerator; -import org.spongycastle.jcajce.util.DefaultJcaJceHelper; -import org.spongycastle.jcajce.util.NamedJcaJceHelper; -import org.spongycastle.jcajce.util.ProviderJcaJceHelper; -import org.spongycastle.operator.InputDecryptor; - -public class JceAsymmetricValueDecryptorGenerator - implements ValueDecryptorGenerator -{ - private PrivateKey recipientKey; - private CRMFHelper helper = new CRMFHelper(new DefaultJcaJceHelper()); - - public JceAsymmetricValueDecryptorGenerator(PrivateKey recipientKey) - { - this.recipientKey = recipientKey; - } - - public JceAsymmetricValueDecryptorGenerator setProvider(Provider provider) - { - this.helper = new CRMFHelper(new ProviderJcaJceHelper(provider)); - - return this; - } - - public JceAsymmetricValueDecryptorGenerator setProvider(String providerName) - { - this.helper = new CRMFHelper(new NamedJcaJceHelper(providerName)); - - return this; - } - - private Key extractSecretKey(AlgorithmIdentifier keyEncryptionAlgorithm, AlgorithmIdentifier contentEncryptionAlgorithm, byte[] encryptedContentEncryptionKey) - throws CRMFException - { - try - { - Key sKey = null; - - Cipher keyCipher = helper.createCipher(keyEncryptionAlgorithm.getAlgorithm()); - - try - { - keyCipher.init(Cipher.UNWRAP_MODE, recipientKey); - sKey = keyCipher.unwrap(encryptedContentEncryptionKey, contentEncryptionAlgorithm.getAlgorithm().getId(), Cipher.SECRET_KEY); - } - catch (NoSuchAlgorithmException e) - { - } - catch (IllegalStateException e) - { - } - catch (UnsupportedOperationException e) - { - } - catch (ProviderException e) - { - } - - // some providers do not support UNWRAP (this appears to be only for asymmetric algorithms) - if (sKey == null) - { - keyCipher.init(Cipher.DECRYPT_MODE, recipientKey); - sKey = new SecretKeySpec(keyCipher.doFinal(encryptedContentEncryptionKey), contentEncryptionAlgorithm.getAlgorithm().getId()); - } - - return sKey; - } - catch (InvalidKeyException e) - { - throw new CRMFException("key invalid in message.", e); - } - catch (IllegalBlockSizeException e) - { - throw new CRMFException("illegal blocksize in message.", e); - } - catch (BadPaddingException e) - { - throw new CRMFException("bad padding in message.", e); - } - } - - public InputDecryptor getValueDecryptor(AlgorithmIdentifier keyEncryptionAlgorithm, final AlgorithmIdentifier contentEncryptionAlgorithm, byte[] encryptedContentEncryptionKey) - throws CRMFException - { - Key secretKey = extractSecretKey(keyEncryptionAlgorithm, contentEncryptionAlgorithm, encryptedContentEncryptionKey); - - final Cipher dataCipher = helper.createContentCipher(secretKey, contentEncryptionAlgorithm); - - return new InputDecryptor() - { - public AlgorithmIdentifier getAlgorithmIdentifier() - { - return contentEncryptionAlgorithm; - } - - public InputStream getInputStream(InputStream dataIn) - { - return new CipherInputStream(dataIn, dataCipher); - } - }; - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/jcajce/JceCRMFEncryptorBuilder.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/jcajce/JceCRMFEncryptorBuilder.java deleted file mode 100644 index 5be72f2a8..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/jcajce/JceCRMFEncryptorBuilder.java +++ /dev/null @@ -1,140 +0,0 @@ -package org.spongycastle.cert.crmf.jcajce; - -import java.io.OutputStream; -import java.security.AlgorithmParameters; -import java.security.GeneralSecurityException; -import java.security.Provider; -import java.security.SecureRandom; -import java.security.InvalidKeyException; - -import javax.crypto.Cipher; -import javax.crypto.CipherOutputStream; -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.cert.crmf.CRMFException; -import org.spongycastle.jcajce.util.DefaultJcaJceHelper; -import org.spongycastle.jcajce.util.NamedJcaJceHelper; -import org.spongycastle.jcajce.util.ProviderJcaJceHelper; -import org.spongycastle.operator.GenericKey; -import org.spongycastle.operator.OutputEncryptor; - -public class JceCRMFEncryptorBuilder -{ - private ASN1ObjectIdentifier encryptionOID; - private int keySize; - - private CRMFHelper helper = new CRMFHelper(new DefaultJcaJceHelper()); - private SecureRandom random; - - public JceCRMFEncryptorBuilder(ASN1ObjectIdentifier encryptionOID) - { - this(encryptionOID, -1); - } - - public JceCRMFEncryptorBuilder(ASN1ObjectIdentifier encryptionOID, int keySize) - { - this.encryptionOID = encryptionOID; - this.keySize = keySize; - } - - public JceCRMFEncryptorBuilder setProvider(Provider provider) - { - this.helper = new CRMFHelper(new ProviderJcaJceHelper(provider)); - - return this; - } - - public JceCRMFEncryptorBuilder setProvider(String providerName) - { - this.helper = new CRMFHelper(new NamedJcaJceHelper(providerName)); - - return this; - } - - public JceCRMFEncryptorBuilder setSecureRandom(SecureRandom random) - { - this.random = random; - - return this; - } - - public OutputEncryptor build() - throws CRMFException - { - return new CRMFOutputEncryptor(encryptionOID, keySize, random); - } - - private class CRMFOutputEncryptor - implements OutputEncryptor - { - private SecretKey encKey; - private AlgorithmIdentifier algorithmIdentifier; - private Cipher cipher; - - CRMFOutputEncryptor(ASN1ObjectIdentifier encryptionOID, int keySize, SecureRandom random) - throws CRMFException - { - KeyGenerator keyGen = helper.createKeyGenerator(encryptionOID); - - if (random == null) - { - random = new SecureRandom(); - } - - if (keySize < 0) - { - keyGen.init(random); - } - else - { - keyGen.init(keySize, random); - } - - cipher = helper.createCipher(encryptionOID); - encKey = keyGen.generateKey(); - AlgorithmParameters params = helper.generateParameters(encryptionOID, encKey, random); - - try - { - cipher.init(Cipher.ENCRYPT_MODE, encKey, params, random); - } - catch (InvalidKeyException e) - { - throw new CRMFException("unable to initialize cipher: " + e.getMessage(), e); - } - catch (GeneralSecurityException e) - { - throw new CRMFException("unable to initialize cipher: " + e.getMessage(), e); - } - - // - // If params are null we try and second guess on them as some providers don't provide - // algorithm parameter generation explicity but instead generate them under the hood. - // - if (params == null) - { - params = cipher.getParameters(); - } - - algorithmIdentifier = helper.getAlgorithmIdentifier(encryptionOID, params); - } - - public AlgorithmIdentifier getAlgorithmIdentifier() - { - return algorithmIdentifier; - } - - public OutputStream getOutputStream(OutputStream dOut) - { - return new CipherOutputStream(dOut, cipher); - } - - public GenericKey getKey() - { - return new GenericKey(encKey); - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/jcajce/JcePKMACValuesCalculator.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/jcajce/JcePKMACValuesCalculator.java deleted file mode 100644 index 6c5937096..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/crmf/jcajce/JcePKMACValuesCalculator.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.spongycastle.cert.crmf.jcajce; - -import java.security.MessageDigest; -import java.security.Provider; -import java.security.InvalidKeyException; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.cert.crmf.CRMFException; -import org.spongycastle.cert.crmf.PKMACValuesCalculator; -import org.spongycastle.jcajce.util.DefaultJcaJceHelper; -import org.spongycastle.jcajce.util.NamedJcaJceHelper; -import org.spongycastle.jcajce.util.ProviderJcaJceHelper; - -public class JcePKMACValuesCalculator - implements PKMACValuesCalculator -{ - private MessageDigest digest; - private Mac mac; - private CRMFHelper helper; - - public JcePKMACValuesCalculator() - { - this.helper = new CRMFHelper(new DefaultJcaJceHelper()); - } - - public JcePKMACValuesCalculator setProvider(Provider provider) - { - this.helper = new CRMFHelper(new ProviderJcaJceHelper(provider)); - - return this; - } - - public JcePKMACValuesCalculator setProvider(String providerName) - { - this.helper = new CRMFHelper(new NamedJcaJceHelper(providerName)); - - return this; - } - - public void setup(AlgorithmIdentifier digAlg, AlgorithmIdentifier macAlg) - throws CRMFException - { - digest = helper.createDigest(digAlg.getAlgorithm()); - mac = helper.createMac(macAlg.getAlgorithm()); - } - - public byte[] calculateDigest(byte[] data) - { - return digest.digest(data); - } - - public byte[] calculateMac(byte[] pwd, byte[] data) - throws CRMFException - { - try - { - mac.init(new SecretKeySpec(pwd, mac.getAlgorithm())); - - return mac.doFinal(data); - } - catch (InvalidKeyException e) - { - throw new CRMFException("failure in setup: " + e.getMessage(), e); - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/jcajce/JcaCertStoreBuilder.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/jcajce/JcaCertStoreBuilder.java deleted file mode 100644 index 63b14ff7b..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/jcajce/JcaCertStoreBuilder.java +++ /dev/null @@ -1,149 +0,0 @@ -package org.spongycastle.cert.jcajce; - -import java.security.GeneralSecurityException; -import java.security.Provider; -import java.security.NoSuchProviderException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CRLException; -import java.security.cert.CertStore; -import java.security.cert.CertificateException; -import java.security.cert.CollectionCertStoreParameters; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.spongycastle.cert.X509CRLHolder; -import org.spongycastle.cert.X509CertificateHolder; -import org.spongycastle.util.Store; - -/** - * Builder to create a CertStore from certificate and CRL stores. - */ -public class JcaCertStoreBuilder -{ - private List certs = new ArrayList(); - private List crls = new ArrayList(); - private Object provider; - private JcaX509CertificateConverter certificateConverter = new JcaX509CertificateConverter(); - private JcaX509CRLConverter crlConverter = new JcaX509CRLConverter(); - - /** - * Add a store full of X509CertificateHolder objects. - * - * @param certStore a store of X509CertificateHolder objects. - */ - public JcaCertStoreBuilder addCertificates(Store certStore) - { - certs.addAll(certStore.getMatches(null)); - - return this; - } - - /** - * Add a single certificate. - * - * @param cert the X509 certificate holder containing the certificate. - */ - public JcaCertStoreBuilder addCertificate(X509CertificateHolder cert) - { - certs.add(cert); - - return this; - } - - /** - * Add a store full of X509CRLHolder objects. - * @param crlStore a store of X509CRLHolder objects. - */ - public JcaCertStoreBuilder addCRLs(Store crlStore) - { - crls.addAll(crlStore.getMatches(null)); - - return this; - } - - /** - * Add a single CRL. - * - * @param crl the X509 CRL holder containing the CRL. - */ - public JcaCertStoreBuilder addCRL(X509CRLHolder crl) - { - crls.add(crl); - - return this; - } - - public JcaCertStoreBuilder setProvider(String providerName) - throws GeneralSecurityException - { - certificateConverter.setProvider(providerName); - crlConverter.setProvider(providerName); - this.provider = providerName; - - return this; - } - - public JcaCertStoreBuilder setProvider(Provider provider) - throws GeneralSecurityException - { - certificateConverter.setProvider(provider); - crlConverter.setProvider(provider); - this.provider = provider; - - return this; - } - - /** - * Build the CertStore from the current inputs. - * - * @return a CertStore. - * @throws GeneralSecurityException - */ - public CertStore build() - throws GeneralSecurityException - { - CollectionCertStoreParameters params = convertHolders(certificateConverter, crlConverter); - - try -{ - if (provider instanceof String) - { - return CertStore.getInstance("Collection", params, (String)provider); - } - - if (provider instanceof Provider) - { - return CertStore.getInstance("Collection", params, (Provider)provider); - } - - return CertStore.getInstance("Collection", params); -} -catch (NoSuchAlgorithmException e) -{ - throw new GeneralSecurityException(e.toString()); -} -catch (NoSuchProviderException e) -{ - throw new GeneralSecurityException(e.toString()); -} - } - - private CollectionCertStoreParameters convertHolders(JcaX509CertificateConverter certificateConverter, JcaX509CRLConverter crlConverter) - throws CertificateException, CRLException - { - List jcaObjs = new ArrayList(certs.size() + crls.size()); - - for (Iterator it = certs.iterator(); it.hasNext();) - { - jcaObjs.add(certificateConverter.getCertificate((X509CertificateHolder)it.next())); - } - - for (Iterator it = crls.iterator(); it.hasNext();) - { - jcaObjs.add(crlConverter.getCRL((X509CRLHolder)it.next())); - } - - return new CollectionCertStoreParameters(jcaObjs); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/path/CertPathValidationException.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/path/CertPathValidationException.java deleted file mode 100644 index d0cbf6079..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/path/CertPathValidationException.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.spongycastle.cert.path; - -public class CertPathValidationException - extends Exception -{ - private Exception cause; - - public CertPathValidationException(String msg) - { - this(msg, null); - } - - public CertPathValidationException(String msg, Exception cause) - { - super(msg); - - this.cause = cause; - } - - public Throwable getCause() - { - return cause; - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/selector/jcajce/JcaSelectorConverter.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/selector/jcajce/JcaSelectorConverter.java deleted file mode 100644 index 8bda2e465..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/selector/jcajce/JcaSelectorConverter.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.spongycastle.cert.selector.jcajce; - -import java.security.cert.X509CertSelector; - -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.cert.selector.X509CertificateHolderSelector; - -public class JcaSelectorConverter -{ - public JcaSelectorConverter() - { - - } - - public X509CertificateHolderSelector getCertificateHolderSelector(X509CertSelector certSelector) - { -try -{ - if (certSelector.getSubjectKeyIdentifier() != null) - { - return new X509CertificateHolderSelector(X500Name.getInstance(certSelector.getIssuerAsBytes()), certSelector.getSerialNumber(), ASN1OctetString.getInstance(certSelector.getSubjectKeyIdentifier()).getOctets()); - } - else - { - return new X509CertificateHolderSelector(X500Name.getInstance(certSelector.getIssuerAsBytes()), certSelector.getSerialNumber()); - } -} -catch (Exception e) -{ -throw new IllegalArgumentException("conversion failed: " + e.toString()); -} - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/selector/jcajce/JcaX509CertSelectorConverter.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/selector/jcajce/JcaX509CertSelectorConverter.java deleted file mode 100644 index 6dbcef43f..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cert/selector/jcajce/JcaX509CertSelectorConverter.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.spongycastle.cert.selector.jcajce; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.cert.X509CertSelector; - -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.cert.selector.X509CertificateHolderSelector; - -public class JcaX509CertSelectorConverter -{ - public JcaX509CertSelectorConverter() - { - } - - protected X509CertSelector doConversion(X500Name issuer, BigInteger serialNumber, byte[] subjectKeyIdentifier) - { - X509CertSelector selector = new X509CertSelector(); - - if (issuer != null) - { - try - { - selector.setIssuer(issuer.getEncoded()); - } - catch (IOException e) - { - throw new IllegalArgumentException("unable to convert issuer: " + e.getMessage()); - } - } - - if (serialNumber != null) - { - selector.setSerialNumber(serialNumber); - } - - if (subjectKeyIdentifier != null) - { - try - { - selector.setSubjectKeyIdentifier(new DEROctetString(subjectKeyIdentifier).getEncoded()); - } - catch (IOException e) - { - throw new IllegalArgumentException("unable to convert issuer: " + e.getMessage()); - } - } - - return selector; - } - - public X509CertSelector getCertSelector(X509CertificateHolderSelector holderSelector) - { - return doConversion(holderSelector.getIssuer(), holderSelector.getSerialNumber(), holderSelector.getSubjectKeyIdentifier()); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/CMSAbsentContent.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/CMSAbsentContent.java deleted file mode 100644 index e1d7e5867..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/CMSAbsentContent.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.spongycastle.cms; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.cms.CMSObjectIdentifiers; - -/** - * a class representing null or absent content. - */ -public class CMSAbsentContent - implements CMSTypedData, CMSReadable -{ - private ASN1ObjectIdentifier type; - - public CMSAbsentContent() - { - this(new ASN1ObjectIdentifier(CMSObjectIdentifiers.data.getId())); - } - - public CMSAbsentContent( - ASN1ObjectIdentifier type) - { - this.type = type; - } - - public InputStream getInputStream() - { - return null; - } - - public void write(OutputStream zOut) - throws IOException, CMSException - { - // do nothing - } - - public Object getContent() - { - return null; - } - - public ASN1ObjectIdentifier getContentType() - { - return type; - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/CMSProcessableByteArray.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/CMSProcessableByteArray.java deleted file mode 100644 index 6ac965c78..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/CMSProcessableByteArray.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.spongycastle.cms; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.cms.CMSObjectIdentifiers; -import org.spongycastle.util.Arrays; - -/** - * a holding class for a byte array of data to be processed. - */ -public class CMSProcessableByteArray - implements CMSTypedData, CMSReadable -{ - private ASN1ObjectIdentifier type; - private byte[] bytes; - - public CMSProcessableByteArray( - byte[] bytes) - { - this(new ASN1ObjectIdentifier(CMSObjectIdentifiers.data.getId()), bytes); - } - - public CMSProcessableByteArray( - ASN1ObjectIdentifier type, - byte[] bytes) - { - this.type = type; - this.bytes = bytes; - } - - public InputStream getInputStream() - { - return new ByteArrayInputStream(bytes); - } - - public void write(OutputStream zOut) - throws IOException, CMSException - { - zOut.write(bytes); - } - - public Object getContent() - { - return Arrays.clone(bytes); - } - - public ASN1ObjectIdentifier getContentType() - { - return type; - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/CMSProcessableFile.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/CMSProcessableFile.java deleted file mode 100644 index 87b7c4e94..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/CMSProcessableFile.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.spongycastle.cms; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.cms.CMSObjectIdentifiers; - -/** - * a holding class for a file of data to be processed. - */ -public class CMSProcessableFile - implements CMSTypedData, CMSReadable -{ - private static final int DEFAULT_BUF_SIZE = 32 * 1024; - - private ASN1ObjectIdentifier type; - private File file; - private byte[] buf; - - public CMSProcessableFile( - File file) - { - this(file, DEFAULT_BUF_SIZE); - } - - public CMSProcessableFile( - File file, - int bufSize) - { - this(new ASN1ObjectIdentifier(CMSObjectIdentifiers.data.getId()), file, bufSize); - } - - public CMSProcessableFile( - ASN1ObjectIdentifier type, - File file, - int bufSize) - { - this.type = type; - this.file = file; - buf = new byte[bufSize]; - } - - public InputStream getInputStream() - throws IOException, CMSException - { - return new BufferedInputStream(new FileInputStream(file), DEFAULT_BUF_SIZE); - } - - public void write(OutputStream zOut) - throws IOException, CMSException - { - FileInputStream fIn = new FileInputStream(file); - int len; - - while ((len = fIn.read(buf, 0, buf.length)) > 0) - { - zOut.write(buf, 0, len); - } - - fIn.close(); - } - - /** - * Return the file handle. - */ - public Object getContent() - { - return file; - } - - public ASN1ObjectIdentifier getContentType() - { - return type; - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/CMSTypedStream.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/CMSTypedStream.java deleted file mode 100644 index 82466af71..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/CMSTypedStream.java +++ /dev/null @@ -1,86 +0,0 @@ -package org.spongycastle.cms; - -import java.io.BufferedInputStream; -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.util.io.Streams; - -public class CMSTypedStream -{ - private static final int BUF_SIZ = 32 * 1024; - - private ASN1ObjectIdentifier _oid; - private InputStream _in; - - public CMSTypedStream( - InputStream in) - { - this(PKCSObjectIdentifiers.data.getId(), in, BUF_SIZ); - } - - public CMSTypedStream( - String oid, - InputStream in) - { - this(new ASN1ObjectIdentifier(oid), in, BUF_SIZ); - } - - public CMSTypedStream( - String oid, - InputStream in, - int bufSize) - { - this(new ASN1ObjectIdentifier(oid), in, bufSize); - } - - public CMSTypedStream( - ASN1ObjectIdentifier oid, - InputStream in) - { - this(oid, in, BUF_SIZ); - } - - public CMSTypedStream( - ASN1ObjectIdentifier oid, - InputStream in, - int bufSize) - { - _oid = oid; - _in = new FullReaderStream(new BufferedInputStream(in, bufSize)); - } - - public ASN1ObjectIdentifier getContentType() - { - return _oid; - } - - public InputStream getContentStream() - { - return _in; - } - - public void drain() - throws IOException - { - Streams.drain(_in); - _in.close(); - } - - private static class FullReaderStream extends FilterInputStream - { - FullReaderStream(InputStream in) - { - super(in); - } - - public int read(byte[] buf, int off, int len) throws IOException - { - int totalRead = Streams.readFully(super.in, buf, off, len); - return totalRead > 0 ? totalRead : -1; - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/OriginatorInfoGenerator.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/OriginatorInfoGenerator.java deleted file mode 100644 index b6cfdd0be..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/OriginatorInfoGenerator.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.spongycastle.cms; - -import java.util.ArrayList; -import java.util.List; - -import org.spongycastle.asn1.cms.OriginatorInfo; -import org.spongycastle.cert.X509CertificateHolder; -import org.spongycastle.util.Store; - -public class OriginatorInfoGenerator -{ - private List origCerts; - private List origCRLs; - - public OriginatorInfoGenerator(X509CertificateHolder origCert) - { - this.origCerts = new ArrayList(1); - this.origCRLs = null; - origCerts.add(origCert.toASN1Structure()); - } - - public OriginatorInfoGenerator(Store origCerts) - throws CMSException - { - this(origCerts, null); - } - - public OriginatorInfoGenerator(Store origCerts, Store origCRLs) - throws CMSException - { - this.origCerts = CMSUtils.getCertificatesFromStore(origCerts); - - if (origCRLs != null) - { - this.origCRLs = CMSUtils.getCRLsFromStore(origCRLs); - } - else - { - this.origCRLs = null; - } - } - - public OriginatorInformation generate() - { - if (origCRLs != null) - { - return new OriginatorInformation(new OriginatorInfo(CMSUtils.createDerSetFromList(origCerts), CMSUtils.createDerSetFromList(origCRLs))); - } - else - { - return new OriginatorInformation(new OriginatorInfo(CMSUtils.createDerSetFromList(origCerts), null)); - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/RecipientId.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/RecipientId.java deleted file mode 100644 index f2dd5dff2..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/RecipientId.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.spongycastle.cms; - -import org.spongycastle.util.Selector; - -public abstract class RecipientId - implements Selector -{ - public static final int keyTrans = 0; - public static final int kek = 1; - public static final int keyAgree = 2; - public static final int password = 3; - - private int type; - - protected RecipientId(int type) - { - this.type = type; - } - - /** - * Return the type code for this recipient ID. - * - * @return one of keyTrans, kek, keyAgree, password - */ - public int getType() - { - return type; - } - - public abstract Object clone(); -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/SignerInfoGenerator.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/SignerInfoGenerator.java deleted file mode 100644 index 47028b995..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/SignerInfoGenerator.java +++ /dev/null @@ -1,291 +0,0 @@ -package org.spongycastle.cms; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Set; -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.DERSet; -import org.spongycastle.asn1.cms.AttributeTable; -import org.spongycastle.asn1.cms.SignerIdentifier; -import org.spongycastle.asn1.cms.SignerInfo; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.cert.X509CertificateHolder; -import org.spongycastle.operator.ContentSigner; -import org.spongycastle.operator.DefaultDigestAlgorithmIdentifierFinder; -import org.spongycastle.operator.DigestAlgorithmIdentifierFinder; -import org.spongycastle.operator.DigestCalculator; -import org.spongycastle.operator.DigestCalculatorProvider; -import org.spongycastle.operator.OperatorCreationException; -import org.spongycastle.util.Arrays; -import org.spongycastle.util.io.TeeOutputStream; - -public class SignerInfoGenerator -{ - private SignerIdentifier signerIdentifier; - private CMSAttributeTableGenerator sAttrGen; - private CMSAttributeTableGenerator unsAttrGen; - private ContentSigner signer; - private DigestCalculator digester; - private DigestAlgorithmIdentifierFinder digAlgFinder = new DefaultDigestAlgorithmIdentifierFinder(); - private CMSSignatureEncryptionAlgorithmFinder sigEncAlgFinder; - - private byte[] calculatedDigest = null; - private X509CertificateHolder certHolder; - - SignerInfoGenerator( - SignerIdentifier signerIdentifier, - ContentSigner signer, - DigestCalculatorProvider digesterProvider, - CMSSignatureEncryptionAlgorithmFinder sigEncAlgFinder) - throws OperatorCreationException - { - this(signerIdentifier, signer, digesterProvider, sigEncAlgFinder, false); - } - - SignerInfoGenerator( - SignerIdentifier signerIdentifier, - ContentSigner signer, - DigestCalculatorProvider digesterProvider, - CMSSignatureEncryptionAlgorithmFinder sigEncAlgFinder, - boolean isDirectSignature) - throws OperatorCreationException - { - this.signerIdentifier = signerIdentifier; - this.signer = signer; - - if (digesterProvider != null) - { - this.digester = digesterProvider.get(digAlgFinder.find(signer.getAlgorithmIdentifier())); - } - else - { - this.digester = null; - } - - if (isDirectSignature) - { - this.sAttrGen = null; - this.unsAttrGen = null; - } - else - { - this.sAttrGen = new DefaultSignedAttributeTableGenerator(); - this.unsAttrGen = null; - } - - this.sigEncAlgFinder = sigEncAlgFinder; - } - - public SignerInfoGenerator( - SignerInfoGenerator original, - CMSAttributeTableGenerator sAttrGen, - CMSAttributeTableGenerator unsAttrGen) - { - this.signerIdentifier = original.signerIdentifier; - this.signer = original.signer; - this.digester = original.digester; - this.sigEncAlgFinder = original.sigEncAlgFinder; - this.sAttrGen = sAttrGen; - this.unsAttrGen = unsAttrGen; - } - - SignerInfoGenerator( - SignerIdentifier signerIdentifier, - ContentSigner signer, - DigestCalculatorProvider digesterProvider, - CMSSignatureEncryptionAlgorithmFinder sigEncAlgFinder, - CMSAttributeTableGenerator sAttrGen, - CMSAttributeTableGenerator unsAttrGen) - throws OperatorCreationException - { - this.signerIdentifier = signerIdentifier; - this.signer = signer; - - if (digesterProvider != null) - { - this.digester = digesterProvider.get(digAlgFinder.find(signer.getAlgorithmIdentifier())); - } - else - { - this.digester = null; - } - - this.sAttrGen = sAttrGen; - this.unsAttrGen = unsAttrGen; - this.sigEncAlgFinder = sigEncAlgFinder; - } - - public SignerIdentifier getSID() - { - return signerIdentifier; - } - - public int getGeneratedVersion() - { - return signerIdentifier.isTagged() ? 3 : 1; - } - - public boolean hasAssociatedCertificate() - { - return certHolder != null; - } - - public X509CertificateHolder getAssociatedCertificate() - { - return certHolder; - } - - public AlgorithmIdentifier getDigestAlgorithm() - { - if (digester != null) - { - return digester.getAlgorithmIdentifier(); - } - - return digAlgFinder.find(signer.getAlgorithmIdentifier()); - } - - public OutputStream getCalculatingOutputStream() - { - if (digester != null) - { - if (sAttrGen == null) - { - return new TeeOutputStream(digester.getOutputStream(), signer.getOutputStream()); - } - return digester.getOutputStream(); - } - else - { - return signer.getOutputStream(); - } - } - - public SignerInfo generate(ASN1ObjectIdentifier contentType) - throws CMSException - { - try - { - /* RFC 3852 5.4 - * The result of the message digest calculation process depends on - * whether the signedAttrs field is present. When the field is absent, - * the result is just the message digest of the content as described - * - * above. When the field is present, however, the result is the message - * digest of the complete DER encoding of the SignedAttrs value - * contained in the signedAttrs field. - */ - ASN1Set signedAttr = null; - - AlgorithmIdentifier digestAlg = null; - - if (sAttrGen != null) - { - digestAlg = digester.getAlgorithmIdentifier(); - calculatedDigest = digester.getDigest(); - Map parameters = getBaseParameters(contentType, digester.getAlgorithmIdentifier(), calculatedDigest); - AttributeTable signed = sAttrGen.getAttributes(Collections.unmodifiableMap(parameters)); - - signedAttr = getAttributeSet(signed); - - // sig must be composed from the DER encoding. - OutputStream sOut = signer.getOutputStream(); - - sOut.write(signedAttr.getEncoded(ASN1Encoding.DER)); - - sOut.close(); - } - else - { - if (digester != null) - { - digestAlg = digester.getAlgorithmIdentifier(); - calculatedDigest = digester.getDigest(); - } - else - { - digestAlg = digAlgFinder.find(signer.getAlgorithmIdentifier()); - calculatedDigest = null; - } - } - - byte[] sigBytes = signer.getSignature(); - - ASN1Set unsignedAttr = null; - if (unsAttrGen != null) - { - Map parameters = getBaseParameters(contentType, digestAlg, calculatedDigest); - parameters.put(CMSAttributeTableGenerator.SIGNATURE, Arrays.clone(sigBytes)); - - AttributeTable unsigned = unsAttrGen.getAttributes(Collections.unmodifiableMap(parameters)); - - unsignedAttr = getAttributeSet(unsigned); - } - - AlgorithmIdentifier digestEncryptionAlgorithm = sigEncAlgFinder.findEncryptionAlgorithm(signer.getAlgorithmIdentifier()); - - return new SignerInfo(signerIdentifier, digestAlg, - signedAttr, digestEncryptionAlgorithm, new DEROctetString(sigBytes), unsignedAttr); - } - catch (IOException e) - { - throw new CMSException("encoding error.", e); - } - } - - void setAssociatedCertificate(X509CertificateHolder certHolder) - { - this.certHolder = certHolder; - } - - private ASN1Set getAttributeSet( - AttributeTable attr) - { - if (attr != null) - { - return new DERSet(attr.toASN1EncodableVector()); - } - - return null; - } - - private Map getBaseParameters(ASN1ObjectIdentifier contentType, AlgorithmIdentifier digAlgId, byte[] hash) - { - Map param = new HashMap(); - - if (contentType != null) - { - param.put(CMSAttributeTableGenerator.CONTENT_TYPE, contentType); - } - - param.put(CMSAttributeTableGenerator.DIGEST_ALGORITHM_IDENTIFIER, digAlgId); - param.put(CMSAttributeTableGenerator.DIGEST, Arrays.clone(hash)); - return param; - } - - public byte[] getCalculatedDigest() - { - if (calculatedDigest != null) - { - return Arrays.clone(calculatedDigest); - } - - return null; - } - - public CMSAttributeTableGenerator getSignedAttributeTableGenerator() - { - return sAttrGen; - } - - public CMSAttributeTableGenerator getUnsignedAttributeTableGenerator() - { - return unsAttrGen; - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/EnvelopedDataHelper.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/EnvelopedDataHelper.java deleted file mode 100644 index 56f6f2f25..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/EnvelopedDataHelper.java +++ /dev/null @@ -1,671 +0,0 @@ -package org.spongycastle.cms.jcajce; - -import java.security.AlgorithmParameterGenerator; -import java.security.AlgorithmParameters; -import java.security.GeneralSecurityException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.KeyFactory; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.spec.AlgorithmParameterSpec; -import java.security.spec.InvalidParameterSpecException; -import java.util.HashMap; -import java.util.Map; - -import javax.crypto.Cipher; -import javax.crypto.KeyAgreement; -import javax.crypto.KeyGenerator; -import javax.crypto.Mac; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.RC2ParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Null; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.pkcs.RC2CBCParameter; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.cms.CMSAlgorithm; -import org.spongycastle.cms.CMSEnvelopedDataGenerator; -import org.spongycastle.cms.CMSException; -import org.spongycastle.operator.DefaultSecretKeySizeProvider; -import org.spongycastle.operator.GenericKey; -import org.spongycastle.operator.SecretKeySizeProvider; -import org.spongycastle.operator.SymmetricKeyUnwrapper; -import org.spongycastle.operator.jcajce.JceAsymmetricKeyUnwrapper; - -public class EnvelopedDataHelper -{ - protected static final SecretKeySizeProvider KEY_SIZE_PROVIDER = DefaultSecretKeySizeProvider.INSTANCE; - - protected static final Map BASE_CIPHER_NAMES = new HashMap(); - protected static final Map CIPHER_ALG_NAMES = new HashMap(); - protected static final Map MAC_ALG_NAMES = new HashMap(); - - static - { - BASE_CIPHER_NAMES.put(CMSAlgorithm.DES_CBC, "DES"); - BASE_CIPHER_NAMES.put(CMSAlgorithm.DES_EDE3_CBC, "DESEDE"); - BASE_CIPHER_NAMES.put(CMSAlgorithm.AES128_CBC, "AES"); - BASE_CIPHER_NAMES.put(CMSAlgorithm.AES192_CBC, "AES"); - BASE_CIPHER_NAMES.put(CMSAlgorithm.AES256_CBC, "AES"); - BASE_CIPHER_NAMES.put(CMSAlgorithm.RC2_CBC, "RC2"); - BASE_CIPHER_NAMES.put(CMSAlgorithm.CAST5_CBC, "CAST5"); - BASE_CIPHER_NAMES.put(CMSAlgorithm.CAMELLIA128_CBC, "Camellia"); - BASE_CIPHER_NAMES.put(CMSAlgorithm.CAMELLIA192_CBC, "Camellia"); - BASE_CIPHER_NAMES.put(CMSAlgorithm.CAMELLIA256_CBC, "Camellia"); - BASE_CIPHER_NAMES.put(CMSAlgorithm.SEED_CBC, "SEED"); - BASE_CIPHER_NAMES.put(PKCSObjectIdentifiers.rc4, "RC4"); - - CIPHER_ALG_NAMES.put(CMSAlgorithm.DES_CBC, "DES/CBC/PKCS5Padding"); - CIPHER_ALG_NAMES.put(CMSAlgorithm.RC2_CBC, "RC2/CBC/PKCS5Padding"); - CIPHER_ALG_NAMES.put(CMSAlgorithm.DES_EDE3_CBC, "DESEDE/CBC/PKCS5Padding"); - CIPHER_ALG_NAMES.put(CMSAlgorithm.AES128_CBC, "AES/CBC/PKCS5Padding"); - CIPHER_ALG_NAMES.put(CMSAlgorithm.AES192_CBC, "AES/CBC/PKCS5Padding"); - CIPHER_ALG_NAMES.put(CMSAlgorithm.AES256_CBC, "AES/CBC/PKCS5Padding"); - CIPHER_ALG_NAMES.put(PKCSObjectIdentifiers.rsaEncryption, "RSA/ECB/PKCS1Padding"); - CIPHER_ALG_NAMES.put(CMSAlgorithm.CAST5_CBC, "CAST5/CBC/PKCS5Padding"); - CIPHER_ALG_NAMES.put(CMSAlgorithm.CAMELLIA128_CBC, "Camellia/CBC/PKCS5Padding"); - CIPHER_ALG_NAMES.put(CMSAlgorithm.CAMELLIA192_CBC, "Camellia/CBC/PKCS5Padding"); - CIPHER_ALG_NAMES.put(CMSAlgorithm.CAMELLIA256_CBC, "Camellia/CBC/PKCS5Padding"); - CIPHER_ALG_NAMES.put(CMSAlgorithm.SEED_CBC, "SEED/CBC/PKCS5Padding"); - CIPHER_ALG_NAMES.put(PKCSObjectIdentifiers.rc4, "RC4"); - - MAC_ALG_NAMES.put(CMSAlgorithm.DES_EDE3_CBC, "DESEDEMac"); - MAC_ALG_NAMES.put(CMSAlgorithm.AES128_CBC, "AESMac"); - MAC_ALG_NAMES.put(CMSAlgorithm.AES192_CBC, "AESMac"); - MAC_ALG_NAMES.put(CMSAlgorithm.AES256_CBC, "AESMac"); - MAC_ALG_NAMES.put(CMSAlgorithm.RC2_CBC, "RC2Mac"); - } - - private static final short[] rc2Table = { - 0xbd, 0x56, 0xea, 0xf2, 0xa2, 0xf1, 0xac, 0x2a, 0xb0, 0x93, 0xd1, 0x9c, 0x1b, 0x33, 0xfd, 0xd0, - 0x30, 0x04, 0xb6, 0xdc, 0x7d, 0xdf, 0x32, 0x4b, 0xf7, 0xcb, 0x45, 0x9b, 0x31, 0xbb, 0x21, 0x5a, - 0x41, 0x9f, 0xe1, 0xd9, 0x4a, 0x4d, 0x9e, 0xda, 0xa0, 0x68, 0x2c, 0xc3, 0x27, 0x5f, 0x80, 0x36, - 0x3e, 0xee, 0xfb, 0x95, 0x1a, 0xfe, 0xce, 0xa8, 0x34, 0xa9, 0x13, 0xf0, 0xa6, 0x3f, 0xd8, 0x0c, - 0x78, 0x24, 0xaf, 0x23, 0x52, 0xc1, 0x67, 0x17, 0xf5, 0x66, 0x90, 0xe7, 0xe8, 0x07, 0xb8, 0x60, - 0x48, 0xe6, 0x1e, 0x53, 0xf3, 0x92, 0xa4, 0x72, 0x8c, 0x08, 0x15, 0x6e, 0x86, 0x00, 0x84, 0xfa, - 0xf4, 0x7f, 0x8a, 0x42, 0x19, 0xf6, 0xdb, 0xcd, 0x14, 0x8d, 0x50, 0x12, 0xba, 0x3c, 0x06, 0x4e, - 0xec, 0xb3, 0x35, 0x11, 0xa1, 0x88, 0x8e, 0x2b, 0x94, 0x99, 0xb7, 0x71, 0x74, 0xd3, 0xe4, 0xbf, - 0x3a, 0xde, 0x96, 0x0e, 0xbc, 0x0a, 0xed, 0x77, 0xfc, 0x37, 0x6b, 0x03, 0x79, 0x89, 0x62, 0xc6, - 0xd7, 0xc0, 0xd2, 0x7c, 0x6a, 0x8b, 0x22, 0xa3, 0x5b, 0x05, 0x5d, 0x02, 0x75, 0xd5, 0x61, 0xe3, - 0x18, 0x8f, 0x55, 0x51, 0xad, 0x1f, 0x0b, 0x5e, 0x85, 0xe5, 0xc2, 0x57, 0x63, 0xca, 0x3d, 0x6c, - 0xb4, 0xc5, 0xcc, 0x70, 0xb2, 0x91, 0x59, 0x0d, 0x47, 0x20, 0xc8, 0x4f, 0x58, 0xe0, 0x01, 0xe2, - 0x16, 0x38, 0xc4, 0x6f, 0x3b, 0x0f, 0x65, 0x46, 0xbe, 0x7e, 0x2d, 0x7b, 0x82, 0xf9, 0x40, 0xb5, - 0x1d, 0x73, 0xf8, 0xeb, 0x26, 0xc7, 0x87, 0x97, 0x25, 0x54, 0xb1, 0x28, 0xaa, 0x98, 0x9d, 0xa5, - 0x64, 0x6d, 0x7a, 0xd4, 0x10, 0x81, 0x44, 0xef, 0x49, 0xd6, 0xae, 0x2e, 0xdd, 0x76, 0x5c, 0x2f, - 0xa7, 0x1c, 0xc9, 0x09, 0x69, 0x9a, 0x83, 0xcf, 0x29, 0x39, 0xb9, 0xe9, 0x4c, 0xff, 0x43, 0xab - }; - - private static final short[] rc2Ekb = { - 0x5d, 0xbe, 0x9b, 0x8b, 0x11, 0x99, 0x6e, 0x4d, 0x59, 0xf3, 0x85, 0xa6, 0x3f, 0xb7, 0x83, 0xc5, - 0xe4, 0x73, 0x6b, 0x3a, 0x68, 0x5a, 0xc0, 0x47, 0xa0, 0x64, 0x34, 0x0c, 0xf1, 0xd0, 0x52, 0xa5, - 0xb9, 0x1e, 0x96, 0x43, 0x41, 0xd8, 0xd4, 0x2c, 0xdb, 0xf8, 0x07, 0x77, 0x2a, 0xca, 0xeb, 0xef, - 0x10, 0x1c, 0x16, 0x0d, 0x38, 0x72, 0x2f, 0x89, 0xc1, 0xf9, 0x80, 0xc4, 0x6d, 0xae, 0x30, 0x3d, - 0xce, 0x20, 0x63, 0xfe, 0xe6, 0x1a, 0xc7, 0xb8, 0x50, 0xe8, 0x24, 0x17, 0xfc, 0x25, 0x6f, 0xbb, - 0x6a, 0xa3, 0x44, 0x53, 0xd9, 0xa2, 0x01, 0xab, 0xbc, 0xb6, 0x1f, 0x98, 0xee, 0x9a, 0xa7, 0x2d, - 0x4f, 0x9e, 0x8e, 0xac, 0xe0, 0xc6, 0x49, 0x46, 0x29, 0xf4, 0x94, 0x8a, 0xaf, 0xe1, 0x5b, 0xc3, - 0xb3, 0x7b, 0x57, 0xd1, 0x7c, 0x9c, 0xed, 0x87, 0x40, 0x8c, 0xe2, 0xcb, 0x93, 0x14, 0xc9, 0x61, - 0x2e, 0xe5, 0xcc, 0xf6, 0x5e, 0xa8, 0x5c, 0xd6, 0x75, 0x8d, 0x62, 0x95, 0x58, 0x69, 0x76, 0xa1, - 0x4a, 0xb5, 0x55, 0x09, 0x78, 0x33, 0x82, 0xd7, 0xdd, 0x79, 0xf5, 0x1b, 0x0b, 0xde, 0x26, 0x21, - 0x28, 0x74, 0x04, 0x97, 0x56, 0xdf, 0x3c, 0xf0, 0x37, 0x39, 0xdc, 0xff, 0x06, 0xa4, 0xea, 0x42, - 0x08, 0xda, 0xb4, 0x71, 0xb0, 0xcf, 0x12, 0x7a, 0x4e, 0xfa, 0x6c, 0x1d, 0x84, 0x00, 0xc8, 0x7f, - 0x91, 0x45, 0xaa, 0x2b, 0xc2, 0xb1, 0x8f, 0xd5, 0xba, 0xf2, 0xad, 0x19, 0xb2, 0x67, 0x36, 0xf7, - 0x0f, 0x0a, 0x92, 0x7d, 0xe3, 0x9d, 0xe9, 0x90, 0x3e, 0x23, 0x27, 0x66, 0x13, 0xec, 0x81, 0x15, - 0xbd, 0x22, 0xbf, 0x9f, 0x7e, 0xa9, 0x51, 0x4b, 0x4c, 0xfb, 0x02, 0xd3, 0x70, 0x86, 0x31, 0xe7, - 0x3b, 0x05, 0x03, 0x54, 0x60, 0x48, 0x65, 0x18, 0xd2, 0xcd, 0x5f, 0x32, 0x88, 0x0e, 0x35, 0xfd - }; - - private JcaJceExtHelper helper; - - EnvelopedDataHelper(JcaJceExtHelper helper) - { - this.helper = helper; - } - - String getBaseCipherName(ASN1ObjectIdentifier algorithm) - { - String name = (String)BASE_CIPHER_NAMES.get(algorithm); - - if (name == null) - { - return algorithm.getId(); - } - - return name; - } - - Key getJceKey(GenericKey key) - { - if (key.getRepresentation() instanceof Key) - { - return (Key)key.getRepresentation(); - } - - if (key.getRepresentation() instanceof byte[]) - { - return new SecretKeySpec((byte[])key.getRepresentation(), "ENC"); - } - - throw new IllegalArgumentException("unknown generic key type"); - } - - public Key getJceKey(ASN1ObjectIdentifier algorithm, GenericKey key) - { - if (key.getRepresentation() instanceof Key) - { - return (Key)key.getRepresentation(); - } - - if (key.getRepresentation() instanceof byte[]) - { - return new SecretKeySpec((byte[])key.getRepresentation(), getBaseCipherName(algorithm)); - } - - throw new IllegalArgumentException("unknown generic key type"); - } - - public void keySizeCheck(AlgorithmIdentifier keyAlgorithm, Key key) - throws CMSException - { - int expectedKeySize = EnvelopedDataHelper.KEY_SIZE_PROVIDER.getKeySize(keyAlgorithm); - if (expectedKeySize > 0) - { - byte[] keyEnc = null; - - try - { - keyEnc = key.getEncoded(); - } - catch (Exception e) - { - // ignore - we're using a HSM... - } - - if (keyEnc != null) - { - if (keyEnc.length * 8 != expectedKeySize) - { - throw new CMSException("Expected key size for algorithm OID not found in recipient."); - } - } - } - } - - Cipher createCipher(ASN1ObjectIdentifier algorithm) - throws CMSException - { - try - { - String cipherName = (String)CIPHER_ALG_NAMES.get(algorithm); - - if (cipherName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createCipher(cipherName); - } - catch (NoSuchAlgorithmException e) - { - // Ignore - } - } - return helper.createCipher(algorithm.getId()); - } - catch (Exception e) - { - throw new CMSException("cannot create cipher: " + e.getMessage(), e); - } - } - - Mac createMac(ASN1ObjectIdentifier algorithm) - throws CMSException - { - try - { - String macName = (String)MAC_ALG_NAMES.get(algorithm); - - if (macName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createMac(macName); - } - catch (NoSuchAlgorithmException e) - { - // Ignore - } - } - return helper.createMac(algorithm.getId()); - } - catch (Exception e) - { - throw new CMSException("cannot create mac: " + e.getMessage(), e); - } - } - - Cipher createRFC3211Wrapper(ASN1ObjectIdentifier algorithm) - throws CMSException - { - String cipherName = (String)BASE_CIPHER_NAMES.get(algorithm); - - if (cipherName == null) - { - throw new CMSException("no name for " + algorithm); - } - - cipherName += "RFC3211Wrap"; - - try - { - return helper.createCipher(cipherName); - } - catch (Exception e) - { - throw new CMSException("cannot create cipher: " + e.getMessage(), e); - } - } - - KeyAgreement createKeyAgreement(ASN1ObjectIdentifier algorithm) - throws CMSException - { - try - { - String agreementName = (String)BASE_CIPHER_NAMES.get(algorithm); - - if (agreementName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createKeyAgreement(agreementName); - } - catch (NoSuchAlgorithmException e) - { - // Ignore - } - } - return helper.createKeyAgreement(algorithm.getId()); - } - catch (Exception e) - { - throw new CMSException("cannot create key pair generator: " + e.getMessage(), e); - } - } - - AlgorithmParameterGenerator createAlgorithmParameterGenerator(ASN1ObjectIdentifier algorithm) - throws CMSException - { - String algorithmName = (String)BASE_CIPHER_NAMES.get(algorithm); - - try - { - if (algorithmName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createAlgorithmParameterGenerator(algorithmName); - } - catch (NoSuchAlgorithmException e) - { - // Ignore - } - } - return helper.createAlgorithmParameterGenerator(algorithm.getId()); - } - catch (Exception e) - { - throw new CMSException("cannot create key pair generator: " + e.getMessage(), e); - } - } - - public Cipher createContentCipher(final Key sKey, final AlgorithmIdentifier encryptionAlgID) - throws CMSException - { - return (Cipher)execute(new JCECallback() - { - public Object doInJCE() - throws CMSException, InvalidAlgorithmParameterException, - InvalidKeyException, InvalidParameterSpecException, NoSuchAlgorithmException, - NoSuchPaddingException, NoSuchProviderException - { - Cipher cipher = createCipher(encryptionAlgID.getAlgorithm()); - ASN1Encodable sParams = encryptionAlgID.getParameters(); - String encAlg = encryptionAlgID.getAlgorithm().getId(); - - if (sParams != null && !(sParams instanceof ASN1Null)) - { - try - { - AlgorithmParameters params = createAlgorithmParameters(encryptionAlgID.getAlgorithm()); - - CMSUtils.loadParameters(params, sParams); - - cipher.init(Cipher.DECRYPT_MODE, sKey, params); - } - catch (NoSuchAlgorithmException e) - { - if (encAlg.equals(CMSAlgorithm.DES_CBC.getId()) - || encAlg.equals(CMSEnvelopedDataGenerator.DES_EDE3_CBC) - || encAlg.equals(CMSEnvelopedDataGenerator.IDEA_CBC) - || encAlg.equals(CMSEnvelopedDataGenerator.AES128_CBC) - || encAlg.equals(CMSEnvelopedDataGenerator.AES192_CBC) - || encAlg.equals(CMSEnvelopedDataGenerator.AES256_CBC)) - { - cipher.init(Cipher.DECRYPT_MODE, sKey, new IvParameterSpec( - ASN1OctetString.getInstance(sParams).getOctets())); - } - else - { - throw e; - } - } - } - else - { - if (encAlg.equals(CMSAlgorithm.DES_CBC.getId()) - || encAlg.equals(CMSEnvelopedDataGenerator.DES_EDE3_CBC) - || encAlg.equals(CMSEnvelopedDataGenerator.IDEA_CBC) - || encAlg.equals(CMSEnvelopedDataGenerator.CAST5_CBC)) - { - cipher.init(Cipher.DECRYPT_MODE, sKey, new IvParameterSpec(new byte[8])); - } - else - { - cipher.init(Cipher.DECRYPT_MODE, sKey); - } - } - - return cipher; - } - }); - } - - Mac createContentMac(final Key sKey, final AlgorithmIdentifier macAlgId) - throws CMSException - { - return (Mac)execute(new JCECallback() - { - public Object doInJCE() - throws CMSException, InvalidAlgorithmParameterException, - InvalidKeyException, InvalidParameterSpecException, NoSuchAlgorithmException, - NoSuchPaddingException, NoSuchProviderException - { - Mac mac = createMac(macAlgId.getAlgorithm()); - ASN1Encodable sParams = macAlgId.getParameters(); - String macAlg = macAlgId.getAlgorithm().getId(); - - if (sParams != null && !(sParams instanceof ASN1Null)) - { - try - { - AlgorithmParameters params = createAlgorithmParameters(macAlgId.getAlgorithm()); - - CMSUtils.loadParameters(params, sParams); - - mac.init(sKey, params.getParameterSpec(IvParameterSpec.class)); - } - catch (NoSuchAlgorithmException e) - { - throw e; - } - } - else - { - mac.init(sKey); - } - - return mac; - } - }); - } - - AlgorithmParameters createAlgorithmParameters(ASN1ObjectIdentifier algorithm) - throws NoSuchAlgorithmException, NoSuchProviderException - { - String algorithmName = (String)BASE_CIPHER_NAMES.get(algorithm); - - if (algorithmName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createAlgorithmParameters(algorithmName); - } - catch (NoSuchAlgorithmException e) - { - // Ignore - } - } - return helper.createAlgorithmParameters(algorithm.getId()); - } - - - KeyPairGenerator createKeyPairGenerator(ASN1ObjectIdentifier algorithm) - throws CMSException - { - try - { - String cipherName = (String)BASE_CIPHER_NAMES.get(algorithm); - - if (cipherName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createKeyPairGenerator(cipherName); - } - catch (NoSuchAlgorithmException e) - { - // Ignore - } - } - return helper.createKeyPairGenerator(algorithm.getId()); - } - catch (Exception e) - { - throw new CMSException("cannot create key pair generator: " + e.getMessage(), e); - } - } - - public KeyGenerator createKeyGenerator(ASN1ObjectIdentifier algorithm) - throws CMSException - { - try - { - String cipherName = (String)BASE_CIPHER_NAMES.get(algorithm); - - if (cipherName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createKeyGenerator(cipherName); - } - catch (NoSuchAlgorithmException e) - { - // Ignore - } - } - return helper.createKeyGenerator(algorithm.getId()); - } - catch (Exception e) - { - throw new CMSException("cannot create key generator: " + e.getMessage(), e); - } - } - - AlgorithmParameters generateParameters(ASN1ObjectIdentifier encryptionOID, SecretKey encKey, SecureRandom rand) - throws CMSException - { - try - { - AlgorithmParameterGenerator pGen = createAlgorithmParameterGenerator(encryptionOID); - - if (encryptionOID.equals(CMSAlgorithm.RC2_CBC)) - { - byte[] iv = new byte[8]; - - rand.nextBytes(iv); - - try - { - pGen.init(new RC2ParameterSpec(encKey.getEncoded().length * 8, iv), rand); - } - catch (InvalidAlgorithmParameterException e) - { - throw new CMSException("parameters generation error: " + e, e); - } - } - - return pGen.generateParameters(); - } - catch (Exception e) - { - throw new CMSException("exception creating algorithm parameter generator: " + e, e); - } - } - - AlgorithmIdentifier getAlgorithmIdentifier(ASN1ObjectIdentifier encryptionOID, AlgorithmParameters params) - throws CMSException - { - ASN1Encodable asn1Params; - if (params != null) - { - asn1Params = CMSUtils.extractParameters(params); - } - else - { - asn1Params = DERNull.INSTANCE; - } - - return new AlgorithmIdentifier( - encryptionOID, - asn1Params); - } - - static Object execute(JCECallback callback) throws CMSException - { - try - { - return callback.doInJCE(); - } - catch (NoSuchAlgorithmException e) - { - throw new CMSException("can't find algorithm.", e); - } - catch (InvalidKeyException e) - { - throw new CMSException("key invalid in message.", e); - } - catch (NoSuchProviderException e) - { - throw new CMSException("can't find provider.", e); - } - catch (NoSuchPaddingException e) - { - throw new CMSException("required padding not supported.", e); - } - catch (InvalidAlgorithmParameterException e) - { - throw new CMSException("algorithm parameters invalid.", e); - } - catch (InvalidParameterSpecException e) - { - throw new CMSException("MAC algorithm parameter spec invalid.", e); - } - } - - public KeyFactory createKeyFactory(ASN1ObjectIdentifier algorithm) - throws CMSException - { - try - { - String cipherName = (String)BASE_CIPHER_NAMES.get(algorithm); - - if (cipherName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createKeyFactory(cipherName); - } - catch (NoSuchAlgorithmException e) - { - // Ignore - } - } - return helper.createKeyFactory(algorithm.getId()); - } - catch (Exception e) - { - throw new CMSException("cannot create key factory: " + e.getMessage(), e); - } - } - - public JceAsymmetricKeyUnwrapper createAsymmetricUnwrapper(AlgorithmIdentifier keyEncryptionAlgorithm, PrivateKey keyEncryptionKey) - { - return helper.createAsymmetricUnwrapper(keyEncryptionAlgorithm, keyEncryptionKey); - } - - public SymmetricKeyUnwrapper createSymmetricUnwrapper(AlgorithmIdentifier keyEncryptionAlgorithm, SecretKey keyEncryptionKey) - { - return helper.createSymmetricUnwrapper(keyEncryptionAlgorithm, keyEncryptionKey); - } - - public AlgorithmIdentifier getAlgorithmIdentifier(ASN1ObjectIdentifier macOID, AlgorithmParameterSpec paramSpec) - { - if (paramSpec instanceof IvParameterSpec) - { - return new AlgorithmIdentifier(macOID, new DEROctetString(((IvParameterSpec)paramSpec).getIV())); - } - - if (paramSpec instanceof RC2ParameterSpec) - { - RC2ParameterSpec rc2Spec = (RC2ParameterSpec)paramSpec; - - int effKeyBits = ((RC2ParameterSpec)paramSpec).getEffectiveKeyBits(); - - if (effKeyBits != -1) - { - int parameterVersion; - - if (effKeyBits < 256) - { - parameterVersion = rc2Table[effKeyBits]; - } - else - { - parameterVersion = effKeyBits; - } - - return new AlgorithmIdentifier(macOID, new RC2CBCParameter(parameterVersion, rc2Spec.getIV())); - } - - return new AlgorithmIdentifier(macOID, new RC2CBCParameter(rc2Spec.getIV())); - } - - throw new IllegalStateException("unknown parameter spec: " + paramSpec); - } - - static interface JCECallback - { - Object doInJCE() - throws CMSException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidParameterSpecException, - NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException; - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JcaSelectorConverter.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JcaSelectorConverter.java deleted file mode 100644 index 6f0224679..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JcaSelectorConverter.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.spongycastle.cms.jcajce; - -import java.security.cert.X509CertSelector; - -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.cms.KeyTransRecipientId; -import org.spongycastle.cms.SignerId; - -public class JcaSelectorConverter -{ - public JcaSelectorConverter() - { - - } - - public SignerId getSignerId(X509CertSelector certSelector) - { -try -{ - if (certSelector.getSubjectKeyIdentifier() != null) - { - return new SignerId(X500Name.getInstance(certSelector.getIssuerAsBytes()), certSelector.getSerialNumber(), ASN1OctetString.getInstance(certSelector.getSubjectKeyIdentifier()).getOctets()); - } - else - { - return new SignerId(X500Name.getInstance(certSelector.getIssuerAsBytes()), certSelector.getSerialNumber()); - } -} -catch (Exception e) -{ - throw new IllegalArgumentException("conversion failed: " + e.toString()); -} - } - - public KeyTransRecipientId getKeyTransRecipientId(X509CertSelector certSelector) - { -try -{ - if (certSelector.getSubjectKeyIdentifier() != null) - { - return new KeyTransRecipientId(X500Name.getInstance(certSelector.getIssuerAsBytes()), certSelector.getSerialNumber(), ASN1OctetString.getInstance(certSelector.getSubjectKeyIdentifier()).getOctets()); - } - else - { - return new KeyTransRecipientId(X500Name.getInstance(certSelector.getIssuerAsBytes()), certSelector.getSerialNumber()); - } -} -catch (Exception e) -{ - throw new IllegalArgumentException("conversion failed: " + e.toString()); -} - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JcaX509CertSelectorConverter.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JcaX509CertSelectorConverter.java deleted file mode 100644 index ceb138ed6..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JcaX509CertSelectorConverter.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.spongycastle.cms.jcajce; - -import java.security.cert.X509CertSelector; - -import org.spongycastle.cms.KeyTransRecipientId; -import org.spongycastle.cms.SignerId; - -public class JcaX509CertSelectorConverter - extends org.spongycastle.cert.selector.jcajce.JcaX509CertSelectorConverter -{ - public JcaX509CertSelectorConverter() - { - } - - public X509CertSelector getCertSelector(KeyTransRecipientId recipientId) - { - return doConversion(recipientId.getIssuer(), recipientId.getSerialNumber(), recipientId.getSubjectKeyIdentifier()); - } - - public X509CertSelector getCertSelector(SignerId signerId) - { - return doConversion(signerId.getIssuer(), signerId.getSerialNumber(), signerId.getSubjectKeyIdentifier()); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JceCMSContentEncryptorBuilder.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JceCMSContentEncryptorBuilder.java deleted file mode 100644 index b4bdd4ad7..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JceCMSContentEncryptorBuilder.java +++ /dev/null @@ -1,166 +0,0 @@ -package org.spongycastle.cms.jcajce; - -import java.io.OutputStream; -import java.security.AlgorithmParameters; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.Provider; -import java.security.SecureRandom; -import java.util.HashMap; -import java.util.Map; - -import javax.crypto.Cipher; -import javax.crypto.CipherOutputStream; -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.cms.CMSAlgorithm; -import org.spongycastle.cms.CMSException; -import org.spongycastle.operator.GenericKey; -import org.spongycastle.operator.OutputEncryptor; -import org.spongycastle.util.Integers; - -public class JceCMSContentEncryptorBuilder -{ - private static Map keySizes = new HashMap(); - - static - { - keySizes.put(CMSAlgorithm.AES128_CBC, Integers.valueOf(128)); - keySizes.put(CMSAlgorithm.AES192_CBC, Integers.valueOf(192)); - keySizes.put(CMSAlgorithm.AES256_CBC, Integers.valueOf(256)); - - keySizes.put(CMSAlgorithm.CAMELLIA128_CBC, Integers.valueOf(128)); - keySizes.put(CMSAlgorithm.CAMELLIA192_CBC, Integers.valueOf(192)); - keySizes.put(CMSAlgorithm.CAMELLIA256_CBC, Integers.valueOf(256)); - } - - private static int getKeySize(ASN1ObjectIdentifier oid) - { - Integer size = (Integer)keySizes.get(oid); - - if (size != null) - { - return size.intValue(); - } - - return -1; - } - - private ASN1ObjectIdentifier encryptionOID; - private int keySize; - - private EnvelopedDataHelper helper = new EnvelopedDataHelper(new DefaultJcaJceExtHelper()); - private SecureRandom random; - - public JceCMSContentEncryptorBuilder(ASN1ObjectIdentifier encryptionOID) - { - this(encryptionOID, getKeySize(encryptionOID)); - } - - public JceCMSContentEncryptorBuilder(ASN1ObjectIdentifier encryptionOID, int keySize) - { - this.encryptionOID = encryptionOID; - this.keySize = keySize; - } - - public JceCMSContentEncryptorBuilder setProvider(Provider provider) - { - this.helper = new EnvelopedDataHelper(new ProviderJcaJceExtHelper(provider)); - - return this; - } - - public JceCMSContentEncryptorBuilder setProvider(String providerName) - { - this.helper = new EnvelopedDataHelper(new NamedJcaJceExtHelper(providerName)); - - return this; - } - - public JceCMSContentEncryptorBuilder setSecureRandom(SecureRandom random) - { - this.random = random; - - return this; - } - - public OutputEncryptor build() - throws CMSException - { - return new CMSOutputEncryptor(encryptionOID, keySize, random); - } - - private class CMSOutputEncryptor - implements OutputEncryptor - { - private SecretKey encKey; - private AlgorithmIdentifier algorithmIdentifier; - private Cipher cipher; - - CMSOutputEncryptor(ASN1ObjectIdentifier encryptionOID, int keySize, SecureRandom random) - throws CMSException - { - KeyGenerator keyGen = helper.createKeyGenerator(encryptionOID); - - if (random == null) - { - random = new SecureRandom(); - } - - if (keySize < 0) - { - keyGen.init(random); - } - else - { - keyGen.init(keySize, random); - } - - cipher = helper.createCipher(encryptionOID); - encKey = keyGen.generateKey(); - AlgorithmParameters params = helper.generateParameters(encryptionOID, encKey, random); - - try - { - cipher.init(Cipher.ENCRYPT_MODE, encKey, params, random); - } - catch (InvalidKeyException e) - { - throw new CMSException("unable to initialize cipher: " + e.getMessage(), e); - } - catch (GeneralSecurityException e) - { - throw new CMSException("unable to initialize cipher: " + e.getMessage(), e); - } - - // - // If params are null we try and second guess on them as some providers don't provide - // algorithm parameter generation explicity but instead generate them under the hood. - // - if (params == null) - { - params = cipher.getParameters(); - } - - algorithmIdentifier = helper.getAlgorithmIdentifier(encryptionOID, params); - } - - public AlgorithmIdentifier getAlgorithmIdentifier() - { - return algorithmIdentifier; - } - - public OutputStream getOutputStream(OutputStream dOut) - { - return new CipherOutputStream(dOut, cipher); - } - - public GenericKey getKey() - { - return new GenericKey(encKey); - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JceKeyAgreeRecipient.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JceKeyAgreeRecipient.java deleted file mode 100644 index 93c11b215..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JceKeyAgreeRecipient.java +++ /dev/null @@ -1,184 +0,0 @@ -package org.spongycastle.cms.jcajce; - -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.PublicKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.X509EncodedKeySpec; - -import javax.crypto.Cipher; -import javax.crypto.KeyAgreement; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.cms.ecc.MQVuserKeyingMaterial; -import org.spongycastle.asn1.pkcs.PrivateKeyInfo; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.cms.CMSEnvelopedGenerator; -import org.spongycastle.cms.CMSException; -import org.spongycastle.cms.KeyAgreeRecipient; -import org.spongycastle.jce.spec.MQVPrivateKeySpec; -import org.spongycastle.jce.spec.MQVPublicKeySpec; - -public abstract class JceKeyAgreeRecipient - implements KeyAgreeRecipient -{ - private PrivateKey recipientKey; - protected EnvelopedDataHelper helper = new EnvelopedDataHelper(new DefaultJcaJceExtHelper()); - protected EnvelopedDataHelper contentHelper = helper; - - public JceKeyAgreeRecipient(PrivateKey recipientKey) - { - this.recipientKey = recipientKey; - } - - /** - * Set the provider to use for key recovery and content processing. - * - * @param provider provider to use. - * @return this recipient. - */ - public JceKeyAgreeRecipient setProvider(Provider provider) - { - this.helper = new EnvelopedDataHelper(new ProviderJcaJceExtHelper(provider)); - this.contentHelper = helper; - - return this; - } - - /** - * Set the provider to use for key recovery and content processing. - * - * @param providerName the name of the provider to use. - * @return this recipient. - */ - public JceKeyAgreeRecipient setProvider(String providerName) - { - this.helper = new EnvelopedDataHelper(new NamedJcaJceExtHelper(providerName)); - this.contentHelper = helper; - - return this; - } - - /** - * Set the provider to use for content processing. If providerName is null a "no provider" search will be - * used to satisfy getInstance calls. - * - * @param provider the provider to use. - * @return this recipient. - */ - public JceKeyAgreeRecipient setContentProvider(Provider provider) - { - this.contentHelper = CMSUtils.createContentHelper(provider); - - return this; - } - - /** - * Set the provider to use for content processing. If providerName is null a "no provider" search will be - * used to satisfy getInstance calls. - * - * @param providerName the name of the provider to use. - * @return this recipient. - */ - public JceKeyAgreeRecipient setContentProvider(String providerName) - { - this.contentHelper = CMSUtils.createContentHelper(providerName); - - return this; - } - - private SecretKey calculateAgreedWrapKey(AlgorithmIdentifier keyEncAlg, ASN1ObjectIdentifier wrapAlg, - PublicKey senderPublicKey, ASN1OctetString userKeyingMaterial, PrivateKey receiverPrivateKey) - throws CMSException, GeneralSecurityException, IOException, InvalidKeyException, NoSuchAlgorithmException - { - String agreeAlg = keyEncAlg.getAlgorithm().getId(); - - if (agreeAlg.equals(CMSEnvelopedGenerator.ECMQV_SHA1KDF)) - { - byte[] ukmEncoding = userKeyingMaterial.getOctets(); - MQVuserKeyingMaterial ukm = MQVuserKeyingMaterial.getInstance( - ASN1Primitive.fromByteArray(ukmEncoding)); - - SubjectPublicKeyInfo pubInfo = new SubjectPublicKeyInfo( - getPrivateKeyAlgorithmIdentifier(), - ukm.getEphemeralPublicKey().getPublicKey().getBytes()); - - X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubInfo.getEncoded()); - KeyFactory fact = helper.createKeyFactory(keyEncAlg.getAlgorithm()); - PublicKey ephemeralKey = fact.generatePublic(pubSpec); - - senderPublicKey = new MQVPublicKeySpec(senderPublicKey, ephemeralKey); - receiverPrivateKey = new MQVPrivateKeySpec(receiverPrivateKey, receiverPrivateKey); - } - - KeyAgreement agreement = helper.createKeyAgreement(keyEncAlg.getAlgorithm()); - - agreement.init(receiverPrivateKey); - agreement.doPhase(senderPublicKey, true); - - return agreement.generateSecret(wrapAlg.getId()); - } - - private Key unwrapSessionKey(ASN1ObjectIdentifier wrapAlg, SecretKey agreedKey, ASN1ObjectIdentifier contentEncryptionAlgorithm, byte[] encryptedContentEncryptionKey) - throws CMSException, InvalidKeyException, NoSuchAlgorithmException - { - Cipher keyCipher = helper.createCipher(wrapAlg); - keyCipher.init(Cipher.UNWRAP_MODE, agreedKey); - return keyCipher.unwrap(encryptedContentEncryptionKey, helper.getBaseCipherName(contentEncryptionAlgorithm), Cipher.SECRET_KEY); - } - - protected Key extractSecretKey(AlgorithmIdentifier keyEncryptionAlgorithm, AlgorithmIdentifier contentEncryptionAlgorithm, SubjectPublicKeyInfo senderKey, ASN1OctetString userKeyingMaterial, byte[] encryptedContentEncryptionKey) - throws CMSException - { - try - { - ASN1ObjectIdentifier wrapAlg = - AlgorithmIdentifier.getInstance(keyEncryptionAlgorithm.getParameters()).getAlgorithm(); - - X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(senderKey.getEncoded()); - KeyFactory fact = helper.createKeyFactory(keyEncryptionAlgorithm.getAlgorithm()); - PublicKey senderPublicKey = fact.generatePublic(pubSpec); - - SecretKey agreedWrapKey = calculateAgreedWrapKey(keyEncryptionAlgorithm, wrapAlg, - senderPublicKey, userKeyingMaterial, recipientKey); - - return unwrapSessionKey(wrapAlg, agreedWrapKey, contentEncryptionAlgorithm.getAlgorithm(), encryptedContentEncryptionKey); - } - catch (NoSuchAlgorithmException e) - { - throw new CMSException("can't find algorithm.", e); - } - catch (InvalidKeyException e) - { - throw new CMSException("key invalid in message.", e); - } - catch (InvalidKeySpecException e) - { - throw new CMSException("originator key spec invalid.", e); - } - catch (NoSuchPaddingException e) - { - throw new CMSException("required padding not supported.", e); - } - catch (Exception e) - { - throw new CMSException("originator key invalid.", e); - } - } - - public AlgorithmIdentifier getPrivateKeyAlgorithmIdentifier() - { - return PrivateKeyInfo.getInstance(recipientKey.getEncoded()).getAlgorithmId(); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JceKeyAgreeRecipientInfoGenerator.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JceKeyAgreeRecipientInfoGenerator.java deleted file mode 100644 index b37828840..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JceKeyAgreeRecipientInfoGenerator.java +++ /dev/null @@ -1,212 +0,0 @@ -package org.spongycastle.cms.jcajce; - -import java.security.GeneralSecurityException; -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; - -import javax.crypto.Cipher; -import javax.crypto.KeyAgreement; -import javax.crypto.SecretKey; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.cms.KeyAgreeRecipientIdentifier; -import org.spongycastle.asn1.cms.RecipientEncryptedKey; -import org.spongycastle.asn1.cms.RecipientKeyIdentifier; -import org.spongycastle.asn1.cms.ecc.MQVuserKeyingMaterial; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.cms.CMSAlgorithm; -import org.spongycastle.cms.CMSEnvelopedGenerator; -import org.spongycastle.cms.CMSException; -import org.spongycastle.cms.KeyAgreeRecipientInfoGenerator; -import org.spongycastle.jce.interfaces.ECPublicKey; -import org.spongycastle.jce.spec.ECParameterSpec; -import org.spongycastle.jce.spec.MQVPrivateKeySpec; -import org.spongycastle.jce.spec.MQVPublicKeySpec; -import org.spongycastle.operator.GenericKey; - -public class JceKeyAgreeRecipientInfoGenerator - extends KeyAgreeRecipientInfoGenerator -{ - private List recipientIDs = new ArrayList(); - private List recipientKeys = new ArrayList(); - private PublicKey senderPublicKey; - private PrivateKey senderPrivateKey; - - private EnvelopedDataHelper helper = new EnvelopedDataHelper(new DefaultJcaJceExtHelper()); - private SecureRandom random; - private KeyPair ephemeralKP; - - public JceKeyAgreeRecipientInfoGenerator(ASN1ObjectIdentifier keyAgreementOID, PrivateKey senderPrivateKey, PublicKey senderPublicKey, ASN1ObjectIdentifier keyEncryptionOID) - { - super(keyAgreementOID, SubjectPublicKeyInfo.getInstance(senderPublicKey.getEncoded()), keyEncryptionOID); - - this.senderPublicKey = senderPublicKey; - this.senderPrivateKey = senderPrivateKey; - } - - public JceKeyAgreeRecipientInfoGenerator setProvider(Provider provider) - { - this.helper = new EnvelopedDataHelper(new ProviderJcaJceExtHelper(provider)); - - return this; - } - - public JceKeyAgreeRecipientInfoGenerator setProvider(String providerName) - { - this.helper = new EnvelopedDataHelper(new NamedJcaJceExtHelper(providerName)); - - return this; - } - - public JceKeyAgreeRecipientInfoGenerator setSecureRandom(SecureRandom random) - { - this.random = random; - - return this; - } - - /** - * Add a recipient based on the passed in certificate's public key and its issuer and serial number. - * - * @param recipientCert recipient's certificate - * @return the current instance. - * @throws CertificateEncodingException if the necessary data cannot be extracted from the certificate. - */ - public JceKeyAgreeRecipientInfoGenerator addRecipient(X509Certificate recipientCert) - throws CertificateEncodingException - { - recipientIDs.add(new KeyAgreeRecipientIdentifier(CMSUtils.getIssuerAndSerialNumber(recipientCert))); - recipientKeys.add(recipientCert.getPublicKey()); - - return this; - } - - /** - * Add a recipient identified by the passed in subjectKeyID and the for the passed in public key. - * - * @param subjectKeyID identifier actual recipient will use to match the private key. - * @param publicKey the public key for encrypting the secret key. - * @return the current instance. - * @throws CertificateEncodingException - */ - public JceKeyAgreeRecipientInfoGenerator addRecipient(byte[] subjectKeyID, PublicKey publicKey) - throws CertificateEncodingException - { - recipientIDs.add(new KeyAgreeRecipientIdentifier(new RecipientKeyIdentifier(subjectKeyID))); - recipientKeys.add(publicKey); - - return this; - } - - public ASN1Sequence generateRecipientEncryptedKeys(AlgorithmIdentifier keyAgreeAlgorithm, AlgorithmIdentifier keyEncryptionAlgorithm, GenericKey contentEncryptionKey) - throws CMSException - { - init(keyAgreeAlgorithm.getAlgorithm()); - - PrivateKey senderPrivateKey = this.senderPrivateKey; - - ASN1ObjectIdentifier keyAgreementOID = keyAgreeAlgorithm.getAlgorithm(); - - if (keyAgreementOID.getId().equals(CMSEnvelopedGenerator.ECMQV_SHA1KDF)) - { - senderPrivateKey = new MQVPrivateKeySpec( - senderPrivateKey, ephemeralKP.getPrivate(), ephemeralKP.getPublic()); - } - - ASN1EncodableVector recipientEncryptedKeys = new ASN1EncodableVector(); - for (int i = 0; i != recipientIDs.size(); i++) - { - PublicKey recipientPublicKey = (PublicKey)recipientKeys.get(i); - KeyAgreeRecipientIdentifier karId = (KeyAgreeRecipientIdentifier)recipientIDs.get(i); - - if (keyAgreementOID.getId().equals(CMSEnvelopedGenerator.ECMQV_SHA1KDF)) - { - recipientPublicKey = new MQVPublicKeySpec(recipientPublicKey, recipientPublicKey); - } - - try - { - // Use key agreement to choose a wrap key for this recipient - KeyAgreement keyAgreement = helper.createKeyAgreement(keyAgreementOID); - keyAgreement.init(senderPrivateKey, random); - keyAgreement.doPhase(recipientPublicKey, true); - SecretKey keyEncryptionKey = keyAgreement.generateSecret(keyEncryptionAlgorithm.getAlgorithm().getId()); - - // Wrap the content encryption key with the agreement key - Cipher keyEncryptionCipher = helper.createCipher(keyEncryptionAlgorithm.getAlgorithm()); - - keyEncryptionCipher.init(Cipher.WRAP_MODE, keyEncryptionKey, random); - - byte[] encryptedKeyBytes = keyEncryptionCipher.wrap(helper.getJceKey(contentEncryptionKey)); - - ASN1OctetString encryptedKey = new DEROctetString(encryptedKeyBytes); - - recipientEncryptedKeys.add(new RecipientEncryptedKey(karId, encryptedKey)); - } - catch (NoSuchAlgorithmException e) - { - throw new CMSException("cannot perform agreement step: " + e.getMessage(), e); - } - catch (InvalidKeyException e) - { - throw new CMSException("cannot perform agreement step: " + e.getMessage(), e); - } - catch (GeneralSecurityException e) - { - throw new CMSException("cannot perform agreement step: " + e.getMessage(), e); - } - } - - return new DERSequence(recipientEncryptedKeys); - } - - protected ASN1Encodable getUserKeyingMaterial(AlgorithmIdentifier keyAgreeAlg) - throws CMSException - { - init(keyAgreeAlg.getAlgorithm()); - - if (ephemeralKP != null) - { - return new MQVuserKeyingMaterial( - createOriginatorPublicKey(SubjectPublicKeyInfo.getInstance(ephemeralKP.getPublic().getEncoded())), null); - } - - return null; - } - - private void init(ASN1ObjectIdentifier keyAgreementOID) - throws CMSException - { - if (random == null) - { - random = new SecureRandom(); - } - - if (keyAgreementOID.equals(CMSAlgorithm.ECMQV_SHA1KDF)) - { - if (ephemeralKP == null) - { - throw new CMSException( - "cannot determine MQV ephemeral key pair parameters from public key"); - } - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JcePasswordRecipient.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JcePasswordRecipient.java deleted file mode 100644 index 31e8729b3..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JcePasswordRecipient.java +++ /dev/null @@ -1,107 +0,0 @@ -package org.spongycastle.cms.jcajce; - -import java.security.InvalidKeyException; -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchAlgorithmException; -import java.security.Key; -import java.security.Provider; - -import javax.crypto.Cipher; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.pkcs.PBKDF2Params; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.cms.CMSException; -import org.spongycastle.cms.PasswordRecipient; -import org.spongycastle.crypto.generators.PKCS5S2ParametersGenerator; -import org.spongycastle.crypto.params.KeyParameter; - -/** - * the RecipientInfo class for a recipient who has been sent a message - * encrypted using a password. - */ -public abstract class JcePasswordRecipient - implements PasswordRecipient -{ - private int schemeID = PasswordRecipient.PKCS5_SCHEME2_UTF8; - protected EnvelopedDataHelper helper = new EnvelopedDataHelper(new DefaultJcaJceExtHelper()); - private char[] password; - - JcePasswordRecipient( - char[] password) - { - this.password = password; - } - - public JcePasswordRecipient setPasswordConversionScheme(int schemeID) - { - this.schemeID = schemeID; - - return this; - } - - public JcePasswordRecipient setProvider(Provider provider) - { - this.helper = new EnvelopedDataHelper(new ProviderJcaJceExtHelper(provider)); - - return this; - } - - public JcePasswordRecipient setProvider(String providerName) - { - this.helper = new EnvelopedDataHelper(new NamedJcaJceExtHelper(providerName)); - - return this; - } - - protected Key extractSecretKey(AlgorithmIdentifier keyEncryptionAlgorithm, AlgorithmIdentifier contentEncryptionAlgorithm, byte[] derivedKey, byte[] encryptedContentEncryptionKey) - throws CMSException - { - Cipher keyEncryptionCipher = helper.createRFC3211Wrapper(keyEncryptionAlgorithm.getAlgorithm()); - - try - { - IvParameterSpec ivSpec = new IvParameterSpec(ASN1OctetString.getInstance(keyEncryptionAlgorithm.getParameters()).getOctets()); - - keyEncryptionCipher.init(Cipher.UNWRAP_MODE, new SecretKeySpec(derivedKey, keyEncryptionCipher.getAlgorithm()), ivSpec); - - return keyEncryptionCipher.unwrap(encryptedContentEncryptionKey, contentEncryptionAlgorithm.getAlgorithm().getId(), Cipher.SECRET_KEY); - } - catch (NoSuchAlgorithmException e) - { - throw new CMSException("cannot process content encryption key: " + e.getMessage(), e); - } - catch (InvalidKeyException e) - { - throw new CMSException("cannot process content encryption key: " + e.getMessage(), e); - } - catch (InvalidAlgorithmParameterException e) - { - throw new CMSException("cannot process content encryption key: " + e.getMessage(), e); - } - } - - public byte[] calculateDerivedKey(byte[] encodedPassword, AlgorithmIdentifier derivationAlgorithm, int keySize) - throws CMSException - { - PBKDF2Params params = PBKDF2Params.getInstance(derivationAlgorithm.getParameters()); - - PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(); - - gen.init(encodedPassword, params.getSalt(), params.getIterationCount().intValue()); - - return ((KeyParameter)gen.generateDerivedParameters(keySize)).getKey(); - } - - public int getPasswordConversionScheme() - { - return schemeID; - } - - public char[] getPassword() - { - return password; - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JcePasswordRecipientInfoGenerator.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JcePasswordRecipientInfoGenerator.java deleted file mode 100644 index ae706b10e..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/JcePasswordRecipientInfoGenerator.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.spongycastle.cms.jcajce; - -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.Provider; - -import javax.crypto.Cipher; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.pkcs.PBKDF2Params; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.cms.CMSException; -import org.spongycastle.cms.PasswordRecipientInfoGenerator; -import org.spongycastle.crypto.generators.PKCS5S2ParametersGenerator; -import org.spongycastle.crypto.params.KeyParameter; -import org.spongycastle.operator.GenericKey; - -public class JcePasswordRecipientInfoGenerator - extends PasswordRecipientInfoGenerator -{ - private EnvelopedDataHelper helper = new EnvelopedDataHelper(new DefaultJcaJceExtHelper()); - - public JcePasswordRecipientInfoGenerator(ASN1ObjectIdentifier kekAlgorithm, char[] password) - { - super(kekAlgorithm, password); - } - - public JcePasswordRecipientInfoGenerator setProvider(Provider provider) - { - this.helper = new EnvelopedDataHelper(new ProviderJcaJceExtHelper(provider)); - - return this; - } - - public JcePasswordRecipientInfoGenerator setProvider(String providerName) - { - this.helper = new EnvelopedDataHelper(new NamedJcaJceExtHelper(providerName)); - - return this; - } - - protected byte[] calculateDerivedKey(byte[] encodedPassword, AlgorithmIdentifier derivationAlgorithm, int keySize) - throws CMSException - { - PBKDF2Params params = PBKDF2Params.getInstance(derivationAlgorithm.getParameters()); - - PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(); - - gen.init(encodedPassword, params.getSalt(), params.getIterationCount().intValue()); - - return ((KeyParameter)gen.generateDerivedParameters(keySize)).getKey(); - } - - public byte[] generateEncryptedBytes(AlgorithmIdentifier keyEncryptionAlgorithm, byte[] derivedKey, GenericKey contentEncryptionKey) - throws CMSException - { - Key contentEncryptionKeySpec = helper.getJceKey(contentEncryptionKey); - Cipher keyEncryptionCipher = helper.createRFC3211Wrapper(keyEncryptionAlgorithm.getAlgorithm()); - - try - { - IvParameterSpec ivSpec = new IvParameterSpec(ASN1OctetString.getInstance(keyEncryptionAlgorithm.getParameters()).getOctets()); - - keyEncryptionCipher.init(Cipher.WRAP_MODE, new SecretKeySpec(derivedKey, keyEncryptionCipher.getAlgorithm()), ivSpec); - - return keyEncryptionCipher.wrap(contentEncryptionKeySpec); - } - catch (GeneralSecurityException e) - { - throw new CMSException("cannot process content encryption key: " + e.getMessage(), e); - } - catch (InvalidKeyException e) - { - throw new CMSException("cannot process content encryption key: " + e.getMessage(), e); - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/ZlibExpanderProvider.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/ZlibExpanderProvider.java deleted file mode 100644 index 880dc2cea..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/cms/jcajce/ZlibExpanderProvider.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.spongycastle.cms.jcajce; - -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.zip.InflaterInputStream; - -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.operator.InputExpander; -import org.spongycastle.operator.InputExpanderProvider; -import org.spongycastle.util.io.StreamOverflowException; - -public class ZlibExpanderProvider - implements InputExpanderProvider -{ - private long limit; - - public ZlibExpanderProvider() - { - this.limit = -1; - } - - /** - * Create a provider which caps the number of expanded bytes that can be produced when the - * compressed stream is parsed. - * - * @param limit max number of bytes allowed in an expanded stream. - */ - public ZlibExpanderProvider(long limit) - { - this.limit = limit; - } - - public InputExpander get(final AlgorithmIdentifier algorithm) - { - return new InputExpander() - { - public AlgorithmIdentifier getAlgorithmIdentifier() - { - return algorithm; - } - - public InputStream getInputStream(InputStream comIn) - { - InputStream s = new InflaterInputStream(comIn); - if (limit >= 0) - { - s = new LimitedInputStream(s, limit); - } - return s; - } - }; - } - - private static class LimitedInputStream - extends FilterInputStream - { - private long remaining; - - public LimitedInputStream(InputStream input, long limit) - { - super(input); - - this.remaining = limit; - } - - public int read() - throws IOException - { - // Only a single 'extra' byte will ever be read - if (remaining >= 0) - { - int b = super.in.read(); - if (b < 0 || --remaining >= 0) - { - return b; - } - } - - throw new StreamOverflowException("expanded byte limit exceeded"); - } - - public int read(byte[] buf, int off, int len) - throws IOException - { - if (len < 1) - { - // This will give correct exceptions/returns for strange lengths - return super.read(buf, off, len); - } - - if (remaining < 1) - { - // Will either return EOF or throw exception - read(); - return -1; - } - - /* - * Limit the underlying request to 'remaining' bytes. This ensures the - * caller will see the full 'limit' bytes before getting an exception. - * Also, only one extra byte will ever be read. - */ - int actualLen = (remaining > len ? len : (int)remaining); - int numRead = super.in.read(buf, off, actualLen); - if (numRead > 0) - { - remaining -= numRead; - } - return numRead; - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/openssl/jcajce/JceOpenSSLPKCS8DecryptorProviderBuilder.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/openssl/jcajce/JceOpenSSLPKCS8DecryptorProviderBuilder.java deleted file mode 100644 index bd0e93f26..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/openssl/jcajce/JceOpenSSLPKCS8DecryptorProviderBuilder.java +++ /dev/null @@ -1,156 +0,0 @@ -package org.spongycastle.openssl.jcajce; - -import java.io.IOException; -import java.io.InputStream; -import java.security.AlgorithmParameters; -import java.security.GeneralSecurityException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.InvalidKeyException; -import java.security.Provider; - -import javax.crypto.Cipher; -import javax.crypto.CipherInputStream; -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.PBEParameterSpec; - -import org.spongycastle.asn1.pkcs.KeyDerivationFunc; -import org.spongycastle.asn1.pkcs.EncryptionScheme; -import org.spongycastle.asn1.pkcs.PBEParameter; -import org.spongycastle.asn1.pkcs.PBES2Parameters; -import org.spongycastle.asn1.pkcs.PBKDF2Params; -import org.spongycastle.asn1.pkcs.PKCS12PBEParams; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.jcajce.util.DefaultJcaJceHelper; -import org.spongycastle.jcajce.util.JcaJceHelper; -import org.spongycastle.jcajce.util.NamedJcaJceHelper; -import org.spongycastle.jcajce.util.ProviderJcaJceHelper; -import org.spongycastle.openssl.PEMException; -import org.spongycastle.operator.InputDecryptor; -import org.spongycastle.operator.InputDecryptorProvider; -import org.spongycastle.operator.OperatorCreationException; - -public class JceOpenSSLPKCS8DecryptorProviderBuilder -{ - private JcaJceHelper helper = new DefaultJcaJceHelper(); - - public JceOpenSSLPKCS8DecryptorProviderBuilder() - { - helper = new DefaultJcaJceHelper(); - } - - public JceOpenSSLPKCS8DecryptorProviderBuilder setProvider(String providerName) - { - helper = new NamedJcaJceHelper(providerName); - - return this; - } - - public JceOpenSSLPKCS8DecryptorProviderBuilder setProvider(Provider provider) - { - helper = new ProviderJcaJceHelper(provider); - - return this; - } - - public InputDecryptorProvider build(final char[] password) - throws OperatorCreationException - { - return new InputDecryptorProvider() - { - public InputDecryptor get(final AlgorithmIdentifier algorithm) - throws OperatorCreationException - { - final Cipher cipher; - - try - { - if (PEMUtilities.isPKCS5Scheme2(algorithm.getAlgorithm())) - { - PBES2Parameters params = PBES2Parameters.getInstance(algorithm.getParameters()); - KeyDerivationFunc func = params.getKeyDerivationFunc(); - EncryptionScheme scheme = params.getEncryptionScheme(); - PBKDF2Params defParams = (PBKDF2Params)func.getParameters(); - - int iterationCount = defParams.getIterationCount().intValue(); - byte[] salt = defParams.getSalt(); - - String oid = scheme.getAlgorithm().getId(); - - SecretKey key = PEMUtilities.generateSecretKeyForPKCS5Scheme2(oid, password, salt, iterationCount); - - cipher = helper.createCipher(oid); - AlgorithmParameters algParams = helper.createAlgorithmParameters(oid); - - algParams.init(scheme.getParameters().toASN1Primitive().getEncoded()); - - cipher.init(Cipher.DECRYPT_MODE, key, algParams); - } - else if (PEMUtilities.isPKCS12(algorithm.getAlgorithm())) - { - PKCS12PBEParams params = PKCS12PBEParams.getInstance(algorithm.getParameters()); - PBEKeySpec pbeSpec = new PBEKeySpec(password); - - SecretKeyFactory secKeyFact = helper.createSecretKeyFactory(algorithm.getAlgorithm().getId()); - PBEParameterSpec defParams = new PBEParameterSpec(params.getIV(), params.getIterations().intValue()); - - cipher = helper.createCipher(algorithm.getAlgorithm().getId()); - - cipher.init(Cipher.DECRYPT_MODE, secKeyFact.generateSecret(pbeSpec), defParams); - } - else if (PEMUtilities.isPKCS5Scheme1(algorithm.getAlgorithm())) - { - PBEParameter params = PBEParameter.getInstance(algorithm.getParameters()); - PBEKeySpec pbeSpec = new PBEKeySpec(password); - - SecretKeyFactory secKeyFact = helper.createSecretKeyFactory(algorithm.getAlgorithm().getId()); - PBEParameterSpec defParams = new PBEParameterSpec(params.getSalt(), params.getIterationCount().intValue()); - - cipher = helper.createCipher(algorithm.getAlgorithm().getId()); - - cipher.init(Cipher.DECRYPT_MODE, secKeyFact.generateSecret(pbeSpec), defParams); - } - else - { - throw new PEMException("Unknown algorithm: " + algorithm.getAlgorithm()); - } - - return new InputDecryptor() - { - public AlgorithmIdentifier getAlgorithmIdentifier() - { - return algorithm; - } - - public InputStream getInputStream(InputStream encIn) - { - return new CipherInputStream(encIn, cipher); - } - }; - } - catch (IOException e) - { - throw new OperatorCreationException(algorithm.getAlgorithm() + " not available: " + e.getMessage(), e); - } - catch (InvalidKeyException e) - { - throw new OperatorCreationException(algorithm.getAlgorithm() + " not available: " + e.getMessage(), e); - } - catch (NoSuchProviderException e) - { - throw new OperatorCreationException(algorithm.getAlgorithm() + " not available: " + e.getMessage(), e); - } - catch (NoSuchAlgorithmException e) - { - throw new OperatorCreationException(algorithm.getAlgorithm() + " not available: " + e.getMessage(), e); - } - catch (GeneralSecurityException e) - { - throw new OperatorCreationException(algorithm.getAlgorithm() + " not available: " + e.getMessage(), e); - } - }; - }; - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/openssl/jcajce/JceOpenSSLPKCS8EncryptorBuilder.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/openssl/jcajce/JceOpenSSLPKCS8EncryptorBuilder.java deleted file mode 100644 index 139d6fcc2..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/openssl/jcajce/JceOpenSSLPKCS8EncryptorBuilder.java +++ /dev/null @@ -1,240 +0,0 @@ -package org.spongycastle.openssl.jcajce; - -import java.io.IOException; -import java.io.OutputStream; -import java.security.AlgorithmParameterGenerator; -import java.security.AlgorithmParameters; -import java.security.GeneralSecurityException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.InvalidKeyException; -import java.security.Provider; -import java.security.SecureRandom; - -import javax.crypto.Cipher; -import javax.crypto.CipherOutputStream; -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.PBEParameterSpec; - -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.nist.NISTObjectIdentifiers; -import org.spongycastle.asn1.pkcs.KeyDerivationFunc; -import org.spongycastle.asn1.pkcs.PBES2Parameters; -import org.spongycastle.asn1.pkcs.PBKDF2Params; -import org.spongycastle.asn1.pkcs.PKCS12PBEParams; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.jcajce.util.DefaultJcaJceHelper; -import org.spongycastle.jcajce.util.JcaJceHelper; -import org.spongycastle.jcajce.util.NamedJcaJceHelper; -import org.spongycastle.jcajce.util.ProviderJcaJceHelper; -import org.spongycastle.operator.GenericKey; -import org.spongycastle.operator.OperatorCreationException; -import org.spongycastle.operator.OutputEncryptor; -import org.spongycastle.operator.jcajce.JceGenericKey; - -public class JceOpenSSLPKCS8EncryptorBuilder -{ - public static final String AES_128_CBC = NISTObjectIdentifiers.id_aes128_CBC.getId(); - public static final String AES_192_CBC = NISTObjectIdentifiers.id_aes192_CBC.getId(); - public static final String AES_256_CBC = NISTObjectIdentifiers.id_aes256_CBC.getId(); - - public static final String DES3_CBC = PKCSObjectIdentifiers.des_EDE3_CBC.getId(); - - public static final String PBE_SHA1_RC4_128 = PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC4.getId(); - public static final String PBE_SHA1_RC4_40 = PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC4.getId(); - public static final String PBE_SHA1_3DES = PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC.getId(); - public static final String PBE_SHA1_2DES = PKCSObjectIdentifiers.pbeWithSHAAnd2_KeyTripleDES_CBC.getId(); - public static final String PBE_SHA1_RC2_128 = PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC.getId(); - public static final String PBE_SHA1_RC2_40 = PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC2_CBC.getId(); - - private JcaJceHelper helper = new DefaultJcaJceHelper(); - - private AlgorithmParameters params; - private ASN1ObjectIdentifier algOID; - byte[] salt; - int iterationCount; - private Cipher cipher; - private SecureRandom random; - private AlgorithmParameterGenerator paramGen; - private SecretKeyFactory secKeyFact; - private char[] password; - - private SecretKey key; - - public JceOpenSSLPKCS8EncryptorBuilder(ASN1ObjectIdentifier algorithm) - { - algOID = algorithm; - - this.iterationCount = 2048; - } - - public JceOpenSSLPKCS8EncryptorBuilder setRandom(SecureRandom random) - { - this.random = random; - - return this; - } - - public JceOpenSSLPKCS8EncryptorBuilder setPasssword(char[] password) - { - this.password = password; - - return this; - } - - public JceOpenSSLPKCS8EncryptorBuilder setIterationCount(int iterationCount) - { - this.iterationCount = iterationCount; - - return this; - } - - public JceOpenSSLPKCS8EncryptorBuilder setProvider(String providerName) - { - helper = new NamedJcaJceHelper(providerName); - - return this; - } - - public JceOpenSSLPKCS8EncryptorBuilder setProvider(Provider provider) - { - helper = new ProviderJcaJceHelper(provider); - - return this; - } - - public OutputEncryptor build() - throws OperatorCreationException - { - final AlgorithmIdentifier algID; - - salt = new byte[20]; - - if (random == null) - { - random = new SecureRandom(); - } - - random.nextBytes(salt); - - try - { - this.cipher = helper.createCipher(algOID.getId()); - - if (PEMUtilities.isPKCS5Scheme2(algOID)) - { - this.paramGen = helper.createAlgorithmParameterGenerator(algOID.getId()); - } - else - { - this.secKeyFact = helper.createSecretKeyFactory(algOID.getId()); - } - } - catch (NoSuchAlgorithmException e) - { - throw new OperatorCreationException(algOID + " not available: " + e.getMessage(), e); - } - catch (NoSuchProviderException e) - { - throw new OperatorCreationException(algOID + " not available: " + e.getMessage(), e); - } - catch (GeneralSecurityException e) - { - throw new OperatorCreationException(algOID + " not available: " + e.getMessage(), e); - } - - if (PEMUtilities.isPKCS5Scheme2(algOID)) - { - params = paramGen.generateParameters(); - - try - { - KeyDerivationFunc scheme = new KeyDerivationFunc(algOID, ASN1Primitive.fromByteArray(params.getEncoded())); - KeyDerivationFunc func = new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params(salt, iterationCount)); - - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(func); - v.add(scheme); - - algID = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, PBES2Parameters.getInstance(new DERSequence(v))); - } - catch (IOException e) - { - throw new OperatorCreationException(e.getMessage(), e); - } - - key = PEMUtilities.generateSecretKeyForPKCS5Scheme2(algOID.getId(), password, salt, iterationCount); - - try - { - cipher.init(Cipher.ENCRYPT_MODE, key, params); - } - catch (InvalidKeyException e) - { - throw new OperatorCreationException(e.getMessage(), e); - } - catch (GeneralSecurityException e) - { - throw new OperatorCreationException(e.getMessage(), e); - } - } - else if (PEMUtilities.isPKCS12(algOID)) - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(new DEROctetString(salt)); - v.add(new ASN1Integer(iterationCount)); - - algID = new AlgorithmIdentifier(algOID, PKCS12PBEParams.getInstance(new DERSequence(v))); - - try - { - PBEKeySpec pbeSpec = new PBEKeySpec(password); - PBEParameterSpec defParams = new PBEParameterSpec(salt, iterationCount); - - key = secKeyFact.generateSecret(pbeSpec); - - cipher.init(Cipher.ENCRYPT_MODE, key, defParams); - } - catch (InvalidKeyException e) - { - throw new OperatorCreationException(e.getMessage(), e); - } - catch (GeneralSecurityException e) - { - throw new OperatorCreationException(e.getMessage(), e); - } - } - else - { - throw new OperatorCreationException("unknown algorithm: " + algOID, null); - } - - return new OutputEncryptor() - { - public AlgorithmIdentifier getAlgorithmIdentifier() - { - return algID; - } - - public OutputStream getOutputStream(OutputStream encOut) - { - return new CipherOutputStream(encOut, cipher); - } - - public GenericKey getKey() - { - return new JceGenericKey(algID, key); - } - }; - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/JcaContentSignerBuilder.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/JcaContentSignerBuilder.java deleted file mode 100644 index 9f88073e6..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/JcaContentSignerBuilder.java +++ /dev/null @@ -1,164 +0,0 @@ -package org.spongycastle.operator.jcajce; - -import java.io.IOException; -import java.io.OutputStream; -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.SecureRandom; -import java.security.Signature; -import java.security.SignatureException; - -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.jcajce.util.DefaultJcaJceHelper; -import org.spongycastle.jcajce.util.NamedJcaJceHelper; -import org.spongycastle.jcajce.util.ProviderJcaJceHelper; -import org.spongycastle.operator.ContentSigner; -import org.spongycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; -import org.spongycastle.operator.OperatorCreationException; -import org.spongycastle.operator.OperatorStreamException; -import org.spongycastle.operator.RuntimeOperatorException; - -public class JcaContentSignerBuilder -{ - private OperatorHelper helper = new OperatorHelper(new DefaultJcaJceHelper()); - private SecureRandom random; - private String signatureAlgorithm; - private AlgorithmIdentifier sigAlgId; - - public JcaContentSignerBuilder(String signatureAlgorithm) - { - this.signatureAlgorithm = signatureAlgorithm; - this.sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(signatureAlgorithm); - } - - public JcaContentSignerBuilder setProvider(Provider provider) - { - this.helper = new OperatorHelper(new ProviderJcaJceHelper(provider)); - - return this; - } - - public JcaContentSignerBuilder setProvider(String providerName) - { - this.helper = new OperatorHelper(new NamedJcaJceHelper(providerName)); - - return this; - } - - public JcaContentSignerBuilder setSecureRandom(SecureRandom random) - { - this.random = random; - - return this; - } - - public ContentSigner build(PrivateKey privateKey) - throws OperatorCreationException - { - try - { - final Signature sig = helper.createSignature(sigAlgId); - - if (random != null) - { - sig.initSign(privateKey); - } - else - { - sig.initSign(privateKey); - } - - return new ContentSigner() - { - private SignatureOutputStream stream = new SignatureOutputStream(sig); - - public AlgorithmIdentifier getAlgorithmIdentifier() - { - return sigAlgId; - } - - public OutputStream getOutputStream() - { - return stream; - } - - public byte[] getSignature() - { - try - { - return stream.getSignature(); - } - catch (SignatureException e) - { - throw new RuntimeOperatorException("exception obtaining signature: " + e.getMessage(), e); - } - } - }; - } - catch (InvalidKeyException e) - { - throw new OperatorCreationException("cannot create signer: " + e.getMessage(), e); - } - catch (Exception e) - { - throw new OperatorCreationException("cannot create signer: " + e.getMessage(), e); - } - } - - private class SignatureOutputStream - extends OutputStream - { - private Signature sig; - - SignatureOutputStream(Signature sig) - { - this.sig = sig; - } - - public void write(byte[] bytes, int off, int len) - throws IOException - { - try - { - sig.update(bytes, off, len); - } - catch (SignatureException e) - { - throw new OperatorStreamException("exception in content signer: " + e.getMessage(), e); - } - } - - public void write(byte[] bytes) - throws IOException - { - try - { - sig.update(bytes); - } - catch (SignatureException e) - { - throw new OperatorStreamException("exception in content signer: " + e.getMessage(), e); - } - } - - public void write(int b) - throws IOException - { - try - { - sig.update((byte)b); - } - catch (SignatureException e) - { - throw new OperatorStreamException("exception in content signer: " + e.getMessage(), e); - } - } - - byte[] getSignature() - throws SignatureException - { - return sig.sign(); - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/JcaContentVerifierProviderBuilder.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/JcaContentVerifierProviderBuilder.java deleted file mode 100644 index 82ddae47d..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/JcaContentVerifierProviderBuilder.java +++ /dev/null @@ -1,311 +0,0 @@ -package org.spongycastle.operator.jcajce; - -import java.io.IOException; -import java.io.OutputStream; -import java.security.Provider; -import java.security.PublicKey; -import java.security.Signature; -import java.security.SignatureException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.cert.X509CertificateHolder; -import org.spongycastle.cert.jcajce.JcaX509CertificateHolder; -import org.spongycastle.jcajce.util.DefaultJcaJceHelper; -import org.spongycastle.jcajce.util.NamedJcaJceHelper; -import org.spongycastle.jcajce.util.ProviderJcaJceHelper; -import org.spongycastle.operator.ContentVerifier; -import org.spongycastle.operator.ContentVerifierProvider; -import org.spongycastle.operator.OperatorCreationException; -import org.spongycastle.operator.OperatorStreamException; -import org.spongycastle.operator.RawContentVerifier; -import org.spongycastle.operator.RuntimeOperatorException; - -public class JcaContentVerifierProviderBuilder -{ - private OperatorHelper helper = new OperatorHelper(new DefaultJcaJceHelper()); - - public JcaContentVerifierProviderBuilder() - { - } - - public JcaContentVerifierProviderBuilder setProvider(Provider provider) - { - this.helper = new OperatorHelper(new ProviderJcaJceHelper(provider)); - - return this; - } - - public JcaContentVerifierProviderBuilder setProvider(String providerName) - { - this.helper = new OperatorHelper(new NamedJcaJceHelper(providerName)); - - return this; - } - - public ContentVerifierProvider build(X509CertificateHolder certHolder) - throws OperatorCreationException, CertificateException - { - return build(helper.convertCertificate(certHolder)); - } - - public ContentVerifierProvider build(final X509Certificate certificate) - throws OperatorCreationException - { - final X509CertificateHolder certHolder; - - try - { - certHolder = new JcaX509CertificateHolder(certificate); - } - catch (CertificateEncodingException e) - { - throw new OperatorCreationException("cannot process certificate: " + e.getMessage(), e); - } - - return new ContentVerifierProvider() - { - private SignatureOutputStream stream; - - public boolean hasAssociatedCertificate() - { - return true; - } - - public X509CertificateHolder getAssociatedCertificate() - { - return certHolder; - } - - public ContentVerifier get(AlgorithmIdentifier algorithm) - throws OperatorCreationException - { - try - { - Signature sig = helper.createSignature(algorithm); - - sig.initVerify(certificate.getPublicKey()); - - stream = new SignatureOutputStream(sig); - } - catch (Exception e) - { - throw new OperatorCreationException("exception on setup: " + e, e); - } - - Signature rawSig = createRawSig(algorithm, certificate.getPublicKey()); - - if (rawSig != null) - { - return new RawSigVerifier(algorithm, stream, rawSig); - } - else - { - return new SigVerifier(algorithm, stream); - } - } - }; - } - - public ContentVerifierProvider build(final PublicKey publicKey) - throws OperatorCreationException - { - return new ContentVerifierProvider() - { - public boolean hasAssociatedCertificate() - { - return false; - } - - public X509CertificateHolder getAssociatedCertificate() - { - return null; - } - - public ContentVerifier get(AlgorithmIdentifier algorithm) - throws OperatorCreationException - { - SignatureOutputStream stream = createSignatureStream(algorithm, publicKey); - - Signature rawSig = createRawSig(algorithm, publicKey); - - if (rawSig != null) - { - return new RawSigVerifier(algorithm, stream, rawSig); - } - else - { - return new SigVerifier(algorithm, stream); - } - } - }; - } - - public ContentVerifierProvider build(SubjectPublicKeyInfo publicKey) - throws OperatorCreationException - { - return this.build(helper.convertPublicKey(publicKey)); - } - - private SignatureOutputStream createSignatureStream(AlgorithmIdentifier algorithm, PublicKey publicKey) - throws OperatorCreationException - { - try - { - Signature sig = helper.createSignature(algorithm); - - sig.initVerify(publicKey); - - return new SignatureOutputStream(sig); - } - catch (Exception e) - { - throw new OperatorCreationException("exception on setup: " + e, e); - } - } - - private Signature createRawSig(AlgorithmIdentifier algorithm, PublicKey publicKey) - { - Signature rawSig; - try - { - rawSig = helper.createRawSignature(algorithm); - - if (rawSig != null) - { - rawSig.initVerify(publicKey); - } - } - catch (Exception e) - { - rawSig = null; - } - return rawSig; - } - - private class SigVerifier - implements ContentVerifier - { - private SignatureOutputStream stream; - private AlgorithmIdentifier algorithm; - - SigVerifier(AlgorithmIdentifier algorithm, SignatureOutputStream stream) - { - this.algorithm = algorithm; - this.stream = stream; - } - - public AlgorithmIdentifier getAlgorithmIdentifier() - { - return algorithm; - } - - public OutputStream getOutputStream() - { - if (stream == null) - { - throw new IllegalStateException("verifier not initialised"); - } - - return stream; - } - - public boolean verify(byte[] expected) - { - try - { - return stream.verify(expected); - } - catch (SignatureException e) - { - throw new RuntimeOperatorException("exception obtaining signature: " + e.getMessage(), e); - } - } - } - - private class RawSigVerifier - extends SigVerifier - implements RawContentVerifier - { - private Signature rawSignature; - - RawSigVerifier(AlgorithmIdentifier algorithm, SignatureOutputStream stream, Signature rawSignature) - { - super(algorithm, stream); - this.rawSignature = rawSignature; - } - - public boolean verify(byte[] digest, byte[] expected) - { - try - { - rawSignature.update(digest); - - return rawSignature.verify(expected); - } - catch (SignatureException e) - { - throw new RuntimeOperatorException("exception obtaining raw signature: " + e.getMessage(), e); - } - } - } - - private class SignatureOutputStream - extends OutputStream - { - private Signature sig; - - SignatureOutputStream(Signature sig) - { - this.sig = sig; - } - - public void write(byte[] bytes, int off, int len) - throws IOException - { - try - { - sig.update(bytes, off, len); - } - catch (SignatureException e) - { - throw new OperatorStreamException("exception in content signer: " + e.getMessage(), e); - } - } - - public void write(byte[] bytes) - throws IOException - { - try - { - sig.update(bytes); - } - catch (SignatureException e) - { - throw new OperatorStreamException("exception in content signer: " + e.getMessage(), e); - } - } - - public void write(int b) - throws IOException - { - try - { - sig.update((byte)b); - } - catch (SignatureException e) - { - throw new OperatorStreamException("exception in content signer: " + e.getMessage(), e); - } - } - - boolean verify(byte[] expected) - throws SignatureException - { - return sig.verify(expected); - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/JceAsymmetricKeyUnwrapper.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/JceAsymmetricKeyUnwrapper.java deleted file mode 100644 index 29f7fb3d1..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/JceAsymmetricKeyUnwrapper.java +++ /dev/null @@ -1,127 +0,0 @@ -package org.spongycastle.operator.jcajce; - -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.Key; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.ProviderException; -import java.util.HashMap; -import java.util.Map; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.spec.SecretKeySpec; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.jcajce.util.DefaultJcaJceHelper; -import org.spongycastle.jcajce.util.NamedJcaJceHelper; -import org.spongycastle.jcajce.util.ProviderJcaJceHelper; -import org.spongycastle.operator.AsymmetricKeyUnwrapper; -import org.spongycastle.operator.GenericKey; -import org.spongycastle.operator.OperatorException; - -public class JceAsymmetricKeyUnwrapper - extends AsymmetricKeyUnwrapper -{ - private OperatorHelper helper = new OperatorHelper(new DefaultJcaJceHelper()); - private Map extraMappings = new HashMap(); - private PrivateKey privKey; - - public JceAsymmetricKeyUnwrapper(AlgorithmIdentifier algorithmIdentifier, PrivateKey privKey) - { - super(algorithmIdentifier); - - this.privKey = privKey; - } - - public JceAsymmetricKeyUnwrapper setProvider(Provider provider) - { - this.helper = new OperatorHelper(new ProviderJcaJceHelper(provider)); - - return this; - } - - public JceAsymmetricKeyUnwrapper setProvider(String providerName) - { - this.helper = new OperatorHelper(new NamedJcaJceHelper(providerName)); - - return this; - } - - /** - * Internally algorithm ids are converted into cipher names using a lookup table. For some providers - * the standard lookup table won't work. Use this method to establish a specific mapping from an - * algorithm identifier to a specific algorithm. - *

- * For example: - *

-     *     unwrapper.setAlgorithmMapping(PKCSObjectIdentifiers.rsaEncryption, "RSA");
-     * 
- *

- * @param algorithm OID of algorithm in recipient. - * @param algorithmName JCE algorithm name to use. - * @return the current Unwrapper. - */ - public JceAsymmetricKeyUnwrapper setAlgorithmMapping(ASN1ObjectIdentifier algorithm, String algorithmName) - { - extraMappings.put(algorithm, algorithmName); - - return this; - } - - public GenericKey generateUnwrappedKey(AlgorithmIdentifier encryptedKeyAlgorithm, byte[] encryptedKey) - throws OperatorException - { - try - { - Key sKey = null; - - Cipher keyCipher = helper.createAsymmetricWrapper(this.getAlgorithmIdentifier().getAlgorithm(), extraMappings); - - try - { - keyCipher.init(Cipher.UNWRAP_MODE, privKey); - sKey = keyCipher.unwrap(encryptedKey, helper.getKeyAlgorithmName(encryptedKeyAlgorithm.getAlgorithm()), Cipher.SECRET_KEY); - } - catch (NoSuchAlgorithmException e) - { - } - catch (InvalidKeyException e) - { - } - catch (IllegalStateException e) - { - } - catch (UnsupportedOperationException e) - { - } - catch (ProviderException e) - { - } - - // some providers do not support UNWRAP (this appears to be only for asymmetric algorithms) - if (sKey == null) - { - keyCipher.init(Cipher.DECRYPT_MODE, privKey); - sKey = new SecretKeySpec(keyCipher.doFinal(encryptedKey), encryptedKeyAlgorithm.getAlgorithm().getId()); - } - - return new GenericKey(sKey); - } - catch (InvalidKeyException e) - { - throw new OperatorException("key invalid: " + e.getMessage(), e); - } - catch (IllegalBlockSizeException e) - { - throw new OperatorException("illegal blocksize: " + e.getMessage(), e); - } - catch (BadPaddingException e) - { - throw new OperatorException("bad padding: " + e.getMessage(), e); - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/JceSymmetricKeyWrapper.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/JceSymmetricKeyWrapper.java deleted file mode 100644 index 2fd2f97cd..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/JceSymmetricKeyWrapper.java +++ /dev/null @@ -1,159 +0,0 @@ -package org.spongycastle.operator.jcajce; - -import java.security.GeneralSecurityException; -import java.security.Key; -import java.security.Provider; -import java.security.SecureRandom; -import java.security.InvalidKeyException; - -import javax.crypto.Cipher; -import javax.crypto.SecretKey; - -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.kisa.KISAObjectIdentifiers; -import org.spongycastle.asn1.nist.NISTObjectIdentifiers; -import org.spongycastle.asn1.ntt.NTTObjectIdentifiers; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.jcajce.util.DefaultJcaJceHelper; -import org.spongycastle.jcajce.util.NamedJcaJceHelper; -import org.spongycastle.jcajce.util.ProviderJcaJceHelper; -import org.spongycastle.operator.GenericKey; -import org.spongycastle.operator.OperatorException; -import org.spongycastle.operator.SymmetricKeyWrapper; - -public class JceSymmetricKeyWrapper - extends SymmetricKeyWrapper -{ - private OperatorHelper helper = new OperatorHelper(new DefaultJcaJceHelper()); - private SecureRandom random; - private SecretKey wrappingKey; - - public JceSymmetricKeyWrapper(SecretKey wrappingKey) - { - super(determineKeyEncAlg(wrappingKey)); - - this.wrappingKey = wrappingKey; - } - - public JceSymmetricKeyWrapper setProvider(Provider provider) - { - this.helper = new OperatorHelper(new ProviderJcaJceHelper(provider)); - - return this; - } - - public JceSymmetricKeyWrapper setProvider(String providerName) - { - this.helper = new OperatorHelper(new NamedJcaJceHelper(providerName)); - - return this; - } - - public JceSymmetricKeyWrapper setSecureRandom(SecureRandom random) - { - this.random = random; - - return this; - } - - public byte[] generateWrappedKey(GenericKey encryptionKey) - throws OperatorException - { - Key contentEncryptionKeySpec = OperatorUtils.getJceKey(encryptionKey); - - Cipher keyEncryptionCipher = helper.createSymmetricWrapper(this.getAlgorithmIdentifier().getAlgorithm()); - - try - { - keyEncryptionCipher.init(Cipher.WRAP_MODE, wrappingKey, random); - - return keyEncryptionCipher.wrap(contentEncryptionKeySpec); - } - catch (InvalidKeyException e) - { - throw new OperatorException("cannot wrap key: " + e.getMessage(), e); - } - catch (GeneralSecurityException e) - { - throw new OperatorException("cannot wrap key: " + e.getMessage(), e); - } - } - - private static AlgorithmIdentifier determineKeyEncAlg(SecretKey key) - { - String algorithm = key.getAlgorithm(); - - if (algorithm.startsWith("DES")) - { - return new AlgorithmIdentifier(new ASN1ObjectIdentifier( - "1.2.840.113549.1.9.16.3.6"), new DERNull()); - } - else if (algorithm.startsWith("RC2")) - { - return new AlgorithmIdentifier(new ASN1ObjectIdentifier( - "1.2.840.113549.1.9.16.3.7"), new ASN1Integer(58)); - } - else if (algorithm.startsWith("AES")) - { - int length = key.getEncoded().length * 8; - ASN1ObjectIdentifier wrapOid; - - if (length == 128) - { - wrapOid = NISTObjectIdentifiers.id_aes128_wrap; - } - else if (length == 192) - { - wrapOid = NISTObjectIdentifiers.id_aes192_wrap; - } - else if (length == 256) - { - wrapOid = NISTObjectIdentifiers.id_aes256_wrap; - } - else - { - throw new IllegalArgumentException("illegal keysize in AES"); - } - - return new AlgorithmIdentifier(wrapOid); // parameters absent - } - else if (algorithm.startsWith("SEED")) - { - // parameters absent - return new AlgorithmIdentifier( - KISAObjectIdentifiers.id_npki_app_cmsSeed_wrap); - } - else if (algorithm.startsWith("Camellia")) - { - int length = key.getEncoded().length * 8; - ASN1ObjectIdentifier wrapOid; - - if (length == 128) - { - wrapOid = NTTObjectIdentifiers.id_camellia128_wrap; - } - else if (length == 192) - { - wrapOid = NTTObjectIdentifiers.id_camellia192_wrap; - } - else if (length == 256) - { - wrapOid = NTTObjectIdentifiers.id_camellia256_wrap; - } - else - { - throw new IllegalArgumentException( - "illegal keysize in Camellia"); - } - - return new AlgorithmIdentifier(wrapOid); // parameters must be - // absent - } - else - { - throw new IllegalArgumentException("unknown algorithm"); - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/OperatorHelper.java b/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/OperatorHelper.java deleted file mode 100644 index 8507d8784..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.1/org/spongycastle/operator/jcajce/OperatorHelper.java +++ /dev/null @@ -1,477 +0,0 @@ -package org.spongycastle.operator.jcajce; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.security.AlgorithmParameters; -import java.security.GeneralSecurityException; -import java.security.KeyFactory; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PublicKey; -import java.security.Signature; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.security.spec.InvalidKeySpecException; -//import java.security.spec.PSSParameterSpec; -import java.security.spec.X509EncodedKeySpec; -import java.util.HashMap; -import java.util.Map; - -import javax.crypto.Cipher; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.spongycastle.asn1.kisa.KISAObjectIdentifiers; -import org.spongycastle.asn1.nist.NISTObjectIdentifiers; -import org.spongycastle.asn1.ntt.NTTObjectIdentifiers; -import org.spongycastle.asn1.oiw.OIWObjectIdentifiers; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.pkcs.RSASSAPSSparams; -import org.spongycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x9.X9ObjectIdentifiers; -import org.spongycastle.cert.X509CertificateHolder; -import org.spongycastle.jcajce.util.JcaJceHelper; -import org.spongycastle.operator.OperatorCreationException; - -class OperatorHelper -{ - private static final Map oids = new HashMap(); - private static final Map asymmetricWrapperAlgNames = new HashMap(); - private static final Map symmetricWrapperAlgNames = new HashMap(); - private static final Map symmetricKeyAlgNames = new HashMap(); - - static - { - // - // reverse mappings - // - oids.put(new ASN1ObjectIdentifier("1.2.840.113549.1.1.5"), "SHA1WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha224WithRSAEncryption, "SHA224WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha256WithRSAEncryption, "SHA256WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha384WithRSAEncryption, "SHA384WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha512WithRSAEncryption, "SHA512WITHRSA"); - oids.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94, "GOST3411WITHGOST3410"); - oids.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001, "GOST3411WITHECGOST3410"); - - oids.put(new ASN1ObjectIdentifier("1.2.840.113549.1.1.4"), "MD5WITHRSA"); - oids.put(new ASN1ObjectIdentifier("1.2.840.113549.1.1.2"), "MD2WITHRSA"); - oids.put(new ASN1ObjectIdentifier("1.2.840.10040.4.3"), "SHA1WITHDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA1, "SHA1WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA224, "SHA224WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA256, "SHA256WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA384, "SHA384WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA512, "SHA512WITHECDSA"); - oids.put(OIWObjectIdentifiers.sha1WithRSA, "SHA1WITHRSA"); - oids.put(OIWObjectIdentifiers.dsaWithSHA1, "SHA1WITHDSA"); - oids.put(NISTObjectIdentifiers.dsa_with_sha224, "SHA224WITHDSA"); - oids.put(NISTObjectIdentifiers.dsa_with_sha256, "SHA256WITHDSA"); - - oids.put(OIWObjectIdentifiers.idSHA1, "SHA-1"); - oids.put(NISTObjectIdentifiers.id_sha224, "SHA-224"); - oids.put(NISTObjectIdentifiers.id_sha256, "SHA-256"); - oids.put(NISTObjectIdentifiers.id_sha384, "SHA-384"); - oids.put(NISTObjectIdentifiers.id_sha512, "SHA-512"); - oids.put(TeleTrusTObjectIdentifiers.ripemd128, "RIPEMD-128"); - oids.put(TeleTrusTObjectIdentifiers.ripemd160, "RIPEMD-160"); - oids.put(TeleTrusTObjectIdentifiers.ripemd256, "RIPEMD-256"); - - asymmetricWrapperAlgNames.put(PKCSObjectIdentifiers.rsaEncryption, "RSA/ECB/PKCS1Padding"); - - symmetricWrapperAlgNames.put(PKCSObjectIdentifiers.id_alg_CMS3DESwrap, "DESEDEWrap"); - symmetricWrapperAlgNames.put(PKCSObjectIdentifiers.id_alg_CMSRC2wrap, "RC2Wrap"); - symmetricWrapperAlgNames.put(NISTObjectIdentifiers.id_aes128_wrap, "AESWrap"); - symmetricWrapperAlgNames.put(NISTObjectIdentifiers.id_aes192_wrap, "AESWrap"); - symmetricWrapperAlgNames.put(NISTObjectIdentifiers.id_aes256_wrap, "AESWrap"); - symmetricWrapperAlgNames.put(NTTObjectIdentifiers.id_camellia128_wrap, "CamelliaWrap"); - symmetricWrapperAlgNames.put(NTTObjectIdentifiers.id_camellia192_wrap, "CamelliaWrap"); - symmetricWrapperAlgNames.put(NTTObjectIdentifiers.id_camellia256_wrap, "CamelliaWrap"); - symmetricWrapperAlgNames.put(KISAObjectIdentifiers.id_npki_app_cmsSeed_wrap, "SEEDWrap"); - symmetricWrapperAlgNames.put(PKCSObjectIdentifiers.des_EDE3_CBC, "DESede"); - - symmetricKeyAlgNames.put(NISTObjectIdentifiers.aes, "AES"); - symmetricKeyAlgNames.put(NISTObjectIdentifiers.id_aes128_CBC, "AES"); - symmetricKeyAlgNames.put(NISTObjectIdentifiers.id_aes192_CBC, "AES"); - symmetricKeyAlgNames.put(NISTObjectIdentifiers.id_aes256_CBC, "AES"); - symmetricKeyAlgNames.put(PKCSObjectIdentifiers.des_EDE3_CBC, "DESede"); - symmetricKeyAlgNames.put(PKCSObjectIdentifiers.RC2_CBC, "RC2"); - } - - private JcaJceHelper helper; - - OperatorHelper(JcaJceHelper helper) - { - this.helper = helper; - } - - Cipher createAsymmetricWrapper(ASN1ObjectIdentifier algorithm, Map extraAlgNames) - throws OperatorCreationException - { - try - { - String cipherName = null; - - if (!extraAlgNames.isEmpty()) - { - cipherName = (String)extraAlgNames.get(algorithm); - } - - if (cipherName == null) - { - cipherName = (String)asymmetricWrapperAlgNames.get(algorithm); - } - - if (cipherName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createCipher(cipherName); - } - catch (NoSuchAlgorithmException e) - { - // try alternate for RSA - if (cipherName.equals("RSA/ECB/PKCS1Padding")) - { - try - { - return helper.createCipher("RSA/NONE/PKCS1Padding"); - } - catch (NoSuchAlgorithmException ex) - { - // Ignore - } - } - // Ignore - } - } - - return helper.createCipher(algorithm.getId()); - } - catch (Exception e) - { - throw new OperatorCreationException("cannot create cipher: " + e.getMessage(), e); - } - } - - Cipher createSymmetricWrapper(ASN1ObjectIdentifier algorithm) - throws OperatorCreationException - { - try - { - String cipherName = (String)symmetricWrapperAlgNames.get(algorithm); - - if (cipherName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createCipher(cipherName); - } - catch (NoSuchAlgorithmException e) - { - // Ignore - } - } - return helper.createCipher(algorithm.getId()); - } - catch (Exception e) - { - throw new OperatorCreationException("cannot create cipher: " + e.getMessage(), e); - } - } - - AlgorithmParameters createAlgorithmParameters(AlgorithmIdentifier cipherAlgId) - throws OperatorCreationException - { - AlgorithmParameters parameters; - - if (cipherAlgId.getAlgorithm().equals(PKCSObjectIdentifiers.rsaEncryption)) - { - return null; - } - - try - { - parameters = helper.createAlgorithmParameters(cipherAlgId.getAlgorithm().getId()); - } - catch (NoSuchAlgorithmException e) - { - return null; // There's a good chance there aren't any! - } - catch (NoSuchProviderException e) - { - throw new OperatorCreationException("cannot create algorithm parameters: " + e.getMessage(), e); - } - - try - { - parameters.init(cipherAlgId.getParameters().toASN1Primitive().getEncoded()); - } - catch (IOException e) - { - throw new OperatorCreationException("cannot initialise algorithm parameters: " + e.getMessage(), e); - } - - return parameters; - } - - MessageDigest createDigest(AlgorithmIdentifier digAlgId) - throws GeneralSecurityException - { - MessageDigest dig; - - try - { - try - { - dig = helper.createDigest(getDigestAlgName(digAlgId.getAlgorithm())); - } - catch (NoSuchAlgorithmException e) - { - // - // try an alternate - // - if (oids.get(digAlgId.getAlgorithm()) != null) - { - String digestAlgorithm = (String)oids.get(digAlgId.getAlgorithm()); - - dig = helper.createDigest(digestAlgorithm); - } - else - { - throw e; - } - } - } - catch (Exception ex) - { - throw new GeneralSecurityException(ex.toString()); - } - - return dig; - } - - Signature createSignature(AlgorithmIdentifier sigAlgId) - throws Exception - { - Signature sig; - - try - { - sig = helper.createSignature(getSignatureName(sigAlgId)); - } - catch (NoSuchAlgorithmException e) - { - // - // try an alternate - // - if (oids.get(sigAlgId.getAlgorithm()) != null) - { - String signatureAlgorithm = (String)oids.get(sigAlgId.getAlgorithm()); - - sig = helper.createSignature(signatureAlgorithm); - } - else - { - throw e; - } - } - - return sig; - } - - public Signature createRawSignature(AlgorithmIdentifier algorithm) - { - Signature sig; - - try - { - String algName = getSignatureName(algorithm); - - algName = "NONE" + algName.substring(algName.indexOf("WITH")); - - sig = helper.createSignature(algName); - - // RFC 4056 - // When the id-RSASSA-PSS algorithm identifier is used for a signature, - // the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params. -/* - if (algorithm.getAlgorithm().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) - { - AlgorithmParameters params = helper.createAlgorithmParameters(algName); - - JcaJceUtils.loadParameters(params, algorithm.getParameters()); - - PSSParameterSpec spec = (PSSParameterSpec)params.getParameterSpec(PSSParameterSpec.class); - sig.setParameter(spec); - } -*/ - } - catch (Exception e) - { - return null; - } - - return sig; - } - - private static String getSignatureName( - AlgorithmIdentifier sigAlgId) - { - ASN1Encodable params = sigAlgId.getParameters(); - - if (params != null && !DERNull.INSTANCE.equals(params)) - { - if (sigAlgId.getAlgorithm().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) - { - RSASSAPSSparams rsaParams = RSASSAPSSparams.getInstance(params); - return getDigestAlgName(rsaParams.getHashAlgorithm().getAlgorithm()) + "WITHRSAANDMGF1"; - } - } - - if (oids.containsKey(sigAlgId.getAlgorithm())) - { - return (String)oids.get(sigAlgId.getAlgorithm()); - } - - return sigAlgId.getAlgorithm().getId(); - } - - private static String getDigestAlgName( - ASN1ObjectIdentifier digestAlgOID) - { - if (PKCSObjectIdentifiers.md5.equals(digestAlgOID)) - { - return "MD5"; - } - else if (OIWObjectIdentifiers.idSHA1.equals(digestAlgOID)) - { - return "SHA1"; - } - else if (NISTObjectIdentifiers.id_sha224.equals(digestAlgOID)) - { - return "SHA224"; - } - else if (NISTObjectIdentifiers.id_sha256.equals(digestAlgOID)) - { - return "SHA256"; - } - else if (NISTObjectIdentifiers.id_sha384.equals(digestAlgOID)) - { - return "SHA384"; - } - else if (NISTObjectIdentifiers.id_sha512.equals(digestAlgOID)) - { - return "SHA512"; - } - else if (TeleTrusTObjectIdentifiers.ripemd128.equals(digestAlgOID)) - { - return "RIPEMD128"; - } - else if (TeleTrusTObjectIdentifiers.ripemd160.equals(digestAlgOID)) - { - return "RIPEMD160"; - } - else if (TeleTrusTObjectIdentifiers.ripemd256.equals(digestAlgOID)) - { - return "RIPEMD256"; - } - else if (CryptoProObjectIdentifiers.gostR3411.equals(digestAlgOID)) - { - return "GOST3411"; - } - else - { - return digestAlgOID.getId(); - } - } - - public X509Certificate convertCertificate(X509CertificateHolder certHolder) - throws CertificateException - { - - try - { - CertificateFactory certFact = helper.createCertificateFactory("X.509"); - - return (X509Certificate)certFact.generateCertificate(new ByteArrayInputStream(certHolder.getEncoded())); - } - catch (IOException e) - { - throw new OpCertificateException("cannot get encoded form of certificate: " + e.getMessage(), e); - } - catch (NoSuchAlgorithmException e) - { - throw new OpCertificateException("cannot create certificate factory: " + e.getMessage(), e); - } - catch (NoSuchProviderException e) - { - throw new OpCertificateException("cannot find factory provider: " + e.getMessage(), e); - } - } - - public PublicKey convertPublicKey(SubjectPublicKeyInfo publicKeyInfo) - throws OperatorCreationException - { - try - { - KeyFactory keyFact = helper.createKeyFactory(publicKeyInfo.getAlgorithm().getAlgorithm().getId()); - - return keyFact.generatePublic(new X509EncodedKeySpec(publicKeyInfo.getEncoded())); - } - catch (IOException e) - { - throw new OperatorCreationException("cannot get encoded form of key: " + e.getMessage(), e); - } - catch (NoSuchAlgorithmException e) - { - throw new OperatorCreationException("cannot create key factory: " + e.getMessage(), e); - } - catch (NoSuchProviderException e) - { - throw new OperatorCreationException("cannot find factory provider: " + e.getMessage(), e); - } - catch (InvalidKeySpecException e) - { - throw new OperatorCreationException("cannot create key factory: " + e.getMessage(), e); - } - } - - // TODO: put somewhere public so cause easily accessed - private static class OpCertificateException - extends CertificateException - { - private Throwable cause; - - public OpCertificateException(String msg, Throwable cause) - { - super(msg); - - this.cause = cause; - } - - public Throwable getCause() - { - return cause; - } - } - - String getKeyAlgorithmName(ASN1ObjectIdentifier oid) - { - - String name = (String)symmetricKeyAlgNames.get(oid); - - if (name != null) - { - return name; - } - - return oid.getId(); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cert/crmf/jcajce/JceCRMFEncryptorBuilder.java b/extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cert/crmf/jcajce/JceCRMFEncryptorBuilder.java deleted file mode 100644 index c3970ee68..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cert/crmf/jcajce/JceCRMFEncryptorBuilder.java +++ /dev/null @@ -1,135 +0,0 @@ -package org.spongycastle.cert.crmf.jcajce; - -import java.io.OutputStream; -import java.security.AlgorithmParameters; -import java.security.GeneralSecurityException; -import java.security.Provider; -import java.security.SecureRandom; - -import javax.crypto.Cipher; -import javax.crypto.CipherOutputStream; -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.cert.crmf.CRMFException; -import org.spongycastle.jcajce.util.DefaultJcaJceHelper; -import org.spongycastle.jcajce.util.NamedJcaJceHelper; -import org.spongycastle.jcajce.util.ProviderJcaJceHelper; -import org.spongycastle.operator.GenericKey; -import org.spongycastle.operator.OutputEncryptor; - -public class JceCRMFEncryptorBuilder -{ - private ASN1ObjectIdentifier encryptionOID; - private int keySize; - - private CRMFHelper helper = new CRMFHelper(new DefaultJcaJceHelper()); - private SecureRandom random; - - public JceCRMFEncryptorBuilder(ASN1ObjectIdentifier encryptionOID) - { - this(encryptionOID, -1); - } - - public JceCRMFEncryptorBuilder(ASN1ObjectIdentifier encryptionOID, int keySize) - { - this.encryptionOID = encryptionOID; - this.keySize = keySize; - } - - public JceCRMFEncryptorBuilder setProvider(Provider provider) - { - this.helper = new CRMFHelper(new ProviderJcaJceHelper(provider)); - - return this; - } - - public JceCRMFEncryptorBuilder setProvider(String providerName) - { - this.helper = new CRMFHelper(new NamedJcaJceHelper(providerName)); - - return this; - } - - public JceCRMFEncryptorBuilder setSecureRandom(SecureRandom random) - { - this.random = random; - - return this; - } - - public OutputEncryptor build() - throws CRMFException - { - return new CRMFOutputEncryptor(encryptionOID, keySize, random); - } - - private class CRMFOutputEncryptor - implements OutputEncryptor - { - private SecretKey encKey; - private AlgorithmIdentifier algorithmIdentifier; - private Cipher cipher; - - CRMFOutputEncryptor(ASN1ObjectIdentifier encryptionOID, int keySize, SecureRandom random) - throws CRMFException - { - KeyGenerator keyGen = helper.createKeyGenerator(encryptionOID); - - if (random == null) - { - random = new SecureRandom(); - } - - if (keySize < 0) - { - keyGen.init(random); - } - else - { - keyGen.init(keySize, random); - } - - cipher = helper.createCipher(encryptionOID); - encKey = keyGen.generateKey(); - AlgorithmParameters params = helper.generateParameters(encryptionOID, encKey, random); - - try - { - cipher.init(Cipher.ENCRYPT_MODE, encKey, params, random); - } - catch (GeneralSecurityException e) - { - throw new CRMFException("unable to initialize cipher: " + e.getMessage(), e); - } - - // - // If params are null we try and second guess on them as some providers don't provide - // algorithm parameter generation explicity but instead generate them under the hood. - // - if (params == null) - { - params = cipher.getParameters(); - } - - algorithmIdentifier = helper.getAlgorithmIdentifier(encryptionOID, params); - } - - public AlgorithmIdentifier getAlgorithmIdentifier() - { - return algorithmIdentifier; - } - - public OutputStream getOutputStream(OutputStream dOut) - { - return new CipherOutputStream(dOut, cipher); - } - - public GenericKey getKey() - { - return new GenericKey(encKey); - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cert/jcajce/JcaAttrCertStore.java b/extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cert/jcajce/JcaAttrCertStore.java deleted file mode 100644 index 3135567b5..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cert/jcajce/JcaAttrCertStore.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.spongycastle.cert.jcajce; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import org.spongycastle.util.CollectionStore; -import org.spongycastle.x509.X509AttributeCertificate; - -/** - * Class for storing Attribute Certificates for later lookup. - *

- * The class will convert X509AttributeCertificate objects into X509AttributeCertificateHolder objects. - *

- */ -public class JcaAttrCertStore - extends CollectionStore -{ - /** - * Basic constructor. - * - * @param collection - initial contents for the store, this is copied. - */ - public JcaAttrCertStore(Collection collection) - throws IOException - { - super(convertCerts(collection)); - } - - public JcaAttrCertStore(X509AttributeCertificate attrCert) - throws IOException - { - this(convertCert(attrCert)); - } - - private static Collection convertCert(X509AttributeCertificate attrCert) - throws IOException - { - List tmp = new ArrayList(); - - tmp.add(attrCert); - - return convertCerts(tmp); - } - - private static Collection convertCerts(Collection collection) - throws IOException - { - List list = new ArrayList(collection.size()); - - for (Iterator it = collection.iterator(); it.hasNext();) - { - Object o = it.next(); - - if (o instanceof X509AttributeCertificate) - { - X509AttributeCertificate cert = (X509AttributeCertificate)o; - - list.add(new JcaX509AttributeCertificateHolder(cert)); - } - else - { - list.add(o); - } - } - - return list; - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cms/bc/BcCMSContentEncryptorBuilder.java b/extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cms/bc/BcCMSContentEncryptorBuilder.java deleted file mode 100644 index 0e0c1f9fe..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cms/bc/BcCMSContentEncryptorBuilder.java +++ /dev/null @@ -1,124 +0,0 @@ -package org.spongycastle.cms.bc; - -import java.io.OutputStream; -import java.security.SecureRandom; -import java.util.HashMap; -import java.util.Map; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.cms.CMSAlgorithm; -import org.spongycastle.cms.CMSException; -import org.spongycastle.crypto.BufferedBlockCipher; -import org.spongycastle.crypto.CipherKeyGenerator; -import org.spongycastle.crypto.StreamCipher; -import org.spongycastle.crypto.io.CipherOutputStream; -import org.spongycastle.crypto.params.KeyParameter; -import org.spongycastle.operator.GenericKey; -import org.spongycastle.operator.OutputEncryptor; -import org.spongycastle.util.Integers; - -public class BcCMSContentEncryptorBuilder -{ - private static Map keySizes = new HashMap(); - - static - { - keySizes.put(CMSAlgorithm.AES128_CBC, Integers.valueOf(128)); - keySizes.put(CMSAlgorithm.AES192_CBC, Integers.valueOf(192)); - keySizes.put(CMSAlgorithm.AES256_CBC, Integers.valueOf(256)); - - keySizes.put(CMSAlgorithm.CAMELLIA128_CBC, Integers.valueOf(128)); - keySizes.put(CMSAlgorithm.CAMELLIA192_CBC, Integers.valueOf(192)); - keySizes.put(CMSAlgorithm.CAMELLIA256_CBC, Integers.valueOf(256)); - } - - private static int getKeySize(ASN1ObjectIdentifier oid) - { - Integer size = (Integer)keySizes.get(oid); - - if (size != null) - { - return size.intValue(); - } - - return -1; - } - - private ASN1ObjectIdentifier encryptionOID; - private int keySize; - - private EnvelopedDataHelper helper = new EnvelopedDataHelper(); - private SecureRandom random; - - public BcCMSContentEncryptorBuilder(ASN1ObjectIdentifier encryptionOID) - { - this(encryptionOID, getKeySize(encryptionOID)); - } - - public BcCMSContentEncryptorBuilder(ASN1ObjectIdentifier encryptionOID, int keySize) - { - this.encryptionOID = encryptionOID; - this.keySize = keySize; - } - - public BcCMSContentEncryptorBuilder setSecureRandom(SecureRandom random) - { - this.random = random; - - return this; - } - - public OutputEncryptor build() - throws CMSException - { - return new CMSOutputEncryptor(encryptionOID, keySize, random); - } - - private class CMSOutputEncryptor - implements OutputEncryptor - { - private KeyParameter encKey; - private AlgorithmIdentifier algorithmIdentifier; - private Object cipher; - - CMSOutputEncryptor(ASN1ObjectIdentifier encryptionOID, int keySize, SecureRandom random) - throws CMSException - { - if (random == null) - { - random = new SecureRandom(); - } - - CipherKeyGenerator keyGen = helper.createKeyGenerator(encryptionOID, random); - - encKey = new KeyParameter(keyGen.generateKey()); - - algorithmIdentifier = helper.generateAlgorithmIdentifier(encryptionOID, encKey, random); - - cipher = helper.createContentCipher(true, encKey, algorithmIdentifier); - } - - public AlgorithmIdentifier getAlgorithmIdentifier() - { - return algorithmIdentifier; - } - - public OutputStream getOutputStream(OutputStream dOut) - { - if (cipher instanceof BufferedBlockCipher) - { - return new CipherOutputStream(dOut, (BufferedBlockCipher)cipher); - } - else - { - return new CipherOutputStream(dOut, (StreamCipher)cipher); - } - } - - public GenericKey getKey() - { - return new GenericKey(algorithmIdentifier, encKey.getKey()); - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cms/jcajce/JceCMSContentEncryptorBuilder.java b/extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cms/jcajce/JceCMSContentEncryptorBuilder.java deleted file mode 100644 index 60bd74a75..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cms/jcajce/JceCMSContentEncryptorBuilder.java +++ /dev/null @@ -1,161 +0,0 @@ -package org.spongycastle.cms.jcajce; - -import java.io.OutputStream; -import java.security.AlgorithmParameters; -import java.security.GeneralSecurityException; -import java.security.Provider; -import java.security.SecureRandom; -import java.util.HashMap; -import java.util.Map; - -import javax.crypto.Cipher; -import javax.crypto.CipherOutputStream; -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.cms.CMSAlgorithm; -import org.spongycastle.cms.CMSException; -import org.spongycastle.operator.GenericKey; -import org.spongycastle.operator.OutputEncryptor; -import org.spongycastle.util.Integers; - -public class JceCMSContentEncryptorBuilder -{ - private static Map keySizes = new HashMap(); - - static - { - keySizes.put(CMSAlgorithm.AES128_CBC, Integers.valueOf(128)); - keySizes.put(CMSAlgorithm.AES192_CBC, Integers.valueOf(192)); - keySizes.put(CMSAlgorithm.AES256_CBC, Integers.valueOf(256)); - - keySizes.put(CMSAlgorithm.CAMELLIA128_CBC, Integers.valueOf(128)); - keySizes.put(CMSAlgorithm.CAMELLIA192_CBC, Integers.valueOf(192)); - keySizes.put(CMSAlgorithm.CAMELLIA256_CBC, Integers.valueOf(256)); - } - - private static int getKeySize(ASN1ObjectIdentifier oid) - { - Integer size = (Integer)keySizes.get(oid); - - if (size != null) - { - return size.intValue(); - } - - return -1; - } - - private ASN1ObjectIdentifier encryptionOID; - private int keySize; - - private EnvelopedDataHelper helper = new EnvelopedDataHelper(new DefaultJcaJceExtHelper()); - private SecureRandom random; - - public JceCMSContentEncryptorBuilder(ASN1ObjectIdentifier encryptionOID) - { - this(encryptionOID, getKeySize(encryptionOID)); - } - - public JceCMSContentEncryptorBuilder(ASN1ObjectIdentifier encryptionOID, int keySize) - { - this.encryptionOID = encryptionOID; - this.keySize = keySize; - } - - public JceCMSContentEncryptorBuilder setProvider(Provider provider) - { - this.helper = new EnvelopedDataHelper(new ProviderJcaJceExtHelper(provider)); - - return this; - } - - public JceCMSContentEncryptorBuilder setProvider(String providerName) - { - this.helper = new EnvelopedDataHelper(new NamedJcaJceExtHelper(providerName)); - - return this; - } - - public JceCMSContentEncryptorBuilder setSecureRandom(SecureRandom random) - { - this.random = random; - - return this; - } - - public OutputEncryptor build() - throws CMSException - { - return new CMSOutputEncryptor(encryptionOID, keySize, random); - } - - private class CMSOutputEncryptor - implements OutputEncryptor - { - private SecretKey encKey; - private AlgorithmIdentifier algorithmIdentifier; - private Cipher cipher; - - CMSOutputEncryptor(ASN1ObjectIdentifier encryptionOID, int keySize, SecureRandom random) - throws CMSException - { - KeyGenerator keyGen = helper.createKeyGenerator(encryptionOID); - - if (random == null) - { - random = new SecureRandom(); - } - - if (keySize < 0) - { - keyGen.init(random); - } - else - { - keyGen.init(keySize, random); - } - - cipher = helper.createCipher(encryptionOID); - encKey = keyGen.generateKey(); - AlgorithmParameters params = helper.generateParameters(encryptionOID, encKey, random); - - try - { - cipher.init(Cipher.ENCRYPT_MODE, encKey, params, random); - } - catch (GeneralSecurityException e) - { - throw new CMSException("unable to initialize cipher: " + e.getMessage(), e); - } - - // - // If params are null we try and second guess on them as some providers don't provide - // algorithm parameter generation explicity but instead generate them under the hood. - // - if (params == null) - { - params = cipher.getParameters(); - } - - algorithmIdentifier = helper.getAlgorithmIdentifier(encryptionOID, params); - } - - public AlgorithmIdentifier getAlgorithmIdentifier() - { - return algorithmIdentifier; - } - - public OutputStream getOutputStream(OutputStream dOut) - { - return new CipherOutputStream(dOut, cipher); - } - - public GenericKey getKey() - { - return new GenericKey(encKey); - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cms/jcajce/JceCMSMacCalculatorBuilder.java b/extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cms/jcajce/JceCMSMacCalculatorBuilder.java deleted file mode 100644 index ab168ffb8..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.2/org/spongycastle/cms/jcajce/JceCMSMacCalculatorBuilder.java +++ /dev/null @@ -1,155 +0,0 @@ -package org.spongycastle.cms.jcajce; - -import java.io.OutputStream; -import java.security.AlgorithmParameterGenerator; -import java.security.AlgorithmParameters; -import java.security.GeneralSecurityException; -import java.security.Provider; -import java.security.SecureRandom; -import java.security.spec.AlgorithmParameterSpec; - -import javax.crypto.KeyGenerator; -import javax.crypto.Mac; -import javax.crypto.SecretKey; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.RC2ParameterSpec; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.cms.CMSException; -import org.spongycastle.jcajce.io.MacOutputStream; -import org.spongycastle.operator.GenericKey; -import org.spongycastle.operator.MacCalculator; - -public class JceCMSMacCalculatorBuilder -{ - private ASN1ObjectIdentifier macOID; - private int keySize; - - private EnvelopedDataHelper helper = new EnvelopedDataHelper(new DefaultJcaJceExtHelper()); - private SecureRandom random; - private MacOutputStream macOutputStream; - - public JceCMSMacCalculatorBuilder(ASN1ObjectIdentifier macOID) - { - this(macOID, -1); - } - - public JceCMSMacCalculatorBuilder(ASN1ObjectIdentifier macOID, int keySize) - { - this.macOID = macOID; - this.keySize = keySize; - } - - public JceCMSMacCalculatorBuilder setProvider(Provider provider) - { - this.helper = new EnvelopedDataHelper(new ProviderJcaJceExtHelper(provider)); - - return this; - } - - public JceCMSMacCalculatorBuilder setProvider(String providerName) - { - this.helper = new EnvelopedDataHelper(new NamedJcaJceExtHelper(providerName)); - - return this; - } - - public JceCMSMacCalculatorBuilder setSecureRandom(SecureRandom random) - { - this.random = random; - - return this; - } - - public MacCalculator build() - throws CMSException - { - return new CMSOutputEncryptor(macOID, keySize, random); - } - - private class CMSOutputEncryptor - implements MacCalculator - { - private SecretKey encKey; - private AlgorithmIdentifier algorithmIdentifier; - private Mac mac; - private SecureRandom random; - - CMSOutputEncryptor(ASN1ObjectIdentifier macOID, int keySize, SecureRandom random) - throws CMSException - { - KeyGenerator keyGen = helper.createKeyGenerator(macOID); - - if (random == null) - { - random = new SecureRandom(); - } - - this.random = random; - - if (keySize < 0) - { - keyGen.init(random); - } - else - { - keyGen.init(keySize, random); - } - - encKey = keyGen.generateKey(); - - AlgorithmParameterSpec paramSpec = generateParameterSpec(macOID, encKey); - - algorithmIdentifier = helper.getAlgorithmIdentifier(macOID, paramSpec); - mac = helper.createContentMac(encKey, algorithmIdentifier); - } - - public AlgorithmIdentifier getAlgorithmIdentifier() - { - return algorithmIdentifier; - } - - public OutputStream getOutputStream() - { - return new MacOutputStream(mac); - } - - public byte[] getMac() - { - return mac.doFinal(); - } - - public GenericKey getKey() - { - return new GenericKey(encKey); - } - - protected AlgorithmParameterSpec generateParameterSpec(ASN1ObjectIdentifier macOID, SecretKey encKey) - throws CMSException - { - try - { - if (macOID.equals(PKCSObjectIdentifiers.RC2_CBC)) - { - byte[] iv = new byte[8]; - - random.nextBytes(iv); - - return new RC2ParameterSpec(encKey.getEncoded().length * 8, iv); - } - - AlgorithmParameterGenerator pGen = helper.createAlgorithmParameterGenerator(macOID); - - AlgorithmParameters p = pGen.generateParameters(); - - return p.getParameterSpec(IvParameterSpec.class); - } - catch (GeneralSecurityException e) - { - return null; - } - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/crmf/jcajce/JcaCertificateRequestMessage.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/crmf/jcajce/JcaCertificateRequestMessage.java deleted file mode 100644 index eac007e0d..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/crmf/jcajce/JcaCertificateRequestMessage.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.spongycastle.cert.crmf.jcajce; - -import java.security.Provider; -import java.security.PublicKey; - -import org.spongycastle.asn1.crmf.CertReqMsg; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.cert.crmf.CRMFException; -import org.spongycastle.cert.crmf.CertificateRequestMessage; -import org.spongycastle.jcajce.util.DefaultJcaJceHelper; -import org.spongycastle.jcajce.util.NamedJcaJceHelper; -import org.spongycastle.jcajce.util.ProviderJcaJceHelper; - -public class JcaCertificateRequestMessage - extends CertificateRequestMessage -{ - private CRMFHelper helper = new CRMFHelper(new DefaultJcaJceHelper()); - - public JcaCertificateRequestMessage(CertificateRequestMessage certReqMsg) - { - this(certReqMsg.toASN1Structure()); - } - - public JcaCertificateRequestMessage(CertReqMsg certReqMsg) - { - super(certReqMsg); - } - - public JcaCertificateRequestMessage setProvider(String providerName) - { - this.helper = new CRMFHelper(new NamedJcaJceHelper(providerName)); - - return this; - } - - public JcaCertificateRequestMessage setProvider(Provider provider) - { - this.helper = new CRMFHelper(new ProviderJcaJceHelper(provider)); - - return this; - } - - public PublicKey getPublicKey() - throws CRMFException - { - SubjectPublicKeyInfo subjectPublicKeyInfo = getCertTemplate().getPublicKey(); - - if (subjectPublicKeyInfo != null) - { - return helper.toPublicKey(subjectPublicKeyInfo); - } - - return null; - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/crmf/jcajce/JcaCertificateRequestMessageBuilder.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/crmf/jcajce/JcaCertificateRequestMessageBuilder.java deleted file mode 100644 index 6b2f85217..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/crmf/jcajce/JcaCertificateRequestMessageBuilder.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.spongycastle.cert.crmf.jcajce; - -import java.math.BigInteger; -import java.security.PublicKey; - -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.cert.crmf.CertificateRequestMessageBuilder; - -public class JcaCertificateRequestMessageBuilder - extends CertificateRequestMessageBuilder -{ - public JcaCertificateRequestMessageBuilder(BigInteger certReqId) - { - super(certReqId); - } - - public JcaCertificateRequestMessageBuilder setPublicKey(PublicKey publicKey) - { - setPublicKey(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); - - return this; - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/crmf/jcajce/JcaPKIArchiveControlBuilder.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/crmf/jcajce/JcaPKIArchiveControlBuilder.java deleted file mode 100644 index 9e2963c8f..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/crmf/jcajce/JcaPKIArchiveControlBuilder.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.spongycastle.cert.crmf.jcajce; - -import java.security.PrivateKey; - -import org.spongycastle.asn1.pkcs.PrivateKeyInfo; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.cert.crmf.PKIArchiveControlBuilder; - -public class JcaPKIArchiveControlBuilder - extends PKIArchiveControlBuilder -{ - public JcaPKIArchiveControlBuilder(PrivateKey privateKey, X500Name name) - { - this(privateKey, new GeneralName(name)); - } - - public JcaPKIArchiveControlBuilder(PrivateKey privateKey, GeneralName generalName) - { - super(PrivateKeyInfo.getInstance(privateKey.getEncoded()), generalName); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaCertStoreBuilder.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaCertStoreBuilder.java deleted file mode 100644 index 37a1723cb..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaCertStoreBuilder.java +++ /dev/null @@ -1,151 +0,0 @@ -package org.spongycastle.cert.jcajce; - -import java.security.GeneralSecurityException; -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.cert.CRLException; -import org.spongycastle.jce.cert.CertStore; -import java.security.cert.CertificateException; -import org.spongycastle.jce.cert.CollectionCertStoreParameters; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.spongycastle.cert.X509CRLHolder; -import org.spongycastle.cert.X509CertificateHolder; -import org.spongycastle.util.Store; - -/** - * Builder to create a CertStore from certificate and CRL stores. - */ -public class JcaCertStoreBuilder -{ - private List certs = new ArrayList(); - private List crls = new ArrayList(); - private Object provider; - private JcaX509CertificateConverter certificateConverter = new JcaX509CertificateConverter(); - private JcaX509CRLConverter crlConverter = new JcaX509CRLConverter(); - private String type = "Collection"; - - /** - * Add a store full of X509CertificateHolder objects. - * - * @param certStore a store of X509CertificateHolder objects. - */ - public JcaCertStoreBuilder addCertificates(Store certStore) - { - certs.addAll(certStore.getMatches(null)); - - return this; - } - - /** - * Add a single certificate. - * - * @param cert the X509 certificate holder containing the certificate. - */ - public JcaCertStoreBuilder addCertificate(X509CertificateHolder cert) - { - certs.add(cert); - - return this; - } - - /** - * Add a store full of X509CRLHolder objects. - * @param crlStore a store of X509CRLHolder objects. - */ - public JcaCertStoreBuilder addCRLs(Store crlStore) - { - crls.addAll(crlStore.getMatches(null)); - - return this; - } - - /** - * Add a single CRL. - * - * @param crl the X509 CRL holder containing the CRL. - */ - public JcaCertStoreBuilder addCRL(X509CRLHolder crl) - { - crls.add(crl); - - return this; - } - - public JcaCertStoreBuilder setProvider(String providerName) - { - certificateConverter.setProvider(providerName); - crlConverter.setProvider(providerName); - this.provider = providerName; - - return this; - } - - public JcaCertStoreBuilder setProvider(Provider provider) - { - certificateConverter.setProvider(provider); - crlConverter.setProvider(provider); - this.provider = provider; - - return this; - } - - /** - * Set the type of the CertStore generated. By default it is "Collection". - * - * @param type type of CertStore passed to CertStore.getInstance(). - * @return the current builder. - */ - public JcaCertStoreBuilder setType(String type) - { - this.type = type; - - return this; - } - - /** - * Build the CertStore from the current inputs. - * - * @return a CertStore. - * @throws GeneralSecurityException - */ - public CertStore build() - throws GeneralSecurityException - { - CollectionCertStoreParameters params = convertHolders(certificateConverter, crlConverter); - - if (provider instanceof String) - { - return CertStore.getInstance(type, params, (String)provider); - } - - if (provider instanceof Provider) - { - return CertStore.getInstance(type, params, (Provider)provider); - } - - return CertStore.getInstance(type, params); - } - - private CollectionCertStoreParameters convertHolders(JcaX509CertificateConverter certificateConverter, JcaX509CRLConverter crlConverter) - throws CertificateException, CRLException - { - List jcaObjs = new ArrayList(certs.size() + crls.size()); - - for (Iterator it = certs.iterator(); it.hasNext();) - { - jcaObjs.add(certificateConverter.getCertificate((X509CertificateHolder)it.next())); - } - - for (Iterator it = crls.iterator(); it.hasNext();) - { - jcaObjs.add(crlConverter.getCRL((X509CRLHolder)it.next())); - } - - return new CollectionCertStoreParameters(jcaObjs); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX500NameUtil.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX500NameUtil.java deleted file mode 100644 index 840dde552..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX500NameUtil.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.spongycastle.cert.jcajce; - -import java.security.cert.X509Certificate; - -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x500.X500NameStyle; -import org.spongycastle.jce.PrincipalUtil; - -public class JcaX500NameUtil -{ - public static X500Name getIssuer(X509Certificate certificate) - { -try -{ - return X500Name.getInstance(PrincipalUtil.getIssuerX509Principal(certificate).getEncoded()); -} -catch (Exception e) -{ - throw new IllegalStateException(e.toString()); -} - } - - public static X500Name getSubject(X509Certificate certificate) - { -try -{ - return X500Name.getInstance(PrincipalUtil.getSubjectX509Principal(certificate).getEncoded()); -} -catch (Exception e) -{ - throw new IllegalStateException(e.toString()); -} - } - - public static X500Name getIssuer(X500NameStyle style, X509Certificate certificate) - { -try -{ - return X500Name.getInstance(style, PrincipalUtil.getIssuerX509Principal(certificate).getEncoded()); -} -catch (Exception e) -{ - throw new IllegalStateException(e.toString()); -} - } - - public static X500Name getSubject(X500NameStyle style, X509Certificate certificate) - { -try -{ - return X500Name.getInstance(style, PrincipalUtil.getSubjectX509Principal(certificate).getEncoded()); -} -catch (Exception e) -{ - throw new IllegalStateException(e.toString()); -} - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX509ExtensionUtils.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX509ExtensionUtils.java deleted file mode 100644 index f40ab480f..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX509ExtensionUtils.java +++ /dev/null @@ -1,138 +0,0 @@ -package org.spongycastle.cert.jcajce; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.PublicKey; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; - -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.oiw.OIWObjectIdentifiers; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.AuthorityKeyIdentifier; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.GeneralNames; -import org.spongycastle.asn1.x509.SubjectKeyIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.cert.X509ExtensionUtils; -import org.spongycastle.operator.DigestCalculator; - -public class JcaX509ExtensionUtils - extends X509ExtensionUtils -{ - /** - * Create a utility class pre-configured with a SHA-1 digest calculator based on the - * default implementation. - * - * @throws java.security.NoSuchAlgorithmException - */ - public JcaX509ExtensionUtils() - throws NoSuchAlgorithmException - { - super(new SHA1DigestCalculator(MessageDigest.getInstance("SHA1"))); - } - - public JcaX509ExtensionUtils(DigestCalculator calculator) - { - super(calculator); - } - - public AuthorityKeyIdentifier createAuthorityKeyIdentifier( - X509Certificate cert) - throws CertificateEncodingException - { - return super.createAuthorityKeyIdentifier(new JcaX509CertificateHolder(cert)); - } - - public AuthorityKeyIdentifier createAuthorityKeyIdentifier( - PublicKey pubKey) - { - return super.createAuthorityKeyIdentifier(SubjectPublicKeyInfo.getInstance(pubKey.getEncoded())); - } - - public AuthorityKeyIdentifier createAuthorityKeyIdentifier(PublicKey pubKey, GeneralNames generalNames, BigInteger serial) - { - return super.createAuthorityKeyIdentifier(SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()), generalNames, serial); - } - - /** - * Return a RFC 3280 type 1 key identifier. As in: - *
-     * (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
-     * value of the BIT STRING subjectPublicKey (excluding the tag,
-     * length, and number of unused bits).
-     * 
- * @param publicKey the key object containing the key identifier is to be based on. - * @return the key identifier. - */ - public SubjectKeyIdentifier createSubjectKeyIdentifier( - PublicKey publicKey) - { - return super.createSubjectKeyIdentifier(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); - } - - /** - * Return a RFC 3280 type 2 key identifier. As in: - *
-     * (2) The keyIdentifier is composed of a four bit type field with
-     * the value 0100 followed by the least significant 60 bits of the
-     * SHA-1 hash of the value of the BIT STRING subjectPublicKey.
-     * 
- * @param publicKey the key object of interest. - * @return the key identifier. - */ - public SubjectKeyIdentifier createTruncatedSubjectKeyIdentifier(PublicKey publicKey) - { - return super.createSubjectKeyIdentifier(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); - } - - /** - * Return the ASN.1 object contained in a byte[] returned by a getExtensionValue() call. - * - * @param encExtValue DER encoded OCTET STRING containing the DER encoded extension object. - * @return an ASN.1 object - * @throws java.io.IOException on a parsing error. - */ - public static ASN1Primitive parseExtensionValue(byte[] encExtValue) - throws IOException - { - return ASN1Primitive.fromByteArray(ASN1OctetString.getInstance(encExtValue).getOctets()); - } - - private static class SHA1DigestCalculator - implements DigestCalculator - { - private ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - private MessageDigest digest; - - public SHA1DigestCalculator(MessageDigest digest) - { - this.digest = digest; - } - - public AlgorithmIdentifier getAlgorithmIdentifier() - { - return new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1); - } - - public OutputStream getOutputStream() - { - return bOut; - } - - public byte[] getDigest() - { - byte[] bytes = digest.digest(bOut.toByteArray()); - - bOut.reset(); - - return bytes; - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX509v1CertificateBuilder.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX509v1CertificateBuilder.java deleted file mode 100644 index b67959bc8..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX509v1CertificateBuilder.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.spongycastle.cert.jcajce; - -import java.math.BigInteger; -import java.security.PublicKey; -import java.util.Date; - -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.cert.X509v1CertificateBuilder; - -/** - * JCA helper class to allow JCA objects to be used in the construction of a Version 1 certificate. - */ -public class JcaX509v1CertificateBuilder - extends X509v1CertificateBuilder -{ - /** - * Initialise the builder using a PublicKey. - * - * @param issuer X500Name representing the issuer of this certificate. - * @param serial the serial number for the certificate. - * @param notBefore date before which the certificate is not valid. - * @param notAfter date after which the certificate is not valid. - * @param subject X500Name representing the subject of this certificate. - * @param publicKey the public key to be associated with the certificate. - */ - public JcaX509v1CertificateBuilder(X500Name issuer, BigInteger serial, Date notBefore, Date notAfter, X500Name subject, PublicKey publicKey) - { - super(issuer, serial, notBefore, notAfter, subject, SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX509v2CRLBuilder.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX509v2CRLBuilder.java deleted file mode 100644 index 4b1f4907b..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX509v2CRLBuilder.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.spongycastle.cert.jcajce; - -import java.util.Date; - -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.cert.X509v2CRLBuilder; - -public class JcaX509v2CRLBuilder - extends X509v2CRLBuilder -{ - public JcaX509v2CRLBuilder(X500Name issuer, Date now) - { - super(issuer, now); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX509v3CertificateBuilder.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX509v3CertificateBuilder.java deleted file mode 100644 index 4f7a4a1e5..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/JcaX509v3CertificateBuilder.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.spongycastle.cert.jcajce; - -import java.math.BigInteger; -import java.security.PublicKey; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.util.Date; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.cert.X509v3CertificateBuilder; - -/** - * JCA helper class to allow JCA objects to be used in the construction of a Version 3 certificate. - */ -public class JcaX509v3CertificateBuilder - extends X509v3CertificateBuilder -{ - /** - * Initialise the builder using a PublicKey. - * - * @param issuer X500Name representing the issuer of this certificate. - * @param serial the serial number for the certificate. - * @param notBefore date before which the certificate is not valid. - * @param notAfter date after which the certificate is not valid. - * @param subject X500Name representing the subject of this certificate. - * @param publicKey the public key to be associated with the certificate. - */ - public JcaX509v3CertificateBuilder(X500Name issuer, BigInteger serial, Date notBefore, Date notAfter, X500Name subject, PublicKey publicKey) - { - super(issuer, serial, notBefore, notAfter, subject, SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); - } - - /** - * Add a given extension field for the standard extensions tag (tag 3) - * copying the extension value from another certificate. - * - * @param oid the type of the extension to be copied. - * @param critical true if the extension is to be marked critical, false otherwise. - * @param certificate the source of the extension to be copied. - * @return the builder instance. - */ - public JcaX509v3CertificateBuilder copyAndAddExtension( - ASN1ObjectIdentifier oid, - boolean critical, - X509Certificate certificate) - throws CertificateEncodingException - { - this.copyAndAddExtension(oid, critical, new JcaX509CertificateHolder(certificate)); - - return this; - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/ProviderCertHelper.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/ProviderCertHelper.java deleted file mode 100644 index a28a7c562..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/jcajce/ProviderCertHelper.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.spongycastle.cert.jcajce; - -import java.security.Provider; -import java.security.NoSuchProviderException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; - -class ProviderCertHelper - extends CertHelper -{ - private final Provider provider; - - ProviderCertHelper(Provider provider) - { - this.provider = provider; - } - - protected CertificateFactory createCertificateFactory(String type) - throws CertificateException - { - try - { - return CertificateFactory.getInstance(type, provider.getName()); - } - catch (NoSuchProviderException e) - { - throw new CertificateException(e.toString()); - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/ocsp/jcajce/JcaRespID.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/ocsp/jcajce/JcaRespID.java deleted file mode 100644 index 41d9072c2..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/ocsp/jcajce/JcaRespID.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.spongycastle.cert.ocsp.jcajce; - -import java.security.PublicKey; - -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.cert.ocsp.OCSPException; -import org.spongycastle.cert.ocsp.RespID; -import org.spongycastle.operator.DigestCalculator; - -public class JcaRespID - extends RespID -{ - public JcaRespID(PublicKey pubKey, DigestCalculator digCalc) - throws OCSPException - { - super(SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()), digCalc); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/selector/jcajce/JcaSelectorConverter.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/selector/jcajce/JcaSelectorConverter.java deleted file mode 100644 index cede4acc8..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/selector/jcajce/JcaSelectorConverter.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.spongycastle.cert.selector.jcajce; - -import org.spongycastle.jce.cert.X509CertSelector; - -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.cert.selector.X509CertificateHolderSelector; - -public class JcaSelectorConverter -{ - public JcaSelectorConverter() - { - - } - - public X509CertificateHolderSelector getCertificateHolderSelector(X509CertSelector certSelector) - { -try -{ - if (certSelector.getSubjectKeyIdentifier() != null) - { - return new X509CertificateHolderSelector(X500Name.getInstance(certSelector.getIssuerAsBytes()), certSelector.getSerialNumber(), ASN1OctetString.getInstance(certSelector.getSubjectKeyIdentifier()).getOctets()); - } - else - { - return new X509CertificateHolderSelector(X500Name.getInstance(certSelector.getIssuerAsBytes()), certSelector.getSerialNumber()); - } -} -catch (Exception e) -{ -throw new IllegalArgumentException("conversion failed: " + e.toString()); -} - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/selector/jcajce/JcaX509CertSelectorConverter.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/selector/jcajce/JcaX509CertSelectorConverter.java deleted file mode 100644 index b2dbb563e..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/selector/jcajce/JcaX509CertSelectorConverter.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.spongycastle.cert.selector.jcajce; - -import java.io.IOException; -import java.math.BigInteger; -import org.spongycastle.jce.cert.X509CertSelector; - -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.cert.selector.X509CertificateHolderSelector; - -public class JcaX509CertSelectorConverter -{ - public JcaX509CertSelectorConverter() - { - } - - protected X509CertSelector doConversion(X500Name issuer, BigInteger serialNumber, byte[] subjectKeyIdentifier) - { - X509CertSelector selector = new X509CertSelector(); - - if (issuer != null) - { - try - { - selector.setIssuer(issuer.getEncoded()); - } - catch (IOException e) - { - throw new IllegalArgumentException("unable to convert issuer: " + e.getMessage()); - } - } - - if (serialNumber != null) - { - selector.setSerialNumber(serialNumber); - } - - if (subjectKeyIdentifier != null) - { - try - { - selector.setSubjectKeyIdentifier(new DEROctetString(subjectKeyIdentifier).getEncoded()); - } - catch (IOException e) - { - throw new IllegalArgumentException("unable to convert issuer: " + e.getMessage()); - } - } - - return selector; - } - - public X509CertSelector getCertSelector(X509CertificateHolderSelector holderSelector) - { - return doConversion(holderSelector.getIssuer(), holderSelector.getSerialNumber(), holderSelector.getSubjectKeyIdentifier()); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/selector/jcajce/JcaX509CertificateHolderSelector.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/selector/jcajce/JcaX509CertificateHolderSelector.java deleted file mode 100644 index 3280af2a0..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cert/selector/jcajce/JcaX509CertificateHolderSelector.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.spongycastle.cert.selector.jcajce; - -import java.math.BigInteger; -import java.security.cert.X509Certificate; - -import org.spongycastle.jce.X509Principal; -import org.spongycastle.jce.PrincipalUtil; - -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x509.X509Extension; -import org.spongycastle.cert.selector.X509CertificateHolderSelector; - -public class JcaX509CertificateHolderSelector - extends X509CertificateHolderSelector -{ - /** - * Construct a signer identifier based on the issuer, serial number and subject key identifier (if present) of the passed in - * certificate. - * - * @param certificate certificate providing the issue and serial number and subject key identifier. - */ - public JcaX509CertificateHolderSelector(X509Certificate certificate) - { - super(convertPrincipal(certificate), certificate.getSerialNumber(), getSubjectKeyId(certificate)); - } - - private static X500Name convertPrincipal(X509Certificate issuer) - { - if (issuer == null) - { - return null; - } -try -{ - return X500Name.getInstance(PrincipalUtil.getIssuerX509Principal(issuer).toASN1Primitive()); -} -catch (Exception e) -{ - throw new IllegalArgumentException("conversion failed: " + e.toString()); -} - } - - private static byte[] getSubjectKeyId(X509Certificate cert) - { - byte[] ext = cert.getExtensionValue(X509Extension.subjectKeyIdentifier.getId()); - - if (ext != null) - { - return ASN1OctetString.getInstance(ASN1OctetString.getInstance(ext).getOctets()).getOctets(); - } - else - { - return null; - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JcaSelectorConverter.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JcaSelectorConverter.java deleted file mode 100644 index c6d0cebe6..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JcaSelectorConverter.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.spongycastle.cms.jcajce; - -import org.spongycastle.jce.cert.X509CertSelector; - -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.cms.KeyTransRecipientId; -import org.spongycastle.cms.SignerId; - -public class JcaSelectorConverter -{ - public JcaSelectorConverter() - { - - } - - public SignerId getSignerId(X509CertSelector certSelector) - { -try -{ - if (certSelector.getSubjectKeyIdentifier() != null) - { - return new SignerId(X500Name.getInstance(certSelector.getIssuerAsBytes()), certSelector.getSerialNumber(), ASN1OctetString.getInstance(certSelector.getSubjectKeyIdentifier()).getOctets()); - } - else - { - return new SignerId(X500Name.getInstance(certSelector.getIssuerAsBytes()), certSelector.getSerialNumber()); - } -} -catch (Exception e) -{ - throw new IllegalArgumentException("conversion failed: " + e.toString()); -} - } - - public KeyTransRecipientId getKeyTransRecipientId(X509CertSelector certSelector) - { -try -{ - if (certSelector.getSubjectKeyIdentifier() != null) - { - return new KeyTransRecipientId(X500Name.getInstance(certSelector.getIssuerAsBytes()), certSelector.getSerialNumber(), ASN1OctetString.getInstance(certSelector.getSubjectKeyIdentifier()).getOctets()); - } - else - { - return new KeyTransRecipientId(X500Name.getInstance(certSelector.getIssuerAsBytes()), certSelector.getSerialNumber()); - } -} -catch (Exception e) -{ - throw new IllegalArgumentException("conversion failed: " + e.toString()); -} - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JcaSignerId.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JcaSignerId.java deleted file mode 100644 index 99650cfb1..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JcaSignerId.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.spongycastle.cms.jcajce; - -import java.math.BigInteger; -import java.security.cert.X509Certificate; - -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.cms.SignerId; -import org.spongycastle.jce.PrincipalUtil; -import org.spongycastle.jce.X509Principal; - -public class JcaSignerId - extends SignerId -{ - private static X509Principal getPrincipal(X509Certificate cert) - { - try - { - return PrincipalUtil.getIssuerX509Principal(cert); - } - catch (Exception e) - { - throw new IllegalArgumentException("unable to extract principle"); - } - } - - /** - * Construct a signer identifier based on the issuer, serial number and subject key identifier (if present) of the passed in - * certificate. - * - * @param certificate certificate providing the issue and serial number and subject key identifier. - */ - public JcaSignerId(X509Certificate certificate) - { - super(X500Name.getInstance(getPrincipal(certificate).getEncoded()), certificate.getSerialNumber(), CMSUtils.getSubjectKeyId(certificate)); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JcaX509CertSelectorConverter.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JcaX509CertSelectorConverter.java deleted file mode 100644 index 594ed1d55..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JcaX509CertSelectorConverter.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.spongycastle.cms.jcajce; - -import org.spongycastle.jce.cert.X509CertSelector; - -import org.spongycastle.cms.KeyTransRecipientId; -import org.spongycastle.cms.SignerId; - -public class JcaX509CertSelectorConverter - extends org.spongycastle.cert.selector.jcajce.JcaX509CertSelectorConverter -{ - public JcaX509CertSelectorConverter() - { - } - - public X509CertSelector getCertSelector(KeyTransRecipientId recipientId) - { - return doConversion(recipientId.getIssuer(), recipientId.getSerialNumber(), recipientId.getSubjectKeyIdentifier()); - } - - public X509CertSelector getCertSelector(SignerId signerId) - { - return doConversion(signerId.getIssuer(), signerId.getSerialNumber(), signerId.getSubjectKeyIdentifier()); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JceKeyAgreeRecipientId.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JceKeyAgreeRecipientId.java deleted file mode 100644 index 91875037e..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JceKeyAgreeRecipientId.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.spongycastle.cms.jcajce; - -import java.math.BigInteger; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; - -import org.spongycastle.jce.PrincipalUtil; -import org.spongycastle.jce.X509Principal; - -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.cms.KeyAgreeRecipientId; - -public class JceKeyAgreeRecipientId - extends KeyAgreeRecipientId -{ - public JceKeyAgreeRecipientId(X509Certificate certificate) - { - super(X500Name.getInstance(extractIssuer(certificate)), certificate.getSerialNumber()); - } - - private static X509Principal extractIssuer(X509Certificate certificate) - { - try - { - return PrincipalUtil.getIssuerX509Principal(certificate); - } - catch (CertificateEncodingException e) - { - throw new IllegalStateException("can't extract issuer"); - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JceKeyTransRecipientId.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JceKeyTransRecipientId.java deleted file mode 100644 index 5bac48b57..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/cms/jcajce/JceKeyTransRecipientId.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.spongycastle.cms.jcajce; - -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; - -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.cms.KeyTransRecipientId; -import org.spongycastle.jce.PrincipalUtil; -import org.spongycastle.jce.X509Principal; - -public class JceKeyTransRecipientId - extends KeyTransRecipientId -{ - public JceKeyTransRecipientId(X509Certificate certificate) - { - super(X500Name.getInstance(extractIssuer(certificate)), certificate.getSerialNumber(), CMSUtils.getSubjectKeyId(certificate)); - } - - private static X509Principal extractIssuer(X509Certificate certificate) - { - try - { - return PrincipalUtil.getIssuerX509Principal(certificate); - } - catch (CertificateEncodingException e) - { - throw new IllegalStateException("can't extract issuer"); - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/eac/jcajce/ProviderEACHelper.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/eac/jcajce/ProviderEACHelper.java deleted file mode 100644 index 4bc4dfa32..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/eac/jcajce/ProviderEACHelper.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.spongycastle.eac.jcajce; - -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; - -class ProviderEACHelper - implements EACHelper -{ - private final Provider provider; - - ProviderEACHelper(Provider provider) - { - this.provider = provider; - } - - public KeyFactory createKeyFactory(String type) - throws NoSuchAlgorithmException, NoSuchProviderException - { - return KeyFactory.getInstance(type, provider.getName()); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/eac/operator/jcajce/ProviderEACHelper.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/eac/operator/jcajce/ProviderEACHelper.java deleted file mode 100644 index dcdd1e1c0..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/eac/operator/jcajce/ProviderEACHelper.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.spongycastle.eac.operator.jcajce; - -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.Signature; - -class ProviderEACHelper - extends EACHelper -{ - private final Provider provider; - - ProviderEACHelper(Provider provider) - { - this.provider = provider; - } - - protected Signature createSignature(String type) - throws NoSuchAlgorithmException, NoSuchProviderException - { - return Signature.getInstance(type, provider.getName()); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/operator/jcajce/JcaAlgorithmParametersConverter.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/operator/jcajce/JcaAlgorithmParametersConverter.java deleted file mode 100644 index a4de4911a..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/operator/jcajce/JcaAlgorithmParametersConverter.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.spongycastle.operator.jcajce; - - -import java.io.IOException; -import java.security.AlgorithmParameters; -import java.security.InvalidAlgorithmParameterException; -import java.security.spec.AlgorithmParameterSpec; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.pkcs.RSAESOAEPparams; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.operator.DefaultDigestAlgorithmIdentifierFinder; - -public class JcaAlgorithmParametersConverter -{ - public JcaAlgorithmParametersConverter() - { - } - - public AlgorithmIdentifier getAlgorithmIdentifier(ASN1ObjectIdentifier algId, AlgorithmParameters parameters) - throws InvalidAlgorithmParameterException - { - try - { - ASN1Encodable params = ASN1Primitive.fromByteArray(parameters.getEncoded()); - - return new AlgorithmIdentifier(algId, params); - } - catch (IOException e) - { - throw new InvalidAlgorithmParameterException("unable to encode parameters object: " + e.getMessage()); - } - } - - public AlgorithmIdentifier getAlgorithmIdentifier(ASN1ObjectIdentifier algorithm, AlgorithmParameterSpec algorithmSpec) - throws InvalidAlgorithmParameterException - { - throw new InvalidAlgorithmParameterException("unknown parameter spec passed."); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/operator/jcajce/OperatorHelper.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/operator/jcajce/OperatorHelper.java deleted file mode 100644 index 419f0939e..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/operator/jcajce/OperatorHelper.java +++ /dev/null @@ -1,470 +0,0 @@ -package org.spongycastle.operator.jcajce; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.security.AlgorithmParameters; -import java.security.GeneralSecurityException; -import java.security.KeyFactory; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PublicKey; -import java.security.Signature; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.security.spec.InvalidKeySpecException; -//import java.security.spec.PSSParameterSpec; -import java.security.spec.X509EncodedKeySpec; -import java.util.HashMap; -import java.util.Map; - -import javax.crypto.Cipher; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.spongycastle.asn1.kisa.KISAObjectIdentifiers; -import org.spongycastle.asn1.nist.NISTObjectIdentifiers; -import org.spongycastle.asn1.ntt.NTTObjectIdentifiers; -import org.spongycastle.asn1.oiw.OIWObjectIdentifiers; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.pkcs.RSASSAPSSparams; -import org.spongycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x9.X9ObjectIdentifiers; -import org.spongycastle.cert.X509CertificateHolder; -import org.spongycastle.jcajce.util.JcaJceHelper; -import org.spongycastle.operator.OperatorCreationException; - -class OperatorHelper -{ - private static final Map oids = new HashMap(); - private static final Map asymmetricWrapperAlgNames = new HashMap(); - private static final Map symmetricWrapperAlgNames = new HashMap(); - private static final Map symmetricKeyAlgNames = new HashMap(); - - static - { - // - // reverse mappings - // - oids.put(new ASN1ObjectIdentifier("1.2.840.113549.1.1.5"), "SHA1WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha224WithRSAEncryption, "SHA224WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha256WithRSAEncryption, "SHA256WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha384WithRSAEncryption, "SHA384WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha512WithRSAEncryption, "SHA512WITHRSA"); - oids.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94, "GOST3411WITHGOST3410"); - oids.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001, "GOST3411WITHECGOST3410"); - - oids.put(new ASN1ObjectIdentifier("1.2.840.113549.1.1.4"), "MD5WITHRSA"); - oids.put(new ASN1ObjectIdentifier("1.2.840.113549.1.1.2"), "MD2WITHRSA"); - oids.put(new ASN1ObjectIdentifier("1.2.840.10040.4.3"), "SHA1WITHDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA1, "SHA1WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA224, "SHA224WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA256, "SHA256WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA384, "SHA384WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA512, "SHA512WITHECDSA"); - oids.put(OIWObjectIdentifiers.sha1WithRSA, "SHA1WITHRSA"); - oids.put(OIWObjectIdentifiers.dsaWithSHA1, "SHA1WITHDSA"); - oids.put(NISTObjectIdentifiers.dsa_with_sha224, "SHA224WITHDSA"); - oids.put(NISTObjectIdentifiers.dsa_with_sha256, "SHA256WITHDSA"); - - oids.put(OIWObjectIdentifiers.idSHA1, "SHA-1"); - oids.put(NISTObjectIdentifiers.id_sha224, "SHA-224"); - oids.put(NISTObjectIdentifiers.id_sha256, "SHA-256"); - oids.put(NISTObjectIdentifiers.id_sha384, "SHA-384"); - oids.put(NISTObjectIdentifiers.id_sha512, "SHA-512"); - oids.put(TeleTrusTObjectIdentifiers.ripemd128, "RIPEMD-128"); - oids.put(TeleTrusTObjectIdentifiers.ripemd160, "RIPEMD-160"); - oids.put(TeleTrusTObjectIdentifiers.ripemd256, "RIPEMD-256"); - - asymmetricWrapperAlgNames.put(PKCSObjectIdentifiers.rsaEncryption, "RSA/ECB/PKCS1Padding"); - - symmetricWrapperAlgNames.put(PKCSObjectIdentifiers.id_alg_CMS3DESwrap, "DESEDEWrap"); - symmetricWrapperAlgNames.put(PKCSObjectIdentifiers.id_alg_CMSRC2wrap, "RC2Wrap"); - symmetricWrapperAlgNames.put(NISTObjectIdentifiers.id_aes128_wrap, "AESWrap"); - symmetricWrapperAlgNames.put(NISTObjectIdentifiers.id_aes192_wrap, "AESWrap"); - symmetricWrapperAlgNames.put(NISTObjectIdentifiers.id_aes256_wrap, "AESWrap"); - symmetricWrapperAlgNames.put(NTTObjectIdentifiers.id_camellia128_wrap, "CamelliaWrap"); - symmetricWrapperAlgNames.put(NTTObjectIdentifiers.id_camellia192_wrap, "CamelliaWrap"); - symmetricWrapperAlgNames.put(NTTObjectIdentifiers.id_camellia256_wrap, "CamelliaWrap"); - symmetricWrapperAlgNames.put(KISAObjectIdentifiers.id_npki_app_cmsSeed_wrap, "SEEDWrap"); - symmetricWrapperAlgNames.put(PKCSObjectIdentifiers.des_EDE3_CBC, "DESede"); - - symmetricKeyAlgNames.put(NISTObjectIdentifiers.aes, "AES"); - symmetricKeyAlgNames.put(NISTObjectIdentifiers.id_aes128_CBC, "AES"); - symmetricKeyAlgNames.put(NISTObjectIdentifiers.id_aes192_CBC, "AES"); - symmetricKeyAlgNames.put(NISTObjectIdentifiers.id_aes256_CBC, "AES"); - symmetricKeyAlgNames.put(PKCSObjectIdentifiers.des_EDE3_CBC, "DESede"); - symmetricKeyAlgNames.put(PKCSObjectIdentifiers.RC2_CBC, "RC2"); - } - - private JcaJceHelper helper; - - OperatorHelper(JcaJceHelper helper) - { - this.helper = helper; - } - - Cipher createAsymmetricWrapper(ASN1ObjectIdentifier algorithm, Map extraAlgNames) - throws OperatorCreationException - { - try - { - String cipherName = null; - - if (!extraAlgNames.isEmpty()) - { - cipherName = (String)extraAlgNames.get(algorithm); - } - - if (cipherName == null) - { - cipherName = (String)asymmetricWrapperAlgNames.get(algorithm); - } - - if (cipherName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createCipher(cipherName); - } - catch (NoSuchAlgorithmException e) - { - // try alternate for RSA - if (cipherName.equals("RSA/ECB/PKCS1Padding")) - { - try - { - return helper.createCipher("RSA/NONE/PKCS1Padding"); - } - catch (NoSuchAlgorithmException ex) - { - // Ignore - } - } - // Ignore - } - } - - return helper.createCipher(algorithm.getId()); - } - catch (GeneralSecurityException e) - { - throw new OperatorCreationException("cannot create cipher: " + e.getMessage(), e); - } - } - - Cipher createSymmetricWrapper(ASN1ObjectIdentifier algorithm) - throws OperatorCreationException - { - try - { - String cipherName = (String)symmetricWrapperAlgNames.get(algorithm); - - if (cipherName != null) - { - try - { - // this is reversed as the Sun policy files now allow unlimited strength RSA - return helper.createCipher(cipherName); - } - catch (NoSuchAlgorithmException e) - { - // Ignore - } - } - return helper.createCipher(algorithm.getId()); - } - catch (GeneralSecurityException e) - { - throw new OperatorCreationException("cannot create cipher: " + e.getMessage(), e); - } - } - - AlgorithmParameters createAlgorithmParameters(AlgorithmIdentifier cipherAlgId) - throws OperatorCreationException - { - AlgorithmParameters parameters; - - if (cipherAlgId.getAlgorithm().equals(PKCSObjectIdentifiers.rsaEncryption)) - { - return null; - } - - try - { - parameters = helper.createAlgorithmParameters(cipherAlgId.getAlgorithm().getId()); - } - catch (NoSuchAlgorithmException e) - { - return null; // There's a good chance there aren't any! - } - catch (NoSuchProviderException e) - { - throw new OperatorCreationException("cannot create algorithm parameters: " + e.getMessage(), e); - } - - try - { - parameters.init(cipherAlgId.getParameters().toASN1Primitive().getEncoded()); - } - catch (IOException e) - { - throw new OperatorCreationException("cannot initialise algorithm parameters: " + e.getMessage(), e); - } - - return parameters; - } - - MessageDigest createDigest(AlgorithmIdentifier digAlgId) - throws GeneralSecurityException - { - MessageDigest dig; - - try - { - dig = helper.createDigest(getDigestAlgName(digAlgId.getAlgorithm())); - } - catch (NoSuchAlgorithmException e) - { - // - // try an alternate - // - if (oids.get(digAlgId.getAlgorithm()) != null) - { - String digestAlgorithm = (String)oids.get(digAlgId.getAlgorithm()); - - dig = helper.createDigest(digestAlgorithm); - } - else - { - throw e; - } - } - - return dig; - } - - Signature createSignature(AlgorithmIdentifier sigAlgId) - throws GeneralSecurityException - { - Signature sig; - - try - { - sig = helper.createSignature(getSignatureName(sigAlgId)); - } - catch (NoSuchAlgorithmException e) - { - // - // try an alternate - // - if (oids.get(sigAlgId.getAlgorithm()) != null) - { - String signatureAlgorithm = (String)oids.get(sigAlgId.getAlgorithm()); - - sig = helper.createSignature(signatureAlgorithm); - } - else - { - throw e; - } - } - - return sig; - } - - public Signature createRawSignature(AlgorithmIdentifier algorithm) - { - Signature sig; - - try - { - String algName = getSignatureName(algorithm); - - algName = "NONE" + algName.substring(algName.indexOf("WITH")); - - sig = helper.createSignature(algName); - - // RFC 4056 - // When the id-RSASSA-PSS algorithm identifier is used for a signature, - // the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params. -/* - if (algorithm.getAlgorithm().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) - { - AlgorithmParameters params = helper.createAlgorithmParameters(algName); - - JcaJceUtils.loadParameters(params, algorithm.getParameters()); - - PSSParameterSpec spec = (PSSParameterSpec)params.getParameterSpec(PSSParameterSpec.class); - sig.setParameter(spec); - } -*/ - } - catch (Exception e) - { - return null; - } - - return sig; - } - - private static String getSignatureName( - AlgorithmIdentifier sigAlgId) - { - ASN1Encodable params = sigAlgId.getParameters(); - - if (params != null && !DERNull.INSTANCE.equals(params)) - { - if (sigAlgId.getAlgorithm().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) - { - RSASSAPSSparams rsaParams = RSASSAPSSparams.getInstance(params); - return getDigestAlgName(rsaParams.getHashAlgorithm().getAlgorithm()) + "WITHRSAANDMGF1"; - } - } - - if (oids.containsKey(sigAlgId.getAlgorithm())) - { - return (String)oids.get(sigAlgId.getAlgorithm()); - } - - return sigAlgId.getAlgorithm().getId(); - } - - private static String getDigestAlgName( - ASN1ObjectIdentifier digestAlgOID) - { - if (PKCSObjectIdentifiers.md5.equals(digestAlgOID)) - { - return "MD5"; - } - else if (OIWObjectIdentifiers.idSHA1.equals(digestAlgOID)) - { - return "SHA1"; - } - else if (NISTObjectIdentifiers.id_sha224.equals(digestAlgOID)) - { - return "SHA224"; - } - else if (NISTObjectIdentifiers.id_sha256.equals(digestAlgOID)) - { - return "SHA256"; - } - else if (NISTObjectIdentifiers.id_sha384.equals(digestAlgOID)) - { - return "SHA384"; - } - else if (NISTObjectIdentifiers.id_sha512.equals(digestAlgOID)) - { - return "SHA512"; - } - else if (TeleTrusTObjectIdentifiers.ripemd128.equals(digestAlgOID)) - { - return "RIPEMD128"; - } - else if (TeleTrusTObjectIdentifiers.ripemd160.equals(digestAlgOID)) - { - return "RIPEMD160"; - } - else if (TeleTrusTObjectIdentifiers.ripemd256.equals(digestAlgOID)) - { - return "RIPEMD256"; - } - else if (CryptoProObjectIdentifiers.gostR3411.equals(digestAlgOID)) - { - return "GOST3411"; - } - else - { - return digestAlgOID.getId(); - } - } - - public X509Certificate convertCertificate(X509CertificateHolder certHolder) - throws CertificateException - { - - try - { - CertificateFactory certFact = helper.createCertificateFactory("X.509"); - - return (X509Certificate)certFact.generateCertificate(new ByteArrayInputStream(certHolder.getEncoded())); - } - catch (IOException e) - { - throw new OpCertificateException("cannot get encoded form of certificate: " + e.getMessage(), e); - } - catch (NoSuchAlgorithmException e) - { - throw new OpCertificateException("cannot create certificate factory: " + e.getMessage(), e); - } - catch (NoSuchProviderException e) - { - throw new OpCertificateException("cannot find factory provider: " + e.getMessage(), e); - } - } - - public PublicKey convertPublicKey(SubjectPublicKeyInfo publicKeyInfo) - throws OperatorCreationException - { - try - { - KeyFactory keyFact = helper.createKeyFactory(publicKeyInfo.getAlgorithm().getAlgorithm().getId()); - - return keyFact.generatePublic(new X509EncodedKeySpec(publicKeyInfo.getEncoded())); - } - catch (IOException e) - { - throw new OperatorCreationException("cannot get encoded form of key: " + e.getMessage(), e); - } - catch (NoSuchAlgorithmException e) - { - throw new OperatorCreationException("cannot create key factory: " + e.getMessage(), e); - } - catch (NoSuchProviderException e) - { - throw new OperatorCreationException("cannot find factory provider: " + e.getMessage(), e); - } - catch (InvalidKeySpecException e) - { - throw new OperatorCreationException("cannot create key factory: " + e.getMessage(), e); - } - } - - // TODO: put somewhere public so cause easily accessed - private static class OpCertificateException - extends CertificateException - { - private Throwable cause; - - public OpCertificateException(String msg, Throwable cause) - { - super(msg); - - this.cause = cause; - } - - public Throwable getCause() - { - return cause; - } - } - - String getKeyAlgorithmName(ASN1ObjectIdentifier oid) - { - - String name = (String)symmetricKeyAlgNames.get(oid); - - if (name != null) - { - return name; - } - - return oid.getId(); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/pkcs/jcajce/JcaPKCS10CertificationRequestBuilder.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/pkcs/jcajce/JcaPKCS10CertificationRequestBuilder.java deleted file mode 100644 index 2e0000e08..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/pkcs/jcajce/JcaPKCS10CertificationRequestBuilder.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.spongycastle.pkcs.jcajce; - -import java.security.PublicKey; - -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.pkcs.PKCS10CertificationRequestBuilder; - -/** - * Extension of the PKCS#10 builder to support PublicKey and X500Principal objects. - */ -public class JcaPKCS10CertificationRequestBuilder - extends PKCS10CertificationRequestBuilder -{ - /** - * Create a PKCS#10 builder for the passed in subject and JCA public key. - * - * @param subject an X500Name containing the subject associated with the request we are building. - * @param publicKey a JCA public key that is to be associated with the request we are building. - */ - public JcaPKCS10CertificationRequestBuilder(X500Name subject, PublicKey publicKey) - { - super(subject, SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/tsp/cms/CMSTimeStampedData.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/tsp/cms/CMSTimeStampedData.java deleted file mode 100644 index 0b5cb6fda..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/tsp/cms/CMSTimeStampedData.java +++ /dev/null @@ -1,204 +0,0 @@ -package org.spongycastle.tsp.cms; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.MalformedURLException; - -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.DERIA5String; -import org.spongycastle.asn1.cms.AttributeTable; -import org.spongycastle.asn1.cms.CMSObjectIdentifiers; -import org.spongycastle.asn1.cms.ContentInfo; -import org.spongycastle.asn1.cms.Evidence; -import org.spongycastle.asn1.cms.TimeStampAndCRL; -import org.spongycastle.asn1.cms.TimeStampTokenEvidence; -import org.spongycastle.asn1.cms.TimeStampedData; -import org.spongycastle.cms.CMSException; -import org.spongycastle.operator.DigestCalculator; -import org.spongycastle.operator.DigestCalculatorProvider; -import org.spongycastle.operator.OperatorCreationException; -import org.spongycastle.tsp.TimeStampToken; - -public class CMSTimeStampedData -{ - private TimeStampedData timeStampedData; - private ContentInfo contentInfo; - private TimeStampDataUtil util; - - public CMSTimeStampedData(ContentInfo contentInfo) - { - this.initialize(contentInfo); - } - - public CMSTimeStampedData(InputStream in) - throws IOException - { - try - { - initialize(ContentInfo.getInstance(new ASN1InputStream(in).readObject())); - } - catch (ClassCastException e) - { - throw new IOException("Malformed content: " + e); - } - catch (IllegalArgumentException e) - { - throw new IOException("Malformed content: " + e); - } - } - - public CMSTimeStampedData(byte[] baseData) - throws IOException - { - this(new ByteArrayInputStream(baseData)); - } - - private void initialize(ContentInfo contentInfo) - { - this.contentInfo = contentInfo; - - if (CMSObjectIdentifiers.timestampedData.equals(contentInfo.getContentType())) - { - this.timeStampedData = TimeStampedData.getInstance(contentInfo.getContent()); - } - else - { - throw new IllegalArgumentException("Malformed content - type must be " + CMSObjectIdentifiers.timestampedData.getId()); - } - - util = new TimeStampDataUtil(this.timeStampedData); - } - - public byte[] calculateNextHash(DigestCalculator calculator) - throws CMSException - { - return util.calculateNextHash(calculator); - } - - /** - * Return a new timeStampedData object with the additional token attached. - * - * @throws CMSException - */ - public CMSTimeStampedData addTimeStamp(TimeStampToken token) - throws CMSException - { - TimeStampAndCRL[] timeStamps = util.getTimeStamps(); - TimeStampAndCRL[] newTimeStamps = new TimeStampAndCRL[timeStamps.length + 1]; - - System.arraycopy(timeStamps, 0, newTimeStamps, 0, timeStamps.length); - - newTimeStamps[timeStamps.length] = new TimeStampAndCRL(token.toCMSSignedData().toASN1Structure()); - - return new CMSTimeStampedData(new ContentInfo(CMSObjectIdentifiers.timestampedData, new TimeStampedData(timeStampedData.getDataUri(), timeStampedData.getMetaData(), timeStampedData.getContent(), new Evidence(new TimeStampTokenEvidence(newTimeStamps))))); - } - - public byte[] getContent() - { - if (timeStampedData.getContent() != null) - { - return timeStampedData.getContent().getOctets(); - } - - return null; - } - - public URL getDataUri() - throws MalformedURLException - { - DERIA5String dataURI = this.timeStampedData.getDataUri(); - - if (dataURI != null) - { - return new URL(dataURI.getString()); - } - - return null; - } - - public String getFileName() - { - return util.getFileName(); - } - - public String getMediaType() - { - return util.getMediaType(); - } - - public AttributeTable getOtherMetaData() - { - return util.getOtherMetaData(); - } - - public TimeStampToken[] getTimeStampTokens() - throws CMSException - { - return util.getTimeStampTokens(); - } - - /** - * Initialise the passed in calculator with the MetaData for this message, if it is - * required as part of the initial message imprint calculation. - * - * @param calculator the digest calculator to be initialised. - * @throws CMSException if the MetaData is required and cannot be processed - */ - public void initialiseMessageImprintDigestCalculator(DigestCalculator calculator) - throws CMSException - { - util.initialiseMessageImprintDigestCalculator(calculator); - } - - /** - * Returns an appropriately initialised digest calculator based on the message imprint algorithm - * described in the first time stamp in the TemporalData for this message. If the metadata is required - * to be included in the digest calculation, the returned calculator will be pre-initialised. - * - * @param calculatorProvider a provider of DigestCalculator objects. - * @return an initialised digest calculator. - * @throws OperatorCreationException if the provider is unable to create the calculator. - */ - public DigestCalculator getMessageImprintDigestCalculator(DigestCalculatorProvider calculatorProvider) - throws OperatorCreationException - { - return util.getMessageImprintDigestCalculator(calculatorProvider); - } - - /** - * Validate the digests present in the TimeStampTokens contained in the CMSTimeStampedData. - * - * @param calculatorProvider provider for digest calculators - * @param dataDigest the calculated data digest for the message - * @throws ImprintDigestInvalidException if an imprint digest fails to compare - * @throws CMSException if an exception occurs processing the message. - */ - public void validate(DigestCalculatorProvider calculatorProvider, byte[] dataDigest) - throws ImprintDigestInvalidException, CMSException - { - util.validate(calculatorProvider, dataDigest); - } - - /** - * Validate the passed in timestamp token against the tokens and data present in the message. - * - * @param calculatorProvider provider for digest calculators - * @param dataDigest the calculated data digest for the message. - * @param timeStampToken the timestamp token of interest. - * @throws ImprintDigestInvalidException if the token is not present in the message, or an imprint digest fails to compare. - * @throws CMSException if an exception occurs processing the message. - */ - public void validate(DigestCalculatorProvider calculatorProvider, byte[] dataDigest, TimeStampToken timeStampToken) - throws ImprintDigestInvalidException, CMSException - { - util.validate(calculatorProvider, dataDigest, timeStampToken); - } - - public byte[] getEncoded() - throws IOException - { - return contentInfo.getEncoded(); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/tsp/cms/CMSTimeStampedDataParser.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/tsp/cms/CMSTimeStampedDataParser.java deleted file mode 100644 index 2b1a695fa..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/tsp/cms/CMSTimeStampedDataParser.java +++ /dev/null @@ -1,207 +0,0 @@ -package org.spongycastle.tsp.cms; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; - -import org.spongycastle.asn1.BERTags; -import org.spongycastle.asn1.DERIA5String; -import org.spongycastle.asn1.cms.AttributeTable; -import org.spongycastle.asn1.cms.CMSObjectIdentifiers; -import org.spongycastle.asn1.cms.ContentInfoParser; -import org.spongycastle.asn1.cms.TimeStampedDataParser; -import org.spongycastle.cms.CMSContentInfoParser; -import org.spongycastle.cms.CMSException; -import org.spongycastle.operator.DigestCalculator; -import org.spongycastle.operator.DigestCalculatorProvider; -import org.spongycastle.operator.OperatorCreationException; -import org.spongycastle.tsp.TimeStampToken; -import org.spongycastle.util.io.Streams; - -public class CMSTimeStampedDataParser - extends CMSContentInfoParser -{ - private TimeStampedDataParser timeStampedData; - private TimeStampDataUtil util; - - public CMSTimeStampedDataParser(InputStream in) - throws CMSException - { - super(in); - - initialize(_contentInfo); - } - - public CMSTimeStampedDataParser(byte[] baseData) - throws CMSException - { - this(new ByteArrayInputStream(baseData)); - } - - private void initialize(ContentInfoParser contentInfo) - throws CMSException - { - try - { - if (CMSObjectIdentifiers.timestampedData.equals(contentInfo.getContentType())) - { - this.timeStampedData = TimeStampedDataParser.getInstance(contentInfo.getContent(BERTags.SEQUENCE)); - } - else - { - throw new IllegalArgumentException("Malformed content - type must be " + CMSObjectIdentifiers.timestampedData.getId()); - } - } - catch (IOException e) - { - throw new CMSException("parsing exception: " + e.getMessage(), e); - } - } - - public byte[] calculateNextHash(DigestCalculator calculator) - throws CMSException - { - return util.calculateNextHash(calculator); - } - - public InputStream getContent() - { - if (timeStampedData.getContent() != null) - { - return timeStampedData.getContent().getOctetStream(); - } - - return null; - } - - public URL getDataUri() - throws MalformedURLException - { - DERIA5String dataURI = this.timeStampedData.getDataUri(); - - if (dataURI != null) - { - return new URL(dataURI.getString()); - } - - return null; - } - - /** - * Initialise the passed in calculator with the MetaData for this message, if it is - * required as part of the initial message imprint calculation. - * - * @param calculator the digest calculator to be initialised. - * @throws CMSException if the MetaData is required and cannot be processed - */ - public void initialiseMessageImprintDigestCalculator(DigestCalculator calculator) - throws CMSException - { - util.initialiseMessageImprintDigestCalculator(calculator); - } - - /** - * Returns an appropriately initialised digest calculator based on the message imprint algorithm - * described in the first time stamp in the TemporalData for this message. If the metadata is required - * to be included in the digest calculation, the returned calculator will be pre-initialised. - * - * @param calculatorProvider a provider of DigestCalculator objects. - * @return an initialised digest calculator. - * @throws OperatorCreationException if the provider is unable to create the calculator. - */ - public DigestCalculator getMessageImprintDigestCalculator(DigestCalculatorProvider calculatorProvider) - throws OperatorCreationException - { - try - { - parseTimeStamps(); - } - catch (CMSException e) - { - throw new OperatorCreationException("unable to extract algorithm ID: " + e.getMessage(), e); - } - - return util.getMessageImprintDigestCalculator(calculatorProvider); - } - - public String getFileName() - { - return util.getFileName(); - } - - public String getMediaType() - { - return util.getMediaType(); - } - - public AttributeTable getOtherMetaData() - { - return util.getOtherMetaData(); - } - - public TimeStampToken[] getTimeStampTokens() - throws CMSException - { - parseTimeStamps(); - - return util.getTimeStampTokens(); - } - - /** - * Validate the digests present in the TimeStampTokens contained in the CMSTimeStampedData. - * - * @param calculatorProvider provider for digest calculators - * @param dataDigest the calculated data digest for the message - * @throws ImprintDigestInvalidException if an imprint digest fails to compare - * @throws CMSException if an exception occurs processing the message. - */ - public void validate(DigestCalculatorProvider calculatorProvider, byte[] dataDigest) - throws ImprintDigestInvalidException, CMSException - { - parseTimeStamps(); - - util.validate(calculatorProvider, dataDigest); - } - - /** - * Validate the passed in timestamp token against the tokens and data present in the message. - * - * @param calculatorProvider provider for digest calculators - * @param dataDigest the calculated data digest for the message. - * @param timeStampToken the timestamp token of interest. - * @throws ImprintDigestInvalidException if the token is not present in the message, or an imprint digest fails to compare. - * @throws CMSException if an exception occurs processing the message. - */ - public void validate(DigestCalculatorProvider calculatorProvider, byte[] dataDigest, TimeStampToken timeStampToken) - throws ImprintDigestInvalidException, CMSException - { - parseTimeStamps(); - - util.validate(calculatorProvider, dataDigest, timeStampToken); - } - - private void parseTimeStamps() - throws CMSException - { - try - { - if (util == null) - { - InputStream cont = this.getContent(); - - if (cont != null) - { - Streams.drain(cont); - } - - util = new TimeStampDataUtil(timeStampedData); - } - } - catch (IOException e) - { - throw new CMSException("unable to parse evidence block: " + e.getMessage(), e); - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/tsp/cms/CMSTimeStampedGenerator.java b/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/tsp/cms/CMSTimeStampedGenerator.java deleted file mode 100644 index 614a744b4..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.3/org/spongycastle/tsp/cms/CMSTimeStampedGenerator.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.spongycastle.tsp.cms; - -import java.net.URL; - -import org.spongycastle.asn1.ASN1Boolean; -import org.spongycastle.asn1.DERBoolean; -import org.spongycastle.asn1.DERIA5String; -import org.spongycastle.asn1.DERUTF8String; -import org.spongycastle.asn1.cms.Attributes; -import org.spongycastle.asn1.cms.MetaData; -import org.spongycastle.cms.CMSException; -import org.spongycastle.operator.DigestCalculator; -import org.spongycastle.util.Integers; - -public class CMSTimeStampedGenerator -{ - protected MetaData metaData; - protected URL dataUri; - - /** - * Set the dataURL to be included in message. - * - * @param dataUri URL for the data the initial message imprint digest is based on. - */ - public void setDataUri(URL dataUri) - { - this.dataUri = dataUri; - } - - /** - * Set the MetaData for the generated message. - * - * @param hashProtected true if the MetaData should be included in first imprint calculation, false otherwise. - * @param fileName optional file name, may be null. - * @param mediaType optional media type, may be null. - */ - public void setMetaData(boolean hashProtected, String fileName, String mediaType) - { - setMetaData(hashProtected, fileName, mediaType, null); - } - - /** - * Set the MetaData for the generated message. - * - * @param hashProtected true if the MetaData should be included in first imprint calculation, false otherwise. - * @param fileName optional file name, may be null. - * @param mediaType optional media type, may be null. - * @param attributes optional attributes, may be null. - */ - public void setMetaData(boolean hashProtected, String fileName, String mediaType, Attributes attributes) - { - DERUTF8String asn1FileName = null; - - if (fileName != null) - { - asn1FileName = new DERUTF8String(fileName); - } - - DERIA5String asn1MediaType = null; - - if (mediaType != null) - { - asn1MediaType = new DERIA5String(mediaType); - } - - setMetaData(hashProtected, asn1FileName, asn1MediaType, attributes); - } - - private void setMetaData(boolean hashProtected, DERUTF8String fileName, DERIA5String mediaType, Attributes attributes) - { - this.metaData = new MetaData(ASN1Boolean.getInstance(hashProtected), fileName, mediaType, attributes); - } - - /** - * Initialise the passed in calculator with the MetaData for this message, if it is - * required as part of the initial message imprint calculation. After initialisation the - * calculator can then be used to calculate the initial message imprint digest for the first - * timestamp. - * - * @param calculator the digest calculator to be initialised. - * @throws CMSException if the MetaData is required and cannot be processed - */ - public void initialiseMessageImprintDigestCalculator(DigestCalculator calculator) - throws CMSException - { - MetaDataUtil util = new MetaDataUtil(metaData); - - util.initialiseMessageImprintDigestCalculator(calculator); - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.4/org/spongycastle/cms/jcajce/JceKeyAgreeRecipientInfoGenerator.java b/extern/spongycastle/pkix/src/main/jdk1.4/org/spongycastle/cms/jcajce/JceKeyAgreeRecipientInfoGenerator.java deleted file mode 100644 index d808d5075..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.4/org/spongycastle/cms/jcajce/JceKeyAgreeRecipientInfoGenerator.java +++ /dev/null @@ -1,215 +0,0 @@ -package org.spongycastle.cms.jcajce; - -import java.security.GeneralSecurityException; -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; - -import javax.crypto.Cipher; -import javax.crypto.KeyAgreement; -import javax.crypto.SecretKey; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.cms.KeyAgreeRecipientIdentifier; -import org.spongycastle.asn1.cms.RecipientEncryptedKey; -import org.spongycastle.asn1.cms.RecipientKeyIdentifier; -import org.spongycastle.asn1.cms.ecc.MQVuserKeyingMaterial; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.cms.CMSAlgorithm; -import org.spongycastle.cms.CMSEnvelopedGenerator; -import org.spongycastle.cms.CMSException; -import org.spongycastle.cms.KeyAgreeRecipientInfoGenerator; -import org.spongycastle.jce.interfaces.ECPublicKey; -import org.spongycastle.jce.spec.ECParameterSpec; -import org.spongycastle.jce.spec.MQVPrivateKeySpec; -import org.spongycastle.jce.spec.MQVPublicKeySpec; -import org.spongycastle.operator.GenericKey; - -public class JceKeyAgreeRecipientInfoGenerator - extends KeyAgreeRecipientInfoGenerator -{ - private List recipientIDs = new ArrayList(); - private List recipientKeys = new ArrayList(); - private PublicKey senderPublicKey; - private PrivateKey senderPrivateKey; - - private EnvelopedDataHelper helper = new EnvelopedDataHelper(new DefaultJcaJceExtHelper()); - private SecureRandom random; - private KeyPair ephemeralKP; - - public JceKeyAgreeRecipientInfoGenerator(ASN1ObjectIdentifier keyAgreementOID, PrivateKey senderPrivateKey, PublicKey senderPublicKey, ASN1ObjectIdentifier keyEncryptionOID) - { - super(keyAgreementOID, SubjectPublicKeyInfo.getInstance(senderPublicKey.getEncoded()), keyEncryptionOID); - - this.senderPublicKey = senderPublicKey; - this.senderPrivateKey = senderPrivateKey; - } - - public JceKeyAgreeRecipientInfoGenerator setProvider(Provider provider) - { - this.helper = new EnvelopedDataHelper(new ProviderJcaJceExtHelper(provider)); - - return this; - } - - public JceKeyAgreeRecipientInfoGenerator setProvider(String providerName) - { - this.helper = new EnvelopedDataHelper(new NamedJcaJceExtHelper(providerName)); - - return this; - } - - public JceKeyAgreeRecipientInfoGenerator setSecureRandom(SecureRandom random) - { - this.random = random; - - return this; - } - - /** - * Add a recipient based on the passed in certificate's public key and its issuer and serial number. - * - * @param recipientCert recipient's certificate - * @return the current instance. - * @throws CertificateEncodingException if the necessary data cannot be extracted from the certificate. - */ - public JceKeyAgreeRecipientInfoGenerator addRecipient(X509Certificate recipientCert) - throws CertificateEncodingException - { - recipientIDs.add(new KeyAgreeRecipientIdentifier(CMSUtils.getIssuerAndSerialNumber(recipientCert))); - recipientKeys.add(recipientCert.getPublicKey()); - - return this; - } - - /** - * Add a recipient identified by the passed in subjectKeyID and the for the passed in public key. - * - * @param subjectKeyID identifier actual recipient will use to match the private key. - * @param publicKey the public key for encrypting the secret key. - * @return the current instance. - * @throws CertificateEncodingException - */ - public JceKeyAgreeRecipientInfoGenerator addRecipient(byte[] subjectKeyID, PublicKey publicKey) - throws CertificateEncodingException - { - recipientIDs.add(new KeyAgreeRecipientIdentifier(new RecipientKeyIdentifier(subjectKeyID))); - recipientKeys.add(publicKey); - - return this; - } - - public ASN1Sequence generateRecipientEncryptedKeys(AlgorithmIdentifier keyAgreeAlgorithm, AlgorithmIdentifier keyEncryptionAlgorithm, GenericKey contentEncryptionKey) - throws CMSException - { - init(keyAgreeAlgorithm.getAlgorithm()); - - PrivateKey senderPrivateKey = this.senderPrivateKey; - - ASN1ObjectIdentifier keyAgreementOID = keyAgreeAlgorithm.getAlgorithm(); - - if (keyAgreementOID.getId().equals(CMSEnvelopedGenerator.ECMQV_SHA1KDF)) - { - senderPrivateKey = new MQVPrivateKeySpec( - senderPrivateKey, ephemeralKP.getPrivate(), ephemeralKP.getPublic()); - } - - ASN1EncodableVector recipientEncryptedKeys = new ASN1EncodableVector(); - for (int i = 0; i != recipientIDs.size(); i++) - { - PublicKey recipientPublicKey = (PublicKey)recipientKeys.get(i); - KeyAgreeRecipientIdentifier karId = (KeyAgreeRecipientIdentifier)recipientIDs.get(i); - - if (keyAgreementOID.getId().equals(CMSEnvelopedGenerator.ECMQV_SHA1KDF)) - { - recipientPublicKey = new MQVPublicKeySpec(recipientPublicKey, recipientPublicKey); - } - - try - { - // Use key agreement to choose a wrap key for this recipient - KeyAgreement keyAgreement = helper.createKeyAgreement(keyAgreementOID); - keyAgreement.init(senderPrivateKey, random); - keyAgreement.doPhase(recipientPublicKey, true); - SecretKey keyEncryptionKey = keyAgreement.generateSecret(keyEncryptionAlgorithm.getAlgorithm().getId()); - - // Wrap the content encryption key with the agreement key - Cipher keyEncryptionCipher = helper.createCipher(keyEncryptionAlgorithm.getAlgorithm()); - - keyEncryptionCipher.init(Cipher.WRAP_MODE, keyEncryptionKey, random); - - byte[] encryptedKeyBytes = keyEncryptionCipher.wrap(helper.getJceKey(contentEncryptionKey)); - - ASN1OctetString encryptedKey = new DEROctetString(encryptedKeyBytes); - - recipientEncryptedKeys.add(new RecipientEncryptedKey(karId, encryptedKey)); - } - catch (GeneralSecurityException e) - { - throw new CMSException("cannot perform agreement step: " + e.getMessage(), e); - } - } - - return new DERSequence(recipientEncryptedKeys); - } - - protected ASN1Encodable getUserKeyingMaterial(AlgorithmIdentifier keyAgreeAlg) - throws CMSException - { - init(keyAgreeAlg.getAlgorithm()); - - if (ephemeralKP != null) - { - return new MQVuserKeyingMaterial( - createOriginatorPublicKey(SubjectPublicKeyInfo.getInstance(ephemeralKP.getPublic().getEncoded())), null); - } - - return null; - } - - private void init(ASN1ObjectIdentifier keyAgreementOID) - throws CMSException - { - if (random == null) - { - random = new SecureRandom(); - } - - if (keyAgreementOID.equals(CMSAlgorithm.ECMQV_SHA1KDF)) - { - if (ephemeralKP == null) - { - try - { - ECParameterSpec ecParamSpec = ((ECPublicKey)senderPublicKey).getParams(); - - KeyPairGenerator ephemKPG = helper.createKeyPairGenerator(keyAgreementOID); - - ephemKPG.initialize(ecParamSpec, random); - - ephemeralKP = ephemKPG.generateKeyPair(); - } - catch (InvalidAlgorithmParameterException e) - { - throw new CMSException( - "cannot determine MQV ephemeral key pair parameters from public key: " + e); - } - } - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.4/org/spongycastle/eac/jcajce/JcaPublicKeyConverter.java b/extern/spongycastle/pkix/src/main/jdk1.4/org/spongycastle/eac/jcajce/JcaPublicKeyConverter.java deleted file mode 100644 index 9c1801ec8..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.4/org/spongycastle/eac/jcajce/JcaPublicKeyConverter.java +++ /dev/null @@ -1,141 +0,0 @@ -package org.spongycastle.eac.jcajce; - -import java.math.BigInteger; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.PublicKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.RSAPublicKeySpec; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.eac.EACObjectIdentifiers; -import org.spongycastle.asn1.eac.ECDSAPublicKey; -import org.spongycastle.asn1.eac.PublicKeyDataObject; -import org.spongycastle.asn1.eac.RSAPublicKey; -import org.spongycastle.eac.EACException; -import org.spongycastle.jce.interfaces.ECPublicKey; -import org.spongycastle.jce.spec.ECParameterSpec; -import org.spongycastle.jce.spec.ECPublicKeySpec; -import org.spongycastle.math.ec.ECCurve; -import org.spongycastle.math.ec.ECFieldElement; -import org.spongycastle.math.ec.ECPoint; - -public class JcaPublicKeyConverter -{ - private EACHelper helper = new DefaultEACHelper(); - - public JcaPublicKeyConverter setProvider(String providerName) - { - this.helper = new NamedEACHelper(providerName); - - return this; - } - - public JcaPublicKeyConverter setProvider(Provider provider) - { - this.helper = new ProviderEACHelper(provider); - - return this; - } - - public PublicKey getKey(PublicKeyDataObject publicKeyDataObject) - throws EACException, InvalidKeySpecException - { - if (publicKeyDataObject.getUsage().on(EACObjectIdentifiers.id_TA_ECDSA)) - { - return getECPublicKeyPublicKey((ECDSAPublicKey)publicKeyDataObject); - } - else - { - RSAPublicKey pubKey = (RSAPublicKey)publicKeyDataObject; - RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(pubKey.getModulus(), pubKey.getPublicExponent()); - - try - { - KeyFactory factk = helper.createKeyFactory("RSA"); - - return factk.generatePublic(pubKeySpec); - } - catch (NoSuchProviderException e) - { - throw new EACException("cannot find provider: " + e.getMessage(), e); - } - catch (NoSuchAlgorithmException e) - { - throw new EACException("cannot find algorithm ECDSA: " + e.getMessage(), e); - } - } - } - - private PublicKey getECPublicKeyPublicKey(ECDSAPublicKey key) - throws EACException, InvalidKeySpecException - { - ECParameterSpec spec = getParams(key); - ECCurve curve = spec.getCurve(); - - ECPoint point = curve.decodePoint(key.getPublicPointY()); - ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, spec); - - KeyFactory factk; - try - { - factk = helper.createKeyFactory("ECDSA"); - } - catch (NoSuchProviderException e) - { - throw new EACException("cannot find provider: " + e.getMessage(), e); - } - catch (NoSuchAlgorithmException e) - { - throw new EACException("cannot find algorithm ECDSA: " + e.getMessage(), e); - } - - return factk.generatePublic(pubKeySpec); - } - - private ECParameterSpec getParams(ECDSAPublicKey key) - { - if (!key.hasParameters()) - { - throw new IllegalArgumentException("Public key does not contains EC Params"); - } - - BigInteger p = key.getPrimeModulusP(); - ECCurve.Fp curve = new ECCurve.Fp(p, key.getFirstCoefA(), key.getSecondCoefB()); - - ECPoint G = curve.decodePoint(key.getBasePointG()); - - BigInteger order = key.getOrderOfBasePointR(); - BigInteger coFactor = key.getCofactorF(); - - ECParameterSpec ecspec = new ECParameterSpec(curve, G, order, coFactor); - - return ecspec; - } - - public PublicKeyDataObject getPublicKeyDataObject(ASN1ObjectIdentifier usage, PublicKey publicKey) - { - if (publicKey instanceof java.security.interfaces.RSAPublicKey) - { - java.security.interfaces.RSAPublicKey pubKey = (java.security.interfaces.RSAPublicKey)publicKey; - - return new RSAPublicKey(usage, pubKey.getModulus(), pubKey.getPublicExponent()); - } - else - { - ECPublicKey pubKey = (ECPublicKey)publicKey; - ECParameterSpec params = pubKey.getParameters(); - - return new ECDSAPublicKey( - usage, - ((ECCurve.Fp)params.getCurve()).getQ(), - ((ECFieldElement.Fp)params.getCurve().getA()).toBigInteger(), ((ECFieldElement.Fp)params.getCurve().getB()).toBigInteger(), - params.getG().getEncoded(), - params.getN(), - pubKey.getQ().getEncoded(), - params.getH().intValue()); - } - } -} diff --git a/extern/spongycastle/pkix/src/main/jdk1.4/org/spongycastle/operator/jcajce/JcaAlgorithmParametersConverter.java b/extern/spongycastle/pkix/src/main/jdk1.4/org/spongycastle/operator/jcajce/JcaAlgorithmParametersConverter.java deleted file mode 100644 index a4de4911a..000000000 --- a/extern/spongycastle/pkix/src/main/jdk1.4/org/spongycastle/operator/jcajce/JcaAlgorithmParametersConverter.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.spongycastle.operator.jcajce; - - -import java.io.IOException; -import java.security.AlgorithmParameters; -import java.security.InvalidAlgorithmParameterException; -import java.security.spec.AlgorithmParameterSpec; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.pkcs.RSAESOAEPparams; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.operator.DefaultDigestAlgorithmIdentifierFinder; - -public class JcaAlgorithmParametersConverter -{ - public JcaAlgorithmParametersConverter() - { - } - - public AlgorithmIdentifier getAlgorithmIdentifier(ASN1ObjectIdentifier algId, AlgorithmParameters parameters) - throws InvalidAlgorithmParameterException - { - try - { - ASN1Encodable params = ASN1Primitive.fromByteArray(parameters.getEncoded()); - - return new AlgorithmIdentifier(algId, params); - } - catch (IOException e) - { - throw new InvalidAlgorithmParameterException("unable to encode parameters object: " + e.getMessage()); - } - } - - public AlgorithmIdentifier getAlgorithmIdentifier(ASN1ObjectIdentifier algorithm, AlgorithmParameterSpec algorithmSpec) - throws InvalidAlgorithmParameterException - { - throw new InvalidAlgorithmParameterException("unknown parameter spec passed."); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/dsa/DSASigner.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/dsa/DSASigner.java deleted file mode 100644 index 16fe1696a..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/dsa/DSASigner.java +++ /dev/null @@ -1,280 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.dsa; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.security.Signature; -import java.security.interfaces.DSAKey; -import java.security.spec.AlgorithmParameterSpec; - -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x509.X509ObjectIdentifiers; -import org.spongycastle.crypto.CipherParameters; -import org.spongycastle.crypto.DSA; -import org.spongycastle.crypto.Digest; -import org.spongycastle.crypto.digests.NullDigest; -import org.spongycastle.crypto.digests.SHA1Digest; -import org.spongycastle.crypto.digests.SHA224Digest; -import org.spongycastle.crypto.digests.SHA256Digest; -import org.spongycastle.crypto.digests.SHA384Digest; -import org.spongycastle.crypto.digests.SHA512Digest; -import org.spongycastle.crypto.params.ParametersWithRandom; - -public class DSASigner - extends Signature - implements PKCSObjectIdentifiers, X509ObjectIdentifiers -{ - private Digest digest; - private DSA signer; - private SecureRandom random; - - protected DSASigner( - Digest digest, - DSA signer) - { - super("DSA"); - this.digest = digest; - this.signer = signer; - } - - protected void engineInitVerify( - PublicKey publicKey) - throws InvalidKeyException - { - CipherParameters param; - -// if (publicKey instanceof GOST3410Key) -// { -// param = GOST3410Util.generatePublicKeyParameter(publicKey); -// } -// else if (publicKey instanceof DSAKey) - if (publicKey instanceof DSAKey) - { - param = DSAUtil.generatePublicKeyParameter(publicKey); - } - else - { - try - { - byte[] bytes = publicKey.getEncoded(); - - publicKey = new BCDSAPublicKey(SubjectPublicKeyInfo.getInstance(bytes)); - - if (publicKey instanceof DSAKey) - { - param = DSAUtil.generatePublicKeyParameter(publicKey); - } - else - { - throw new InvalidKeyException("can't recognise key type in DSA based signer"); - } - } - catch (Exception e) - { - throw new InvalidKeyException("can't recognise key type in DSA based signer"); - } - } - - digest.reset(); - signer.init(false, param); - } - - protected void engineInitSign( - PrivateKey privateKey, - SecureRandom random) - throws InvalidKeyException - { - this.random = random; - engineInitSign(privateKey); - } - - protected void engineInitSign( - PrivateKey privateKey) - throws InvalidKeyException - { - CipherParameters param; - -// if (privateKey instanceof GOST3410Key) -// { -// param = GOST3410Util.generatePrivateKeyParameter(privateKey); -// } -// else -// { - param = DSAUtil.generatePrivateKeyParameter(privateKey); -// } - - if (random != null) - { - param = new ParametersWithRandom(param, random); - } - - digest.reset(); - signer.init(true, param); - } - - protected void engineUpdate( - byte b) - throws SignatureException - { - digest.update(b); - } - - protected void engineUpdate( - byte[] b, - int off, - int len) - throws SignatureException - { - digest.update(b, off, len); - } - - protected byte[] engineSign() - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - try - { - BigInteger[] sig = signer.generateSignature(hash); - - return derEncode(sig[0], sig[1]); - } - catch (Exception e) - { - throw new SignatureException(e.toString()); - } - } - - protected boolean engineVerify( - byte[] sigBytes) - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - BigInteger[] sig; - - try - { - sig = derDecode(sigBytes); - } - catch (Exception e) - { - throw new SignatureException("error decoding signature bytes."); - } - - return signer.verifySignature(hash, sig[0], sig[1]); - } - - protected void engineSetParameter( - AlgorithmParameterSpec params) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated replaced with - */ - protected void engineSetParameter( - String param, - Object value) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated - */ - protected Object engineGetParameter( - String param) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - private byte[] derEncode( - BigInteger r, - BigInteger s) - throws IOException - { - ASN1Integer[] rs = new ASN1Integer[]{ new ASN1Integer(r), new ASN1Integer(s) }; - return new DERSequence(rs).getEncoded(ASN1Encoding.DER); - } - - private BigInteger[] derDecode( - byte[] encoding) - throws IOException - { - ASN1Sequence s = (ASN1Sequence)ASN1Primitive.fromByteArray(encoding); - return new BigInteger[]{ - ((ASN1Integer)s.getObjectAt(0)).getValue(), - ((ASN1Integer)s.getObjectAt(1)).getValue() - }; - } - - static public class stdDSA - extends DSASigner - { - public stdDSA() - { - super(new SHA1Digest(), new org.spongycastle.crypto.signers.DSASigner()); - } - } - - static public class dsa224 - extends DSASigner - { - public dsa224() - { - super(new SHA224Digest(), new org.spongycastle.crypto.signers.DSASigner()); - } - } - - static public class dsa256 - extends DSASigner - { - public dsa256() - { - super(new SHA256Digest(), new org.spongycastle.crypto.signers.DSASigner()); - } - } - - static public class dsa384 - extends DSASigner - { - public dsa384() - { - super(new SHA384Digest(), new org.spongycastle.crypto.signers.DSASigner()); - } - } - - static public class dsa512 - extends DSASigner - { - public dsa512() - { - super(new SHA512Digest(), new org.spongycastle.crypto.signers.DSASigner()); - } - } - - static public class noneDSA - extends DSASigner - { - public noneDSA() - { - super(new NullDigest(), new org.spongycastle.crypto.signers.DSASigner()); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/ecgost/SignatureSpi.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/ecgost/SignatureSpi.java deleted file mode 100644 index 54b83de7e..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/ecgost/SignatureSpi.java +++ /dev/null @@ -1,221 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.ecgost; - -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.security.spec.AlgorithmParameterSpec; - -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x509.X509ObjectIdentifiers; -import org.spongycastle.crypto.CipherParameters; -import org.spongycastle.crypto.DSA; -import org.spongycastle.crypto.Digest; -import org.spongycastle.crypto.digests.GOST3411Digest; -import org.spongycastle.crypto.params.ParametersWithRandom; -import org.spongycastle.crypto.signers.ECGOST3410Signer; -import org.spongycastle.jcajce.provider.asymmetric.util.ECUtil; -import org.spongycastle.jce.interfaces.ECKey; -import org.spongycastle.jce.interfaces.ECPublicKey; -import org.spongycastle.jce.interfaces.GOST3410Key; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.jcajce.provider.asymmetric.util.GOST3410Util; - -public class SignatureSpi - extends java.security.Signature - implements PKCSObjectIdentifiers, X509ObjectIdentifiers -{ - private Digest digest; - private DSA signer; - private SecureRandom appRandom; - - public SignatureSpi() - { - super("ECGOST3410"); - this.digest = new GOST3411Digest(); - this.signer = new ECGOST3410Signer(); - } - - protected void engineInitVerify( - PublicKey publicKey) - throws InvalidKeyException - { - CipherParameters param; - - if (publicKey instanceof ECPublicKey) - { - param = ECUtil.generatePublicKeyParameter(publicKey); - } - else if (publicKey instanceof GOST3410Key) - { - param = GOST3410Util.generatePublicKeyParameter(publicKey); - } - else - { - try - { - byte[] bytes = publicKey.getEncoded(); - - publicKey = BouncyCastleProvider.getPublicKey(SubjectPublicKeyInfo.getInstance(bytes)); - - if (publicKey instanceof ECPublicKey) - { - param = ECUtil.generatePublicKeyParameter(publicKey); - } - else - { - throw new InvalidKeyException("can't recognise key type in DSA based signer"); - } - } - catch (Exception e) - { - throw new InvalidKeyException("can't recognise key type in DSA based signer"); - } - } - - digest.reset(); - signer.init(false, param); - } - - protected void engineInitSign( - PrivateKey privateKey) - throws InvalidKeyException - { - CipherParameters param; - - if (privateKey instanceof ECKey) - { - param = ECUtil.generatePrivateKeyParameter(privateKey); - } - else - { - param = GOST3410Util.generatePrivateKeyParameter(privateKey); - } - - digest.reset(); - - if (appRandom != null) - { - signer.init(true, new ParametersWithRandom(param, appRandom)); - } - else - { - signer.init(true, param); - } - } - - protected void engineUpdate( - byte b) - throws SignatureException - { - digest.update(b); - } - - protected void engineUpdate( - byte[] b, - int off, - int len) - throws SignatureException - { - digest.update(b, off, len); - } - - protected byte[] engineSign() - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - try - { - byte[] sigBytes = new byte[64]; - BigInteger[] sig = signer.generateSignature(hash); - byte[] r = sig[0].toByteArray(); - byte[] s = sig[1].toByteArray(); - - if (s[0] != 0) - { - System.arraycopy(s, 0, sigBytes, 32 - s.length, s.length); - } - else - { - System.arraycopy(s, 1, sigBytes, 32 - (s.length - 1), s.length - 1); - } - - if (r[0] != 0) - { - System.arraycopy(r, 0, sigBytes, 64 - r.length, r.length); - } - else - { - System.arraycopy(r, 1, sigBytes, 64 - (r.length - 1), r.length - 1); - } - - return sigBytes; - } - catch (Exception e) - { - throw new SignatureException(e.toString()); - } - } - - protected boolean engineVerify( - byte[] sigBytes) - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - BigInteger[] sig; - - try - { - byte[] r = new byte[32]; - byte[] s = new byte[32]; - - System.arraycopy(sigBytes, 0, s, 0, 32); - - System.arraycopy(sigBytes, 32, r, 0, 32); - - sig = new BigInteger[2]; - sig[0] = new BigInteger(1, r); - sig[1] = new BigInteger(1, s); - } - catch (Exception e) - { - throw new SignatureException("error decoding signature bytes."); - } - - return signer.verifySignature(hash, sig[0], sig[1]); - } - - protected void engineSetParameter( - AlgorithmParameterSpec params) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated replaced with - */ - protected void engineSetParameter( - String param, - Object value) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated - */ - protected Object engineGetParameter( - String param) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/gost/SignatureSpi.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/gost/SignatureSpi.java deleted file mode 100644 index 65303d3d6..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/gost/SignatureSpi.java +++ /dev/null @@ -1,230 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.gost; - -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.security.spec.AlgorithmParameterSpec; - -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x509.X509ObjectIdentifiers; -import org.spongycastle.crypto.CipherParameters; -import org.spongycastle.crypto.DSA; -import org.spongycastle.crypto.Digest; -import org.spongycastle.crypto.digests.GOST3411Digest; -import org.spongycastle.crypto.params.ParametersWithRandom; -import org.spongycastle.crypto.signers.GOST3410Signer; -import org.spongycastle.jcajce.provider.asymmetric.util.ECUtil; -import org.spongycastle.jce.interfaces.ECKey; -import org.spongycastle.jce.interfaces.ECPublicKey; -import org.spongycastle.jce.interfaces.GOST3410Key; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.jcajce.provider.asymmetric.util.GOST3410Util; - -public class SignatureSpi - extends java.security.Signature - implements PKCSObjectIdentifiers, X509ObjectIdentifiers -{ - private Digest digest; - private DSA signer; - private SecureRandom random; - - public SignatureSpi() - { - super("GOST3410"); - this.digest = new GOST3411Digest(); - this.signer = new GOST3410Signer(); - } - - protected void engineInitVerify( - PublicKey publicKey) - throws InvalidKeyException - { - CipherParameters param; - - if (publicKey instanceof ECPublicKey) - { - param = ECUtil.generatePublicKeyParameter(publicKey); - } - else if (publicKey instanceof GOST3410Key) - { - param = GOST3410Util.generatePublicKeyParameter(publicKey); - } - else - { - try - { - byte[] bytes = publicKey.getEncoded(); - - publicKey = BouncyCastleProvider.getPublicKey(SubjectPublicKeyInfo.getInstance(bytes)); - - if (publicKey instanceof ECPublicKey) - { - param = ECUtil.generatePublicKeyParameter(publicKey); - } - else - { - throw new InvalidKeyException("can't recognise key type in DSA based signer"); - } - } - catch (Exception e) - { - throw new InvalidKeyException("can't recognise key type in DSA based signer"); - } - } - - digest.reset(); - signer.init(false, param); - } - - protected void engineInitSign( - PrivateKey privateKey, - SecureRandom random) - throws InvalidKeyException - { - this.random = random; - engineInitSign(privateKey); - } - - protected void engineInitSign( - PrivateKey privateKey) - throws InvalidKeyException - { - CipherParameters param; - - if (privateKey instanceof ECKey) - { - param = ECUtil.generatePrivateKeyParameter(privateKey); - } - else - { - param = GOST3410Util.generatePrivateKeyParameter(privateKey); - } - - digest.reset(); - - if (random != null) - { - signer.init(true, new ParametersWithRandom(param, random)); - } - else - { - signer.init(true, param); - } - } - - protected void engineUpdate( - byte b) - throws SignatureException - { - digest.update(b); - } - - protected void engineUpdate( - byte[] b, - int off, - int len) - throws SignatureException - { - digest.update(b, off, len); - } - - protected byte[] engineSign() - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - try - { - byte[] sigBytes = new byte[64]; - BigInteger[] sig = signer.generateSignature(hash); - byte[] r = sig[0].toByteArray(); - byte[] s = sig[1].toByteArray(); - - if (s[0] != 0) - { - System.arraycopy(s, 0, sigBytes, 32 - s.length, s.length); - } - else - { - System.arraycopy(s, 1, sigBytes, 32 - (s.length - 1), s.length - 1); - } - - if (r[0] != 0) - { - System.arraycopy(r, 0, sigBytes, 64 - r.length, r.length); - } - else - { - System.arraycopy(r, 1, sigBytes, 64 - (r.length - 1), r.length - 1); - } - - return sigBytes; - } - catch (Exception e) - { - throw new SignatureException(e.toString()); - } - } - - protected boolean engineVerify( - byte[] sigBytes) - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - BigInteger[] sig; - - try - { - byte[] r = new byte[32]; - byte[] s = new byte[32]; - - System.arraycopy(sigBytes, 0, s, 0, 32); - - System.arraycopy(sigBytes, 32, r, 0, 32); - - sig = new BigInteger[2]; - sig[0] = new BigInteger(1, r); - sig[1] = new BigInteger(1, s); - } - catch (Exception e) - { - throw new SignatureException("error decoding signature bytes."); - } - - return signer.verifySignature(hash, sig[0], sig[1]); - } - - protected void engineSetParameter( - AlgorithmParameterSpec params) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated replaced with - */ - protected void engineSetParameter( - String param, - Object value) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated - */ - protected Object engineGetParameter( - String param) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/rsa/DigestSignatureSpi.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/rsa/DigestSignatureSpi.java deleted file mode 100644 index 2807ed4d0..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/rsa/DigestSignatureSpi.java +++ /dev/null @@ -1,368 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.rsa; - -import java.io.IOException; -import java.security.AlgorithmParameters; -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SignatureException; -import java.security.Signature; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.AlgorithmParameterSpec; - -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.nist.NISTObjectIdentifiers; -import org.spongycastle.asn1.oiw.OIWObjectIdentifiers; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.DigestInfo; -import org.spongycastle.crypto.AsymmetricBlockCipher; -import org.spongycastle.crypto.CipherParameters; -import org.spongycastle.crypto.Digest; -import org.spongycastle.crypto.digests.MD2Digest; -import org.spongycastle.crypto.digests.MD4Digest; -import org.spongycastle.crypto.digests.MD5Digest; -import org.spongycastle.crypto.digests.NullDigest; -import org.spongycastle.crypto.digests.RIPEMD128Digest; -import org.spongycastle.crypto.digests.RIPEMD160Digest; -import org.spongycastle.crypto.digests.RIPEMD256Digest; -import org.spongycastle.crypto.digests.SHA1Digest; -import org.spongycastle.crypto.digests.SHA224Digest; -import org.spongycastle.crypto.digests.SHA256Digest; -import org.spongycastle.crypto.digests.SHA384Digest; -import org.spongycastle.crypto.digests.SHA512Digest; -import org.spongycastle.crypto.encodings.PKCS1Encoding; -import org.spongycastle.crypto.engines.RSABlindedEngine; - -public class DigestSignatureSpi - extends Signature -{ - private Digest digest; - private AsymmetricBlockCipher cipher; - private AlgorithmIdentifier algId; - - // care - this constructor is actually used by outside organisations - protected DigestSignatureSpi( - Digest digest, - AsymmetricBlockCipher cipher) - { - super(digest.getAlgorithmName() + "withRSA"); - this.digest = digest; - this.cipher = cipher; - this.algId = null; - } - - // care - this constructor is actually used by outside organisations - protected DigestSignatureSpi( - ASN1ObjectIdentifier objId, - Digest digest, - AsymmetricBlockCipher cipher) - { - super(digest.getAlgorithmName() + "withRSA"); - this.digest = digest; - this.cipher = cipher; - this.algId = new AlgorithmIdentifier(objId, DERNull.INSTANCE); - } - - protected void engineInitVerify( - PublicKey publicKey) - throws InvalidKeyException - { - if (!(publicKey instanceof RSAPublicKey)) - { - throw new InvalidKeyException("Supplied key (" + getType(publicKey) + ") is not a RSAPublicKey instance"); - } - - CipherParameters param = RSAUtil.generatePublicKeyParameter((RSAPublicKey)publicKey); - - digest.reset(); - cipher.init(false, param); - } - - protected void engineInitSign( - PrivateKey privateKey) - throws InvalidKeyException - { - if (!(privateKey instanceof RSAPrivateKey)) - { - throw new InvalidKeyException("Supplied key (" + getType(privateKey) + ") is not a RSAPrivateKey instance"); - } - - CipherParameters param = RSAUtil.generatePrivateKeyParameter((RSAPrivateKey)privateKey); - - digest.reset(); - - cipher.init(true, param); - } - - private String getType( - Object o) - { - if (o == null) - { - return null; - } - - return o.getClass().getName(); - } - - protected void engineUpdate( - byte b) - throws SignatureException - { - digest.update(b); - } - - protected void engineUpdate( - byte[] b, - int off, - int len) - throws SignatureException - { - digest.update(b, off, len); - } - - protected byte[] engineSign() - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - try - { - byte[] bytes = derEncode(hash); - - return cipher.processBlock(bytes, 0, bytes.length); - } - catch (ArrayIndexOutOfBoundsException e) - { - throw new SignatureException("key too small for signature type"); - } - catch (Exception e) - { - throw new SignatureException(e.toString()); - } - } - - protected boolean engineVerify( - byte[] sigBytes) - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - byte[] sig; - byte[] expected; - - try - { - sig = cipher.processBlock(sigBytes, 0, sigBytes.length); - - expected = derEncode(hash); - } - catch (Exception e) - { - return false; - } - - if (sig.length == expected.length) - { - for (int i = 0; i < sig.length; i++) - { - if (sig[i] != expected[i]) - { - return false; - } - } - } - else if (sig.length == expected.length - 2) // NULL left out - { - int sigOffset = sig.length - hash.length - 2; - int expectedOffset = expected.length - hash.length - 2; - - expected[1] -= 2; // adjust lengths - expected[3] -= 2; - - for (int i = 0; i < hash.length; i++) - { - if (sig[sigOffset + i] != expected[expectedOffset + i]) // check hash - { - return false; - } - } - - for (int i = 0; i < sigOffset; i++) - { - if (sig[i] != expected[i]) // check header less NULL - { - return false; - } - } - } - else - { - return false; - } - - return true; - } - - protected void engineSetParameter( - AlgorithmParameterSpec params) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated replaced with - */ - protected void engineSetParameter( - String param, - Object value) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated - */ - protected Object engineGetParameter( - String param) - { - return null; - } - - protected AlgorithmParameters engineGetParameters() - { - return null; - } - - private byte[] derEncode( - byte[] hash) - throws IOException - { - if (algId == null) - { - // For raw RSA, the DigestInfo must be prepared externally - return hash; - } - - DigestInfo dInfo = new DigestInfo(algId, hash); - - return dInfo.getEncoded(ASN1Encoding.DER); - } - - static public class SHA1 - extends DigestSignatureSpi - { - public SHA1() - { - super(OIWObjectIdentifiers.idSHA1, new SHA1Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class SHA224 - extends DigestSignatureSpi - { - public SHA224() - { - super(NISTObjectIdentifiers.id_sha224, new SHA224Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class SHA256 - extends DigestSignatureSpi - { - public SHA256() - { - super(NISTObjectIdentifiers.id_sha256, new SHA256Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class SHA384 - extends DigestSignatureSpi - { - public SHA384() - { - super(NISTObjectIdentifiers.id_sha384, new SHA384Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class SHA512 - extends DigestSignatureSpi - { - public SHA512() - { - super(NISTObjectIdentifiers.id_sha512, new SHA512Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class MD2 - extends DigestSignatureSpi - { - public MD2() - { - super(PKCSObjectIdentifiers.md2, new MD2Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class MD4 - extends DigestSignatureSpi - { - public MD4() - { - super(PKCSObjectIdentifiers.md4, new MD4Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class MD5 - extends DigestSignatureSpi - { - public MD5() - { - super(PKCSObjectIdentifiers.md5, new MD5Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class RIPEMD160 - extends DigestSignatureSpi - { - public RIPEMD160() - { - super(TeleTrusTObjectIdentifiers.ripemd160, new RIPEMD160Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class RIPEMD128 - extends DigestSignatureSpi - { - public RIPEMD128() - { - super(TeleTrusTObjectIdentifiers.ripemd128, new RIPEMD128Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class RIPEMD256 - extends DigestSignatureSpi - { - public RIPEMD256() - { - super(TeleTrusTObjectIdentifiers.ripemd256, new RIPEMD256Digest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class noneRSA - extends DigestSignatureSpi - { - public noneRSA() - { - super(new NullDigest(), new PKCS1Encoding(new RSABlindedEngine())); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/rsa/ISOSignatureSpi.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/rsa/ISOSignatureSpi.java deleted file mode 100644 index e87ccff1e..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/rsa/ISOSignatureSpi.java +++ /dev/null @@ -1,143 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.rsa; - -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SignatureException; -import java.security.Signature; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.AlgorithmParameterSpec; - -import org.spongycastle.crypto.AsymmetricBlockCipher; -import org.spongycastle.crypto.CipherParameters; -import org.spongycastle.crypto.Digest; -import org.spongycastle.crypto.digests.MD5Digest; -import org.spongycastle.crypto.digests.RIPEMD160Digest; -import org.spongycastle.crypto.digests.SHA1Digest; -import org.spongycastle.crypto.engines.RSABlindedEngine; -import org.spongycastle.crypto.signers.ISO9796d2Signer; - -public class ISOSignatureSpi - extends Signature -{ - private ISO9796d2Signer signer; - - protected ISOSignatureSpi( - Digest digest, - AsymmetricBlockCipher cipher) - { - super(digest.getAlgorithmName() + "withRSA/ISO9796-2"); - signer = new ISO9796d2Signer(cipher, digest, true); - } - - protected void engineInitVerify( - PublicKey publicKey) - throws InvalidKeyException - { - CipherParameters param = RSAUtil.generatePublicKeyParameter((RSAPublicKey)publicKey); - - signer.init(false, param); - } - - protected void engineInitSign( - PrivateKey privateKey) - throws InvalidKeyException - { - CipherParameters param = RSAUtil.generatePrivateKeyParameter((RSAPrivateKey)privateKey); - - signer.init(true, param); - } - - protected void engineUpdate( - byte b) - throws SignatureException - { - signer.update(b); - } - - protected void engineUpdate( - byte[] b, - int off, - int len) - throws SignatureException - { - signer.update(b, off, len); - } - - protected byte[] engineSign() - throws SignatureException - { - try - { - byte[] sig = signer.generateSignature(); - - return sig; - } - catch (Exception e) - { - throw new SignatureException(e.toString()); - } - } - - protected boolean engineVerify( - byte[] sigBytes) - throws SignatureException - { - boolean yes = signer.verifySignature(sigBytes); - - return yes; - } - - protected void engineSetParameter( - AlgorithmParameterSpec params) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated replaced with - */ - protected void engineSetParameter( - String param, - Object value) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated - */ - protected Object engineGetParameter( - String param) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - static public class SHA1WithRSAEncryption - extends ISOSignatureSpi - { - public SHA1WithRSAEncryption() - { - super(new SHA1Digest(), new RSABlindedEngine()); - } - } - - static public class MD5WithRSAEncryption - extends ISOSignatureSpi - { - public MD5WithRSAEncryption() - { - super(new MD5Digest(), new RSABlindedEngine()); - } - } - - static public class RIPEMD160WithRSAEncryption - extends ISOSignatureSpi - { - public RIPEMD160WithRSAEncryption() - { - super(new RIPEMD160Digest(), new RSABlindedEngine()); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/util/DSABase.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/util/DSABase.java deleted file mode 100644 index 9cf4485f9..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/util/DSABase.java +++ /dev/null @@ -1,129 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.util; - -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.Signature; -import java.security.SignatureException; -import java.security.spec.AlgorithmParameterSpec; - -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.x509.X509ObjectIdentifiers; -import org.spongycastle.crypto.DSA; -import org.spongycastle.crypto.Digest; - -public abstract class DSABase - extends Signature - implements PKCSObjectIdentifiers, X509ObjectIdentifiers -{ - protected Digest digest; - protected DSA signer; - protected DSAEncoder encoder; - private SecureRandom appRandom; - - protected DSABase( - String name, - Digest digest, - DSA signer, - DSAEncoder encoder) - { - super(name); - - this.digest = digest; - this.signer = signer; - this.encoder = encoder; - } - - protected void engineInitSign( - PrivateKey privateKey) - throws InvalidKeyException - { - doEngineInitSign(privateKey, appRandom); - } - - protected void engineUpdate( - byte b) - throws SignatureException - { - digest.update(b); - } - - protected void engineUpdate( - byte[] b, - int off, - int len) - throws SignatureException - { - digest.update(b, off, len); - } - - protected byte[] engineSign() - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - try - { - BigInteger[] sig = signer.generateSignature(hash); - - return encoder.encode(sig[0], sig[1]); - } - catch (Exception e) - { - throw new SignatureException(e.toString()); - } - } - - protected boolean engineVerify( - byte[] sigBytes) - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - BigInteger[] sig; - - try - { - sig = encoder.decode(sigBytes); - } - catch (Exception e) - { - throw new SignatureException("error decoding signature bytes."); - } - - return signer.verifySignature(hash, sig[0], sig[1]); - } - - protected void engineSetParameter( - AlgorithmParameterSpec params) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated replaced with - */ - protected void engineSetParameter( - String param, - Object value) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated - */ - protected Object engineGetParameter( - String param) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - protected abstract void doEngineInitSign(PrivateKey privateKey, SecureRandom random) - throws InvalidKeyException; -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/x509/CertificateFactory.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/x509/CertificateFactory.java deleted file mode 100644 index 75d4eb269..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/x509/CertificateFactory.java +++ /dev/null @@ -1,397 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.x509; - -import java.io.IOException; -import java.io.InputStream; -import java.io.PushbackInputStream; -import java.security.cert.CRL; -import java.security.cert.CRLException; -import java.security.cert.CertPath; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactorySpi; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1Set; -import org.spongycastle.asn1.ASN1TaggedObject; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.pkcs.SignedData; -import org.spongycastle.asn1.x509.Certificate; -import org.spongycastle.asn1.x509.CertificateList; -import org.spongycastle.jce.provider.X509CRLObject; -import org.spongycastle.jce.provider.X509CertificateObject; - -/** - * class for dealing with X509 certificates. - *

- * At the moment this will deal with "-----BEGIN CERTIFICATE-----" to "-----END CERTIFICATE-----" - * base 64 encoded certs, as well as the BER binaries of certificates and some classes of PKCS#7 - * objects. - */ -public class CertificateFactory - extends CertificateFactorySpi -{ - private static final PEMUtil PEM_CERT_PARSER = new PEMUtil("CERTIFICATE"); - private static final PEMUtil PEM_CRL_PARSER = new PEMUtil("CRL"); - - private ASN1Set sData = null; - private int sDataObjectCount = 0; - private InputStream currentStream = null; - - private ASN1Set sCrlData = null; - private int sCrlDataObjectCount = 0; - private InputStream currentCrlStream = null; - - private java.security.cert.Certificate readDERCertificate( - ASN1InputStream dIn) - throws IOException, CertificateParsingException - { - ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); - - if (seq.size() > 1 - && seq.getObjectAt(0) instanceof ASN1ObjectIdentifier) - { - if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) - { - sData = SignedData.getInstance(ASN1Sequence.getInstance( - (ASN1TaggedObject)seq.getObjectAt(1), true)).getCertificates(); - - return getCertificate(); - } - } - - return new X509CertificateObject( - Certificate.getInstance(seq)); - } - - private java.security.cert.Certificate getCertificate() - throws CertificateParsingException - { - if (sData != null) - { - while (sDataObjectCount < sData.size()) - { - Object obj = sData.getObjectAt(sDataObjectCount++); - - if (obj instanceof ASN1Sequence) - { - return new X509CertificateObject( - Certificate.getInstance(obj)); - } - } - } - - return null; - } - - private java.security.cert.Certificate readPEMCertificate( - InputStream in) - throws IOException, CertificateParsingException - { - ASN1Sequence seq = PEM_CERT_PARSER.readPEMObject(in); - - if (seq != null) - { - return new X509CertificateObject( - Certificate.getInstance(seq)); - } - - return null; - } - - protected CRL createCRL(CertificateList c) - throws CRLException - { - return new X509CRLObject(c); - } - - private CRL readPEMCRL( - InputStream in) - throws IOException, CRLException - { - ASN1Sequence seq = PEM_CRL_PARSER.readPEMObject(in); - - if (seq != null) - { - return createCRL( - CertificateList.getInstance(seq)); - } - - return null; - } - - private CRL readDERCRL( - ASN1InputStream aIn) - throws IOException, CRLException - { - ASN1Sequence seq = (ASN1Sequence)aIn.readObject(); - - if (seq.size() > 1 - && seq.getObjectAt(0) instanceof ASN1ObjectIdentifier) - { - if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) - { - sCrlData = SignedData.getInstance(ASN1Sequence.getInstance( - (ASN1TaggedObject)seq.getObjectAt(1), true)).getCRLs(); - - return getCRL(); - } - } - - return createCRL( - CertificateList.getInstance(seq)); - } - - private CRL getCRL() - throws CRLException - { - if (sCrlData == null || sCrlDataObjectCount >= sCrlData.size()) - { - return null; - } - - return createCRL( - CertificateList.getInstance( - sCrlData.getObjectAt(sCrlDataObjectCount++))); - } - - /** - * Generates a certificate object and initializes it with the data - * read from the input stream inStream. - */ - public java.security.cert.Certificate engineGenerateCertificate( - InputStream in) - throws CertificateException - { - if (currentStream == null) - { - currentStream = in; - sData = null; - sDataObjectCount = 0; - } - else if (currentStream != in) // reset if input stream has changed - { - currentStream = in; - sData = null; - sDataObjectCount = 0; - } - - try - { - if (sData != null) - { - if (sDataObjectCount != sData.size()) - { - return getCertificate(); - } - else - { - sData = null; - sDataObjectCount = 0; - return null; - } - } - - PushbackInputStream pis = new PushbackInputStream(in); - int tag = pis.read(); - - if (tag == -1) - { - return null; - } - - pis.unread(tag); - - if (tag != 0x30) // assume ascii PEM encoded. - { - return readPEMCertificate(pis); - } - else - { - return readDERCertificate(new ASN1InputStream(pis)); - } - } - catch (Exception e) - { - throw new ExCertificateException(e); - } - } - - /** - * Returns a (possibly empty) collection view of the certificates - * read from the given input stream inStream. - */ - public Collection engineGenerateCertificates( - InputStream inStream) - throws CertificateException - { - java.security.cert.Certificate cert; - List certs = new ArrayList(); - - while ((cert = engineGenerateCertificate(inStream)) != null) - { - certs.add(cert); - } - - return certs; - } - - /** - * Generates a certificate revocation list (CRL) object and initializes - * it with the data read from the input stream inStream. - */ - public CRL engineGenerateCRL( - InputStream inStream) - throws CRLException - { - if (currentCrlStream == null) - { - currentCrlStream = inStream; - sCrlData = null; - sCrlDataObjectCount = 0; - } - else if (currentCrlStream != inStream) // reset if input stream has changed - { - currentCrlStream = inStream; - sCrlData = null; - sCrlDataObjectCount = 0; - } - - try - { - if (sCrlData != null) - { - if (sCrlDataObjectCount != sCrlData.size()) - { - return getCRL(); - } - else - { - sCrlData = null; - sCrlDataObjectCount = 0; - return null; - } - } - - PushbackInputStream pis = new PushbackInputStream(inStream); - int tag = pis.read(); - - if (tag == -1) - { - return null; - } - - pis.unread(tag); - - if (tag != 0x30) // assume ascii PEM encoded. - { - return readPEMCRL(pis); - } - else - { // lazy evaluate to help processing of large CRLs - return readDERCRL(new ASN1InputStream(pis, true)); - } - } - catch (CRLException e) - { - throw e; - } - catch (Exception e) - { - throw new CRLException(e.toString()); - } - } - - /** - * Returns a (possibly empty) collection view of the CRLs read from - * the given input stream inStream. - * - * The inStream may contain a sequence of DER-encoded CRLs, or - * a PKCS#7 CRL set. This is a PKCS#7 SignedData object, with the - * only signficant field being crls. In particular the signature - * and the contents are ignored. - */ - public Collection engineGenerateCRLs( - InputStream inStream) - throws CRLException - { - CRL crl; - List crls = new ArrayList(); - - while ((crl = engineGenerateCRL(inStream)) != null) - { - crls.add(crl); - } - - return crls; - } - - public Iterator engineGetCertPathEncodings() - { - return null; // TODO: PKIXCertPath.certPathEncodings.iterator(); - } - - public CertPath engineGenerateCertPath( - InputStream inStream) - throws CertificateException - { - return engineGenerateCertPath(inStream, "PkiPath"); - } - - public CertPath engineGenerateCertPath( - InputStream inStream, - String encoding) - throws CertificateException - { - return new PKIXCertPath(inStream, encoding); - } - - public CertPath engineGenerateCertPath( - List certificates) - throws CertificateException - { - Iterator iter = certificates.iterator(); - Object obj; - while (iter.hasNext()) - { - obj = iter.next(); - if (obj != null) - { - if (!(obj instanceof X509Certificate)) - { - throw new CertificateException("list contains non X509Certificate object while creating CertPath\n" + obj.toString()); - } - } - } - return new PKIXCertPath(certificates); - } - - private class ExCertificateException - extends CertificateException - { - private Throwable cause; - - public ExCertificateException(Throwable cause) - { - this.cause = cause; - } - - public ExCertificateException(String msg, Throwable cause) - { - super(msg); - - this.cause = cause; - } - - public Throwable getCause() - { - return cause; - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/x509/PKIXCertPath.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/x509/PKIXCertPath.java deleted file mode 100644 index a2462a9a0..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/x509/PKIXCertPath.java +++ /dev/null @@ -1,379 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.x509; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStreamWriter; -import java.security.NoSuchProviderException; -import java.security.cert.CertPath; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -import org.spongycastle.jce.X509Principal; -import org.spongycastle.jce.PrincipalUtil; -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.DERSet; -import org.spongycastle.asn1.pkcs.ContentInfo; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.pkcs.SignedData; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.util.io.pem.PemObject; -import org.spongycastle.util.io.pem.PemWriter; - -/** - * CertPath implementation for X.509 certificates. - *
- **/ -public class PKIXCertPath - extends CertPath -{ - static final List certPathEncodings; - - static - { - List encodings = new ArrayList(); - encodings.add("PkiPath"); - encodings.add("PEM"); - encodings.add("PKCS7"); - certPathEncodings = Collections.unmodifiableList(encodings); - } - - private List certificates; - - /** - * @param certs - */ - private List sortCerts( - List certs) - { - try - { - if (certs.size() < 2) - { - return certs; - } - - X509Principal issuer = PrincipalUtil.getIssuerX509Principal(((X509Certificate)certs.get(0))); - boolean okay = true; - - for (int i = 1; i != certs.size(); i++) - { - X509Certificate cert = (X509Certificate)certs.get(i); - - if (issuer.equals(PrincipalUtil.getSubjectX509Principal(cert))) - { - issuer = PrincipalUtil.getIssuerX509Principal(((X509Certificate)certs.get(i))); - } - else - { - okay = false; - break; - } - } - - if (okay) - { - return certs; - } - - // find end-entity cert - List retList = new ArrayList(certs.size()); - List orig = new ArrayList(certs); - - for (int i = 0; i < certs.size(); i++) - { - X509Certificate cert = (X509Certificate)certs.get(i); - boolean found = false; - - X509Principal subject = PrincipalUtil.getSubjectX509Principal(cert); - - for (int j = 0; j != certs.size(); j++) - { - X509Certificate c = (X509Certificate)certs.get(j); - if (PrincipalUtil.getIssuerX509Principal(c).equals(subject)) - { - found = true; - break; - } - } - - if (!found) - { - retList.add(cert); - certs.remove(i); - } - } - - // can only have one end entity cert - something's wrong, give up. - if (retList.size() > 1) - { - return orig; - } - - for (int i = 0; i != retList.size(); i++) - { - issuer = PrincipalUtil.getIssuerX509Principal(((X509Certificate)retList.get(i))); - - for (int j = 0; j < certs.size(); j++) - { - X509Certificate c = (X509Certificate)certs.get(j); - if (issuer.equals(PrincipalUtil.getSubjectX509Principal(c))) - { - retList.add(c); - certs.remove(j); - break; - } - } - } - - // make sure all certificates are accounted for. - if (certs.size() > 0) - { - return orig; - } - - return retList; - } - catch (Exception e) - { - return certs; - } - } - - PKIXCertPath(List certificates) - { - super("X.509"); - this.certificates = sortCerts(new ArrayList(certificates)); - } - - /** - * Creates a CertPath of the specified type. - * This constructor is protected because most users should use - * a CertificateFactory to create CertPaths. - **/ - PKIXCertPath( - InputStream inStream, - String encoding) - throws CertificateException - { - super("X.509"); - try - { - if (encoding.equalsIgnoreCase("PkiPath")) - { - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Primitive derObject = derInStream.readObject(); - if (!(derObject instanceof ASN1Sequence)) - { - throw new CertificateException("input stream does not contain a ASN1 SEQUENCE while reading PkiPath encoded data to load CertPath"); - } - Enumeration e = ((ASN1Sequence)derObject).getObjects(); - certificates = new ArrayList(); - CertificateFactory certFactory = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME); - while (e.hasMoreElements()) - { - ASN1Encodable element = (ASN1Encodable)e.nextElement(); - byte[] encoded = element.toASN1Primitive().getEncoded(ASN1Encoding.DER); - certificates.add(0, certFactory.generateCertificate( - new ByteArrayInputStream(encoded))); - } - } - else if (encoding.equalsIgnoreCase("PKCS7") || encoding.equalsIgnoreCase("PEM")) - { - inStream = new BufferedInputStream(inStream); - certificates = new ArrayList(); - CertificateFactory certFactory= CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME); - Certificate cert; - while ((cert = certFactory.generateCertificate(inStream)) != null) - { - certificates.add(cert); - } - } - else - { - throw new CertificateException("unsupported encoding: " + encoding); - } - } - catch (IOException ex) - { - throw new CertificateException("IOException throw while decoding CertPath:\n" + ex.toString()); - } - catch (NoSuchProviderException ex) - { - throw new CertificateException("BouncyCastle provider not found while trying to get a CertificateFactory:\n" + ex.toString()); - } - - this.certificates = sortCerts(certificates); - } - - /** - * Returns an iteration of the encodings supported by this - * certification path, with the default encoding - * first. Attempts to modify the returned Iterator via its - * remove method result in an UnsupportedOperationException. - * - * @return an Iterator over the names of the supported encodings (as Strings) - **/ - public Iterator getEncodings() - { - return certPathEncodings.iterator(); - } - - /** - * Returns the encoded form of this certification path, using - * the default encoding. - * - * @return the encoded bytes - * @exception java.security.cert.CertificateEncodingException if an encoding error occurs - **/ - public byte[] getEncoded() - throws CertificateEncodingException - { - Iterator iter = getEncodings(); - if (iter.hasNext()) - { - Object enc = iter.next(); - if (enc instanceof String) - { - return getEncoded((String)enc); - } - } - return null; - } - - /** - * Returns the encoded form of this certification path, using - * the specified encoding. - * - * @param encoding the name of the encoding to use - * @return the encoded bytes - * @exception java.security.cert.CertificateEncodingException if an encoding error - * occurs or the encoding requested is not supported - * - **/ - public byte[] getEncoded(String encoding) - throws CertificateEncodingException - { - if (encoding.equalsIgnoreCase("PkiPath")) - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - ListIterator iter = certificates.listIterator(certificates.size()); - while (iter.hasPrevious()) - { - v.add(toASN1Object((X509Certificate)iter.previous())); - } - - return toDEREncoded(new DERSequence(v)); - } - else if (encoding.equalsIgnoreCase("PKCS7")) - { - ContentInfo encInfo = new ContentInfo(PKCSObjectIdentifiers.data, null); - - ASN1EncodableVector v = new ASN1EncodableVector(); - for (int i = 0; i != certificates.size(); i++) - { - v.add(toASN1Object((X509Certificate)certificates.get(i))); - } - - SignedData sd = new SignedData( - new ASN1Integer(1), - new DERSet(), - encInfo, - new DERSet(v), - null, - new DERSet()); - - return toDEREncoded(new ContentInfo( - PKCSObjectIdentifiers.signedData, sd)); - } - else if (encoding.equalsIgnoreCase("PEM")) - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - PemWriter pWrt = new PemWriter(new OutputStreamWriter(bOut)); - - try - { - for (int i = 0; i != certificates.size(); i++) - { - pWrt.writeObject(new PemObject("CERTIFICATE", ((X509Certificate)certificates.get(i)).getEncoded())); - } - - pWrt.close(); - } - catch (Exception e) - { - throw new CertificateEncodingException("can't encode certificate for PEM encoded path"); - } - - return bOut.toByteArray(); - } - else - { - throw new CertificateEncodingException("unsupported encoding: " + encoding); - } - } - - /** - * Returns the list of certificates in this certification - * path. The List returned must be immutable and thread-safe. - * - * @return an immutable List of Certificates (may be empty, but not null) - **/ - public List getCertificates() - { - return Collections.unmodifiableList(new ArrayList(certificates)); - } - - /** - * Return a DERObject containing the encoded certificate. - * - * @param cert the X509Certificate object to be encoded - * - * @return the DERObject - **/ - private ASN1Primitive toASN1Object( - X509Certificate cert) - throws CertificateEncodingException - { - try - { - return new ASN1InputStream(cert.getEncoded()).readObject(); - } - catch (Exception e) - { - throw new CertificateEncodingException("Exception while encoding certificate: " + e.toString()); - } - } - - private byte[] toDEREncoded(ASN1Encodable obj) - throws CertificateEncodingException - { - try - { - return obj.toASN1Primitive().getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CertificateEncodingException("Exception thrown: " + e); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/x509/SignatureUtil.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/x509/SignatureUtil.java deleted file mode 100644 index e3dc0876b..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jcajce/provider/asymmetric/x509/SignatureUtil.java +++ /dev/null @@ -1,107 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.x509; - -import java.io.IOException; -import java.security.AlgorithmParameters; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Signature; -import java.security.SignatureException; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1Null; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.spongycastle.asn1.nist.NISTObjectIdentifiers; -import org.spongycastle.asn1.oiw.OIWObjectIdentifiers; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.pkcs.RSASSAPSSparams; -import org.spongycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x9.X9ObjectIdentifiers; - -class SignatureUtil -{ - private static final ASN1Null derNull = new DERNull(); - - static String getSignatureName( - AlgorithmIdentifier sigAlgId) - { - ASN1Encodable params = sigAlgId.getParameters(); - - if (params != null && !derNull.equals(params)) - { - if (sigAlgId.getAlgorithm().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) - { - RSASSAPSSparams rsaParams = RSASSAPSSparams.getInstance(params); - - return getDigestAlgName(rsaParams.getHashAlgorithm().getAlgorithm()) + "withRSAandMGF1"; - } - if (sigAlgId.getAlgorithm().equals(X9ObjectIdentifiers.ecdsa_with_SHA2)) - { - ASN1Sequence ecDsaParams = ASN1Sequence.getInstance(params); - - return getDigestAlgName((ASN1ObjectIdentifier)ecDsaParams.getObjectAt(0)) + "withECDSA"; - } - } - - return sigAlgId.getAlgorithm().getId(); - } - - /** - * Return the digest algorithm using one of the standard JCA string - * representations rather the the algorithm identifier (if possible). - */ - private static String getDigestAlgName( - ASN1ObjectIdentifier digestAlgOID) - { - if (PKCSObjectIdentifiers.md5.equals(digestAlgOID)) - { - return "MD5"; - } - else if (OIWObjectIdentifiers.idSHA1.equals(digestAlgOID)) - { - return "SHA1"; - } - else if (NISTObjectIdentifiers.id_sha224.equals(digestAlgOID)) - { - return "SHA224"; - } - else if (NISTObjectIdentifiers.id_sha256.equals(digestAlgOID)) - { - return "SHA256"; - } - else if (NISTObjectIdentifiers.id_sha384.equals(digestAlgOID)) - { - return "SHA384"; - } - else if (NISTObjectIdentifiers.id_sha512.equals(digestAlgOID)) - { - return "SHA512"; - } - else if (TeleTrusTObjectIdentifiers.ripemd128.equals(digestAlgOID)) - { - return "RIPEMD128"; - } - else if (TeleTrusTObjectIdentifiers.ripemd160.equals(digestAlgOID)) - { - return "RIPEMD160"; - } - else if (TeleTrusTObjectIdentifiers.ripemd256.equals(digestAlgOID)) - { - return "RIPEMD256"; - } - else if (CryptoProObjectIdentifiers.gostR3411.equals(digestAlgOID)) - { - return "GOST3411"; - } - else - { - return digestAlgOID.getId(); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/MultiCertStoreParameters.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/MultiCertStoreParameters.java deleted file mode 100644 index 8762494b2..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/MultiCertStoreParameters.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.spongycastle.jce; - -import java.security.cert.CertStoreParameters; -import java.util.Collection; - -public class MultiCertStoreParameters - implements CertStoreParameters -{ - private Collection certStores; - private boolean searchAllStores; - - /** - * Create a parameters object which specifies searching of all the passed in stores. - * - * @param certStores CertStores making up the multi CertStore - */ - public MultiCertStoreParameters(Collection certStores) - { - this(certStores, true); - } - - /** - * Create a parameters object which can be to used to make a multi store made up - * of the passed in CertStores. If the searchAllStores parameter is false, any search on - * the multi-store will terminate as soon as a search query produces a result. - * - * @param certStores CertStores making up the multi CertStore - * @param searchAllStores true if all CertStores should be searched on request, false if a result - * should be returned on the first successful CertStore query. - */ - public MultiCertStoreParameters(Collection certStores, boolean searchAllStores) - { - this.certStores = certStores; - this.searchAllStores = searchAllStores; - } - - public Collection getCertStores() - { - return certStores; - } - - public boolean getSearchAllStores() - { - return searchAllStores; - } - - public Object clone() - { - return this; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/netscape/NetscapeCertRequest.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/netscape/NetscapeCertRequest.java deleted file mode 100644 index 45d7975a6..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/netscape/NetscapeCertRequest.java +++ /dev/null @@ -1,296 +0,0 @@ -package org.spongycastle.jce.netscape; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.security.InvalidKeyException; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.Signature; -import java.security.SignatureException; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.X509EncodedKeySpec; - -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Object; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.DERBitString; -import org.spongycastle.asn1.DERIA5String; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; - -/** - * - * - * Handles NetScape certificate request (KEYGEN), these are constructed as: - *


- *   SignedPublicKeyAndChallenge ::= SEQUENCE {
- *     publicKeyAndChallenge    PublicKeyAndChallenge,
- *     signatureAlgorithm       AlgorithmIdentifier,
- *     signature                BIT STRING
- *   }
- * 
- * - * PublicKey's encoded-format has to be X.509. - * - **/ -public class NetscapeCertRequest - extends ASN1Object -{ - AlgorithmIdentifier sigAlg; - AlgorithmIdentifier keyAlg; - byte sigBits []; - String challenge; - DERBitString content; - PublicKey pubkey ; - - private static ASN1Sequence getReq( - byte[] r) - throws IOException - { - ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(r)); - - return ASN1Sequence.getInstance(aIn.readObject()); - } - - public NetscapeCertRequest( - byte[] req) - throws IOException - { - this(getReq(req)); - } - - public NetscapeCertRequest (ASN1Sequence spkac) - { - try - { - - // - // SignedPublicKeyAndChallenge ::= SEQUENCE { - // publicKeyAndChallenge PublicKeyAndChallenge, - // signatureAlgorithm AlgorithmIdentifier, - // signature BIT STRING - // } - // - if (spkac.size() != 3) - { - throw new IllegalArgumentException("invalid SPKAC (size):" - + spkac.size()); - } - - sigAlg = new AlgorithmIdentifier((ASN1Sequence)spkac - .getObjectAt(1)); - sigBits = ((DERBitString)spkac.getObjectAt(2)).getBytes(); - - // - // PublicKeyAndChallenge ::= SEQUENCE { - // spki SubjectPublicKeyInfo, - // challenge IA5STRING - // } - // - ASN1Sequence pkac = (ASN1Sequence)spkac.getObjectAt(0); - - if (pkac.size() != 2) - { - throw new IllegalArgumentException("invalid PKAC (len): " - + pkac.size()); - } - - challenge = ((DERIA5String)pkac.getObjectAt(1)).getString(); - - //this could be dangerous, as ASN.1 decoding/encoding - //could potentially alter the bytes - content = new DERBitString(pkac); - - SubjectPublicKeyInfo pubkeyinfo = new SubjectPublicKeyInfo( - (ASN1Sequence)pkac.getObjectAt(0)); - - X509EncodedKeySpec xspec = new X509EncodedKeySpec(new DERBitString( - pubkeyinfo).getBytes()); - - keyAlg = pubkeyinfo.getAlgorithmId(); - pubkey = KeyFactory.getInstance(keyAlg.getObjectId().getId(), "SC") - .generatePublic(xspec); - - } - catch (Exception e) - { - throw new IllegalArgumentException(e.toString()); - } - } - - public NetscapeCertRequest( - String challenge, - AlgorithmIdentifier signing_alg, - PublicKey pub_key) throws NoSuchAlgorithmException, - InvalidKeySpecException, NoSuchProviderException, IOException - { - - this.challenge = challenge; - sigAlg = signing_alg; - pubkey = pub_key; - - ASN1EncodableVector content_der = new ASN1EncodableVector(); - content_der.add(getKeySpec()); - //content_der.add(new SubjectPublicKeyInfo(sigAlg, new RSAPublicKeyStructure(pubkey.getModulus(), pubkey.getPublicExponent()).getDERObject())); - content_der.add(new DERIA5String(challenge)); - - content = new DERBitString(new DERSequence(content_der)); - } - - public String getChallenge() - { - return challenge; - } - - public void setChallenge(String value) - { - challenge = value; - } - - public AlgorithmIdentifier getSigningAlgorithm() - { - return sigAlg; - } - - public void setSigningAlgorithm(AlgorithmIdentifier value) - { - sigAlg = value; - } - - public AlgorithmIdentifier getKeyAlgorithm() - { - return keyAlg; - } - - public void setKeyAlgorithm(AlgorithmIdentifier value) - { - keyAlg = value; - } - - public PublicKey getPublicKey() - { - return pubkey; - } - - public void setPublicKey(PublicKey value) - { - pubkey = value; - } - - public boolean verify(String challenge) throws NoSuchAlgorithmException, - InvalidKeyException, SignatureException, NoSuchProviderException - { - if (!challenge.equals(this.challenge)) - { - return false; - } - - // - // Verify the signature .. shows the response was generated - // by someone who knew the associated private key - // - Signature sig = Signature.getInstance(sigAlg.getObjectId().getId(), - "SC"); - sig.initVerify(pubkey); - sig.update(content.getBytes()); - - return sig.verify(sigBits); - } - - public void sign(PrivateKey priv_key) throws NoSuchAlgorithmException, - InvalidKeyException, SignatureException, NoSuchProviderException, - InvalidKeySpecException - { - sign(priv_key, null); - } - - public void sign(PrivateKey priv_key, SecureRandom rand) - throws NoSuchAlgorithmException, InvalidKeyException, - SignatureException, NoSuchProviderException, - InvalidKeySpecException - { - Signature sig = Signature.getInstance(sigAlg.getAlgorithm().getId(), - "SC"); - - if (rand != null) - { - sig.initSign(priv_key); - } - else - { - sig.initSign(priv_key); - } - - ASN1EncodableVector pkac = new ASN1EncodableVector(); - - pkac.add(getKeySpec()); - pkac.add(new DERIA5String(challenge)); - - try - { - sig.update(new DERSequence(pkac).getEncoded(ASN1Encoding.DER)); - } - catch (IOException ioe) - { - throw new SignatureException(ioe.getMessage()); - } - - sigBits = sig.sign(); - } - - private ASN1Primitive getKeySpec() throws NoSuchAlgorithmException, - InvalidKeySpecException, NoSuchProviderException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - ASN1Primitive obj = null; - try - { - - baos.write(pubkey.getEncoded()); - baos.close(); - - ASN1InputStream derin = new ASN1InputStream( - new ByteArrayInputStream(baos.toByteArray())); - - obj = derin.readObject(); - } - catch (IOException ioe) - { - throw new InvalidKeySpecException(ioe.getMessage()); - } - return obj; - } - - public ASN1Primitive toASN1Primitive() - { - ASN1EncodableVector spkac = new ASN1EncodableVector(); - ASN1EncodableVector pkac = new ASN1EncodableVector(); - - try - { - pkac.add(getKeySpec()); - } - catch (Exception e) - { - //ignore - } - - pkac.add(new DERIA5String(challenge)); - - spkac.add(new DERSequence(pkac)); - spkac.add(sigAlg); - spkac.add(new DERBitString(sigBits)); - - return new DERSequence(spkac); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/AnnotatedException.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/AnnotatedException.java deleted file mode 100644 index 8c115d984..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/AnnotatedException.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.spongycastle.jce.provider; - -public class AnnotatedException - extends Exception -{ - private Throwable _underlyingException; - - AnnotatedException(String string, Throwable e) - { - super(string); - - _underlyingException = e; - } - - AnnotatedException(String string) - { - this(string, null); - } - - Throwable getUnderlyingException() - { - return _underlyingException; - } - - public Throwable getCause() - { - return _underlyingException; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/BouncyCastleProvider.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/BouncyCastleProvider.java deleted file mode 100644 index 107e4c9f9..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/BouncyCastleProvider.java +++ /dev/null @@ -1,274 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.io.IOException; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.PublicKey; -import java.util.HashMap; -import java.util.Map; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.pkcs.PrivateKeyInfo; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.jcajce.provider.config.ConfigurableProvider; -import org.spongycastle.jcajce.provider.config.ProviderConfiguration; -import org.spongycastle.jcajce.provider.util.AlgorithmProvider; -import org.spongycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; - -/** - * To add the provider at runtime use: - *
- * import java.security.Security;
- * import org.spongycastle.jce.provider.BouncyCastleProvider;
- *
- * Security.addProvider(new BouncyCastleProvider());
- * 
- * The provider can also be configured as part of your environment via - * static registration by adding an entry to the java.security properties - * file (found in $JAVA_HOME/jre/lib/security/java.security, where - * $JAVA_HOME is the location of your JDK/JRE distribution). You'll find - * detailed instructions in the file but basically it comes down to adding - * a line: - *
- * 
- *    security.provider.<n>=org.spongycastle.jce.provider.BouncyCastleProvider
- * 
- * 
- * Where <n> is the preference you want the provider at (1 being the - * most preferred). - *

Note: JCE algorithm names should be upper-case only so the case insensitive - * test for getInstance works. - */ -public final class BouncyCastleProvider extends Provider - implements ConfigurableProvider -{ - private static String info = "BouncyCastle Security Provider v1.51"; - - public static final String PROVIDER_NAME = "SC"; - - public static final ProviderConfiguration CONFIGURATION = new BouncyCastleProviderConfiguration(); - - private static final Map keyInfoConverters = new HashMap(); - - /* - * Configurable symmetric ciphers - */ - private static final String SYMMETRIC_PACKAGE = "org.spongycastle.jcajce.provider.symmetric."; - - private static final String[] SYMMETRIC_GENERIC = - { - "PBEPBKDF2", "PBEPKCS12" - }; - - private static final String[] SYMMETRIC_MACS = - { - "SipHash" - }; - - private static final String[] SYMMETRIC_CIPHERS = - { - "AES", "ARC4", "Blowfish", "Camellia", "CAST5", "CAST6", "ChaCha", "DES", "DESede", - "GOST28147", "Grainv1", "Grain128", "HC128", "HC256", "IDEA", "Noekeon", "RC2", "RC5", - "RC6", "Rijndael", "Salsa20", "SEED", "Serpent", "Shacal2", "Skipjack", "TEA", "Twofish", "Threefish", - "VMPC", "VMPCKSA3", "XTEA", "XSalsa20" - }; - - /* - * Configurable asymmetric ciphers - */ - private static final String ASYMMETRIC_PACKAGE = "org.spongycastle.jcajce.provider.asymmetric."; - - // this one is required for GNU class path - it needs to be loaded first as the - // later ones configure it. - private static final String[] ASYMMETRIC_GENERIC = - { - "X509", "IES" - }; - - private static final String[] ASYMMETRIC_CIPHERS = - { - "DSA", "DH", "EC", "RSA", "GOST", "ECGOST", "ElGamal", "DSTU4145" - }; - - /* - * Configurable digests - */ - private static final String DIGEST_PACKAGE = "org.spongycastle.jcajce.provider.digest."; - private static final String[] DIGESTS = - { - "GOST3411", "MD2", "MD4", "MD5", "SHA1", "RIPEMD128", "RIPEMD160", "RIPEMD256", "RIPEMD320", "SHA224", "SHA256", "SHA384", "SHA512", "SHA3", "Skein", "SM3", "Tiger", "Whirlpool" - }; - - /* - * Configurable keystores - */ - private static final String KEYSTORE_PACKAGE = "org.spongycastle.jcajce.provider.keystore."; - private static final String[] KEYSTORES = - { - "SC", "PKCS12" - }; - - /** - * Construct a new provider. This should only be required when - * using runtime registration of the provider using the - * Security.addProvider() mechanism. - */ - public BouncyCastleProvider() - { - super(PROVIDER_NAME, 1.51, info); - - setup(); - } - - private void setup() - { - loadAlgorithms(DIGEST_PACKAGE, DIGESTS); - - loadAlgorithms(SYMMETRIC_PACKAGE, SYMMETRIC_GENERIC); - - loadAlgorithms(SYMMETRIC_PACKAGE, SYMMETRIC_MACS); - - loadAlgorithms(SYMMETRIC_PACKAGE, SYMMETRIC_CIPHERS); - - loadAlgorithms(ASYMMETRIC_PACKAGE, ASYMMETRIC_GENERIC); - - loadAlgorithms(ASYMMETRIC_PACKAGE, ASYMMETRIC_CIPHERS); - - loadAlgorithms(KEYSTORE_PACKAGE, KEYSTORES); - - // - // X509Store - // - put("X509Store.CERTIFICATE/COLLECTION", "org.spongycastle.jce.provider.X509StoreCertCollection"); - put("X509Store.ATTRIBUTECERTIFICATE/COLLECTION", "org.spongycastle.jce.provider.X509StoreAttrCertCollection"); - put("X509Store.CRL/COLLECTION", "org.spongycastle.jce.provider.X509StoreCRLCollection"); - put("X509Store.CERTIFICATEPAIR/COLLECTION", "org.spongycastle.jce.provider.X509StoreCertPairCollection"); - - put("X509Store.CERTIFICATE/LDAP", "org.spongycastle.jce.provider.X509StoreLDAPCerts"); - put("X509Store.CRL/LDAP", "org.spongycastle.jce.provider.X509StoreLDAPCRLs"); - put("X509Store.ATTRIBUTECERTIFICATE/LDAP", "org.spongycastle.jce.provider.X509StoreLDAPAttrCerts"); - put("X509Store.CERTIFICATEPAIR/LDAP", "org.spongycastle.jce.provider.X509StoreLDAPCertPairs"); - - // - // X509StreamParser - // - put("X509StreamParser.CERTIFICATE", "org.spongycastle.jce.provider.X509CertParser"); - put("X509StreamParser.ATTRIBUTECERTIFICATE", "org.spongycastle.jce.provider.X509AttrCertParser"); - put("X509StreamParser.CRL", "org.spongycastle.jce.provider.X509CRLParser"); - put("X509StreamParser.CERTIFICATEPAIR", "org.spongycastle.jce.provider.X509CertPairParser"); - - // - // cipher engines - // - put("Cipher.BROKENPBEWITHMD5ANDDES", "org.spongycastle.jce.provider.BrokenJCEBlockCipher$BrokePBEWithMD5AndDES"); - - put("Cipher.BROKENPBEWITHSHA1ANDDES", "org.spongycastle.jce.provider.BrokenJCEBlockCipher$BrokePBEWithSHA1AndDES"); - - - put("Cipher.OLDPBEWITHSHAANDTWOFISH-CBC", "org.spongycastle.jce.provider.BrokenJCEBlockCipher$OldPBEWithSHAAndTwofish"); - - // Certification Path API - put("CertPathValidator.RFC3281", "org.spongycastle.jce.provider.PKIXAttrCertPathValidatorSpi"); - put("CertPathBuilder.RFC3281", "org.spongycastle.jce.provider.PKIXAttrCertPathBuilderSpi"); - put("CertPathValidator.RFC3280", "org.spongycastle.jce.provider.PKIXCertPathValidatorSpi"); - put("CertPathBuilder.RFC3280", "org.spongycastle.jce.provider.PKIXCertPathBuilderSpi"); - put("CertPathValidator.PKIX", "org.spongycastle.jce.provider.PKIXCertPathValidatorSpi"); - put("CertPathBuilder.PKIX", "org.spongycastle.jce.provider.PKIXCertPathBuilderSpi"); - put("CertStore.Collection", "org.spongycastle.jce.provider.CertStoreCollectionSpi"); - put("CertStore.LDAP", "org.spongycastle.jce.provider.X509LDAPCertStoreSpi"); - put("CertStore.Multi", "org.spongycastle.jce.provider.MultiCertStoreSpi"); - put("Alg.Alias.CertStore.X509LDAP", "LDAP"); - } - - private void loadAlgorithms(String packageName, String[] names) - { - for (int i = 0; i != names.length; i++) - { - Class clazz = null; - try - { - ClassLoader loader = this.getClass().getClassLoader(); - - if (loader != null) - { - clazz = loader.loadClass(packageName + names[i] + "$Mappings"); - } - else - { - clazz = Class.forName(packageName + names[i] + "$Mappings"); - } - } - catch (ClassNotFoundException e) - { - // ignore - } - - if (clazz != null) - { - try - { - ((AlgorithmProvider)clazz.newInstance()).configure(this); - } - catch (Exception e) - { // this should never ever happen!! - throw new InternalError("cannot create instance of " - + packageName + names[i] + "$Mappings : " + e); - } - } - } - } - - public void setParameter(String parameterName, Object parameter) - { - synchronized (CONFIGURATION) - { - ((BouncyCastleProviderConfiguration)CONFIGURATION).setParameter(parameterName, parameter); - } - } - - public boolean hasAlgorithm(String type, String name) - { - return containsKey(type + "." + name) || containsKey("Alg.Alias." + type + "." + name); - } - - public void addAlgorithm(String key, String value) - { - if (containsKey(key)) - { - throw new IllegalStateException("duplicate provider key (" + key + ") found"); - } - - put(key, value); - } - - public void addKeyInfoConverter(ASN1ObjectIdentifier oid, AsymmetricKeyInfoConverter keyInfoConverter) - { - keyInfoConverters.put(oid, keyInfoConverter); - } - - public static PublicKey getPublicKey(SubjectPublicKeyInfo publicKeyInfo) - throws IOException - { - AsymmetricKeyInfoConverter converter = (AsymmetricKeyInfoConverter)keyInfoConverters.get(publicKeyInfo.getAlgorithm().getAlgorithm()); - - if (converter == null) - { - return null; - } - - return converter.generatePublic(publicKeyInfo); - } - - public static PrivateKey getPrivateKey(PrivateKeyInfo privateKeyInfo) - throws IOException - { - AsymmetricKeyInfoConverter converter = (AsymmetricKeyInfoConverter)keyInfoConverters.get(privateKeyInfo.getPrivateKeyAlgorithm().getAlgorithm()); - - if (converter == null) - { - return null; - } - - return converter.generatePrivate(privateKeyInfo); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/BouncyCastleProviderConfiguration.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/BouncyCastleProviderConfiguration.java deleted file mode 100644 index bfeedb2ad..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/BouncyCastleProviderConfiguration.java +++ /dev/null @@ -1,108 +0,0 @@ -package org.spongycastle.jce.provider; - -import javax.crypto.spec.DHParameterSpec; - -import org.spongycastle.jcajce.provider.config.ConfigurableProvider; -import org.spongycastle.jcajce.provider.config.ProviderConfiguration; -import org.spongycastle.jce.spec.ECParameterSpec; - -class BouncyCastleProviderConfiguration - implements ProviderConfiguration -{ - private volatile ECParameterSpec ecImplicitCaParams; - private volatile Object dhDefaultParams; - - void setParameter(String parameterName, Object parameter) - { - SecurityManager securityManager = System.getSecurityManager(); - - if (parameterName.equals(ConfigurableProvider.THREAD_LOCAL_EC_IMPLICITLY_CA)) - { - ECParameterSpec curveSpec; - - if (parameter instanceof ECParameterSpec || parameter == null) - { - curveSpec = (ECParameterSpec)parameter; - } - else - { - throw new IllegalArgumentException("not a valid ECParameterSpec"); - } - - ecImplicitCaParams = (ECParameterSpec)curveSpec; - } - else if (parameterName.equals(ConfigurableProvider.EC_IMPLICITLY_CA)) - { - if (parameter instanceof ECParameterSpec || parameter == null) - { - ecImplicitCaParams = (ECParameterSpec)parameter; - } - else // assume java.security.spec - { - throw new IllegalArgumentException("not a valid ECParameterSpec"); - } - } - else if (parameterName.equals(ConfigurableProvider.THREAD_LOCAL_DH_DEFAULT_PARAMS)) - { - Object dhSpec; - - - if (parameter instanceof DHParameterSpec || parameter instanceof DHParameterSpec[] || parameter == null) - { - dhSpec = parameter; - } - else - { - throw new IllegalArgumentException("not a valid DHParameterSpec"); - } - - dhDefaultParams = dhSpec; - } - else if (parameterName.equals(ConfigurableProvider.DH_DEFAULT_PARAMS)) - { - - if (parameter instanceof DHParameterSpec || parameter instanceof DHParameterSpec[] || parameter == null) - { - dhDefaultParams = parameter; - } - else - { - throw new IllegalArgumentException("not a valid DHParameterSpec or DHParameterSpec[]"); - } - } - } - - public ECParameterSpec getEcImplicitlyCa() - { - return ecImplicitCaParams; - } - - public DHParameterSpec getDHDefaultParameters(int keySize) - { - Object params = dhDefaultParams; - - if (params instanceof DHParameterSpec) - { - DHParameterSpec spec = (DHParameterSpec)params; - - if (spec.getP().bitLength() == keySize) - { - return spec; - } - } - else if (params instanceof DHParameterSpec[]) - { - DHParameterSpec[] specs = (DHParameterSpec[])params; - - for (int i = 0; i != specs.length; i++) - { - if (specs[i].getP().bitLength() == keySize) - { - return specs[i]; - } - } - } - - return null; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/CertStoreCollectionSpi.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/CertStoreCollectionSpi.java deleted file mode 100644 index 19a361ae4..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/CertStoreCollectionSpi.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.security.InvalidAlgorithmParameterException; -import java.security.cert.CRL; -import java.security.cert.CRLSelector; -import java.security.cert.CertSelector; -import java.security.cert.CertStoreException; -import java.security.cert.CertStoreParameters; -import java.security.cert.CertStoreSpi; -import java.security.cert.Certificate; -import java.security.cert.CollectionCertStoreParameters; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -public class CertStoreCollectionSpi extends CertStoreSpi -{ - private CollectionCertStoreParameters params; - - public CertStoreCollectionSpi(CertStoreParameters params) - throws InvalidAlgorithmParameterException - { - super(params); - - if (!(params instanceof CollectionCertStoreParameters)) - { - throw new InvalidAlgorithmParameterException( "org.spongycastle.jce.provider.CertStoreCollectionSpi: parameter must be a CollectionCertStoreParameters object\n" + params.toString() ); - } - - this.params = (CollectionCertStoreParameters)params; - } - - public Collection engineGetCertificates( - CertSelector selector) - throws CertStoreException - { - Set col = new HashSet(); - Iterator iter = params.getCollection().iterator(); - - if (selector == null) - { - while (iter.hasNext()) - { - Object obj = iter.next(); - - if (obj instanceof Certificate) - { - col.add(obj); - } - } - } - else - { - while (iter.hasNext()) - { - Object obj = iter.next(); - - if ((obj instanceof Certificate) && selector.match((Certificate)obj)) - { - col.add(obj); - } - } - } - - return col; - } - - - public Collection engineGetCRLs( - CRLSelector selector) - throws CertStoreException - { - Set col = new HashSet(); - Iterator iter = params.getCollection().iterator(); - - if (selector == null) - { - while (iter.hasNext()) - { - Object obj = iter.next(); - - if (obj instanceof CRL) - { - col.add(obj); - } - } - } - else - { - while (iter.hasNext()) - { - Object obj = iter.next(); - - if ((obj instanceof CRL) && selector.match((CRL)obj)) - { - col.add(obj); - } - } - } - - return col; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/MultiCertStoreSpi.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/MultiCertStoreSpi.java deleted file mode 100644 index c6db1bdbd..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/MultiCertStoreSpi.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.spongycastle.jce.provider; - -import org.spongycastle.jce.MultiCertStoreParameters; - -import java.security.InvalidAlgorithmParameterException; -import java.security.cert.CRLSelector; -import java.security.cert.CertSelector; -import java.security.cert.CertStore; -import java.security.cert.CertStoreException; -import java.security.cert.CertStoreParameters; -import java.security.cert.CertStoreSpi; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -public class MultiCertStoreSpi - extends CertStoreSpi -{ - private MultiCertStoreParameters params; - - public MultiCertStoreSpi(CertStoreParameters params) - throws InvalidAlgorithmParameterException - { - super(params); - - if (!(params instanceof MultiCertStoreParameters)) - { - throw new InvalidAlgorithmParameterException("org.spongycastle.jce.provider.MultiCertStoreSpi: parameter must be a MultiCertStoreParameters object\n" + params.toString()); - } - - this.params = (MultiCertStoreParameters)params; - } - - public Collection engineGetCertificates(CertSelector certSelector) - throws CertStoreException - { - boolean searchAllStores = params.getSearchAllStores(); - Iterator iter = params.getCertStores().iterator(); - List allCerts = searchAllStores ? new ArrayList() : Collections.EMPTY_LIST; - - while (iter.hasNext()) - { - CertStore store = (CertStore)iter.next(); - Collection certs = store.getCertificates(certSelector); - - if (searchAllStores) - { - allCerts.addAll(certs); - } - else if (!certs.isEmpty()) - { - return certs; - } - } - - return allCerts; - } - - public Collection engineGetCRLs(CRLSelector crlSelector) - throws CertStoreException - { - boolean searchAllStores = params.getSearchAllStores(); - Iterator iter = params.getCertStores().iterator(); - List allCRLs = searchAllStores ? new ArrayList() : Collections.EMPTY_LIST; - - while (iter.hasNext()) - { - CertStore store = (CertStore)iter.next(); - Collection crls = store.getCRLs(crlSelector); - - if (searchAllStores) - { - allCRLs.addAll(crls); - } - else if (!crls.isEmpty()) - { - return crls; - } - } - - return allCRLs; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/PKIXCertPathBuilderSpi.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/PKIXCertPathBuilderSpi.java deleted file mode 100644 index e09a3526f..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/PKIXCertPathBuilderSpi.java +++ /dev/null @@ -1,365 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.io.IOException; -import java.security.InvalidAlgorithmParameterException; -import java.security.PublicKey; -import java.security.cert.*; -import org.spongycastle.jce.*; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -/** - * Implements the PKIX CertPathBuilding algorithem for BouncyCastle. - *
- * MAYBE: implement more CertPath validation whil build path to omit invalid pathes - * - * @see CertPathBuilderSpi - **/ -public class PKIXCertPathBuilderSpi - extends CertPathBuilderSpi -{ - /** - * Build and validate a CertPath using the given parameter. - * - * @param params PKIXBuilderParameters object containing all - * information to build the CertPath - **/ - public CertPathBuilderResult engineBuild( - CertPathParameters params) - throws CertPathBuilderException, InvalidAlgorithmParameterException - { - if (!(params instanceof PKIXBuilderParameters)) - { - throw new InvalidAlgorithmParameterException("params must be a PKIXBuilderParameters instance"); - } - - PKIXBuilderParameters pkixParams = (PKIXBuilderParameters)params; - - Collection targets; - Iterator targetIter; - List certPathList = new ArrayList(); - X509Certificate cert; - Collection certs; - CertPath certPath = null; - Exception certPathException = null; - - // search target certificates - CertSelector certSelect = pkixParams.getTargetCertConstraints(); - if (certSelect == null) - { - throw new CertPathBuilderException("targetCertConstraints must be non-null for CertPath building"); - } - - try - { - targets = findCertificates(certSelect, pkixParams.getCertStores()); - } - catch (CertStoreException e) - { - throw new CertPathBuilderException(e); - } - - if (targets.isEmpty()) - { - throw new CertPathBuilderException("no certificate found matching targetCertContraints"); - } - - CertificateFactory cFact; - CertPathValidator validator; - - try - { - cFact = CertificateFactory.getInstance("X.509", "SC"); - validator = CertPathValidator.getInstance("PKIX", "SC"); - } - catch (Exception e) - { - throw new CertPathBuilderException("exception creating support classes: " + e); - } - - // - // check all potential target certificates - targetIter = targets.iterator(); - while (targetIter.hasNext()) - { - cert = (X509Certificate)targetIter.next(); - certPathList.clear(); - while (cert != null) - { - // add cert to the certpath - certPathList.add(cert); - - // check wether the issuer of is a TrustAnchor - if (findTrustAnchor(cert, pkixParams.getTrustAnchors()) != null) - { - try - { - certPath = cFact.generateCertPath(certPathList); - - PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult)validator.validate(certPath, pkixParams); - - return new PKIXCertPathBuilderResult(certPath, - result.getTrustAnchor(), - result.getPolicyTree(), - result.getPublicKey()); - } - catch (CertificateException ex) - { - certPathException = ex; - } - catch (CertPathValidatorException ex) - { - certPathException = ex; - } - // if validation failed go to next certificate - cert = null; - } - else - { - // try to get the issuer certificate from one - // of the CertStores - try - { - X509Certificate issuer = findIssuer(cert, pkixParams.getCertStores()); - if (issuer.equals(cert)) - { - cert = null; - } - else - { - cert = issuer; - } - } - catch (CertPathValidatorException ex) - { - certPathException = ex; - cert = null; - } - } - } - } - - if (certPath != null) - { - throw new CertPathBuilderException("found certificate chain, but could not be validated", certPathException); - } - - throw new CertPathBuilderException("unable to find certificate chain"); - } - - /** - * Search the given Set of TrustAnchor's for one that is the - * issuer of the fiven X509 certificate. - * - * @param cert the X509 certificate - * @param trustAnchors a Set of TrustAnchor's - * - * @return the TrustAnchor object if found or - * null if not. - * - * @exception CertPathValidatorException if a TrustAnchor was - * found but the signature verificytion on the given certificate - * has thrown an exception. This Exception can be obtainted with - * getCause() method. - **/ - final TrustAnchor findTrustAnchor( - X509Certificate cert, - Set trustAnchors) - throws CertPathBuilderException - { - Iterator iter = trustAnchors.iterator(); - TrustAnchor trust = null; - PublicKey trustPublicKey = null; - Exception invalidKeyEx = null; - - X509CertSelector certSelectX509 = new X509CertSelector(); - - try - { - certSelectX509.setSubject(PrincipalUtil.getIssuerX509Principal(cert).getEncoded()); - } - catch (CertificateEncodingException ex) - { - throw new CertPathBuilderException("can't get trust anchor principal",null); - } - catch (IOException ex) - { - throw new CertPathBuilderException("can't get trust anchor principal",null); - } - - while (iter.hasNext() && trust == null) - { - trust = (TrustAnchor)iter.next(); - if (trust.getTrustedCert() != null) - { - if (certSelectX509.match(trust.getTrustedCert())) - { - trustPublicKey = trust.getTrustedCert().getPublicKey(); - } - else - { - trust = null; - } - } - else if (trust.getCAName() != null - && trust.getCAPublicKey() != null) - { - try - { - X509Principal certIssuer = PrincipalUtil.getIssuerX509Principal(cert); - X509Principal caName = new X509Principal(trust.getCAName()); - if (certIssuer.equals(caName)) - { - trustPublicKey = trust.getCAPublicKey(); - } - else - { - trust = null; - } - } - catch (CertificateEncodingException ex) - { - trust = null; - } - catch (IllegalArgumentException ex) - { - trust = null; - } - } - else - { - trust = null; - } - - if (trustPublicKey != null) - { - try - { - cert.verify(trustPublicKey); - } - catch (Exception ex) - { - invalidKeyEx = ex; - trust = null; - } - } - } - - if (trust == null && invalidKeyEx != null) - { - throw new CertPathBuilderException("TrustAnchor found put certificate validation failed",invalidKeyEx); - } - - return trust; - } - - /** - * Return a Collection of all certificates found in the - * CertStore's that are matching the certSelect criteriums. - * - * @param certSelector a {@link CertSelector CertSelector} - * object that will be used to select the certificates - * @param certStores a List containing only {@link CertStore - * CertStore} objects. These are used to search for - * certificates - * - * @return a Collection of all found {@link Certificate Certificate} - * objects. May be empty but never null. - **/ - private Collection findCertificates( - CertSelector certSelect, - List certStores) - throws CertStoreException - { - Set certs = new HashSet(); - Iterator iter = certStores.iterator(); - - while (iter.hasNext()) - { - CertStore certStore = (CertStore)iter.next(); - - certs.addAll(certStore.getCertificates(certSelect)); - } - - return certs; - } - - /** - * Find the issuer certificate of the given certificate. - * - * @param cert the certificate hows issuer certificate should - * be found. - * @param certStores a list of CertStore object - * that will be searched - * - * @return then X509Certificate object containing - * the issuer certificate or null if not found - * - * @exception CertPathValidatorException if a TrustAnchor was - * found but the signature verificytion on the given certificate - * has thrown an exception. This Exception can be obtainted with - * getCause() method. - **/ - private X509Certificate findIssuer( - X509Certificate cert, - List certStores) - throws CertPathValidatorException - { - Exception invalidKeyEx = null; - X509CertSelector certSelect = new X509CertSelector(); - try - { - certSelect.setSubject(PrincipalUtil.getIssuerX509Principal(cert).getEncoded()); - } - catch (CertificateEncodingException ex) - { - throw new CertPathValidatorException("Issuer not found", null, null, -1); - } - catch (IOException ex) - { - throw new CertPathValidatorException("Issuer not found", null, null, -1); - } - - Iterator iter; - try - { - iter = findCertificates(certSelect, certStores).iterator(); - } - catch (CertStoreException e) - { - throw new CertPathValidatorException(e); - } - - X509Certificate issuer = null; - while (iter.hasNext() && issuer == null) - { - issuer = (X509Certificate)iter.next(); - try - { - cert.verify(issuer.getPublicKey()); - } - catch (Exception ex) - { - invalidKeyEx = ex; - issuer = null; - } - } - - if (issuer == null && invalidKeyEx == null) - { - throw new CertPathValidatorException("Issuer not found", null, null, -1); - } - - if (issuer == null && invalidKeyEx != null) - { - throw new CertPathValidatorException("issuer found but certificate validation failed",invalidKeyEx,null,-1); - } - - return issuer; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/PKIXCertPathValidatorSpi.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/PKIXCertPathValidatorSpi.java deleted file mode 100644 index 7f6955549..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/PKIXCertPathValidatorSpi.java +++ /dev/null @@ -1,2183 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.security.InvalidAlgorithmParameterException; -import java.security.PublicKey; -import java.security.cert.CRLException; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertPath; -import java.security.cert.CertPathParameters; -import java.security.cert.CertPathValidatorSpi; -import java.security.cert.CertPathValidatorException; -import java.security.cert.CertPathValidatorResult; -import java.security.cert.PolicyQualifierInfo; -import java.security.cert.X509Certificate; -import java.security.cert.X509CRL; -import java.security.cert.X509CRLEntry; -import java.security.cert.X509CRLSelector; -import java.security.cert.X509CertSelector; -import java.security.cert.PKIXParameters; -import java.security.cert.PKIXCertPathChecker; -import java.security.cert.PKIXCertPathValidatorResult; -import java.security.cert.TrustAnchor; -import java.security.cert.PKIXParameters; -import java.security.cert.CertStore; -import java.security.cert.CertStoreException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TimeZone; -import java.text.SimpleDateFormat; - -import org.spongycastle.jce.X509Principal; -import org.spongycastle.jce.PrincipalUtil; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.ASN1OutputStream; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1TaggedObject; -import org.spongycastle.asn1.BERConstructedOctetString; -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Enumerated; -import org.spongycastle.asn1.DERIA5String; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.BasicConstraints; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.GeneralSubtree; -import org.spongycastle.asn1.x509.IssuingDistributionPoint; -import org.spongycastle.asn1.x509.NameConstraints; -import org.spongycastle.asn1.x509.PolicyInformation; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x509.X509Extensions; - -/** - * CertPathValidatorSpi implemenation for X.509 Certificate validation ala rfc 3280
- **/ -public class PKIXCertPathValidatorSpi extends CertPathValidatorSpi -{ - private static final String CERTIFICATE_POLICIES = X509Extensions.CertificatePolicies.getId(); - private static final String POLICY_MAPPINGS = X509Extensions.PolicyMappings.getId(); - private static final String INHIBIT_ANY_POLICY = X509Extensions.InhibitAnyPolicy.getId(); - private static final String ISSUING_DISTRIBUTION_POINT = X509Extensions.IssuingDistributionPoint.getId(); - private static final String DELTA_CRL_INDICATOR = X509Extensions.DeltaCRLIndicator.getId(); - private static final String POLICY_CONSTRAINTS = X509Extensions.PolicyConstraints.getId(); - private static final String BASIC_CONSTRAINTS = X509Extensions.BasicConstraints.getId(); - private static final String SUBJECT_ALTERNATIVE_NAME = X509Extensions.SubjectAlternativeName.getId(); - private static final String NAME_CONSTRAINTS = X509Extensions.NameConstraints.getId(); - private static final String KEY_USAGE = X509Extensions.KeyUsage.getId(); - - private static final String CRL_NUMBER = X509Extensions.CRLNumber.getId(); - - private static final String ANY_POLICY = "2.5.29.32.0"; - - - /* - * key usage bits - */ - private static final int KEY_CERT_SIGN = 5; - private static final int CRL_SIGN = 6; - - private static final String[] crlReasons = new String[] { - "unspecified", - "keyCompromise", - "cACompromise", - "affiliationChanged", - "superseded", - "cessationOfOperation", - "certificateHold", - "unknown", - "removeFromCRL", - "privilegeWithdrawn", - "aACompromise" }; - - /** - * extract the value of the given extension, if it exists. - */ - private ASN1Primitive getExtensionValue( - java.security.cert.X509Extension ext, - String oid) - throws AnnotatedException - { - byte[] bytes = ext.getExtensionValue(oid); - if (bytes == null) - { - return null; - } - - return getObject(oid, bytes); - } - - private ASN1Primitive getObject( - String oid, - byte[] ext) - throws AnnotatedException - { - try - { - ASN1InputStream aIn = new ASN1InputStream(ext); - ASN1OctetString octs = (ASN1OctetString)aIn.readObject(); - - aIn = new ASN1InputStream(octs.getOctets()); - return aIn.readObject(); - } - catch (IOException e) - { - throw new AnnotatedException("exception processing extension " + oid, e); - } - } - - private boolean withinDNSubtree( - ASN1Sequence dns, - ASN1Sequence subtree) - { - if (subtree.size() < 1) - { - return false; - } - - if (subtree.size() > dns.size()) - { - return false; - } - - for (int j = subtree.size() - 1; j >= 0; j--) - { - if (!subtree.getObjectAt(j).equals(dns.getObjectAt(j))) - { - return false; - } - } - - return true; - } - - private void checkPermittedDN( - Set permitted, - ASN1Sequence dns) - throws CertPathValidatorException - { - if (permitted.isEmpty()) - { - return; - } - - Iterator it = permitted.iterator(); - - while (it.hasNext()) - { - ASN1Sequence subtree = (ASN1Sequence)it.next(); - - if (withinDNSubtree(dns, subtree)) - { - return; - } - } - - throw new CertPathValidatorException("Subject distinguished name is not from a permitted subtree"); - } - - private void checkExcludedDN( - Set excluded, - ASN1Sequence dns) - throws CertPathValidatorException - { - if (excluded.isEmpty()) - { - return; - } - - Iterator it = excluded.iterator(); - - while (it.hasNext()) - { - ASN1Sequence subtree = (ASN1Sequence)it.next(); - - if (withinDNSubtree(dns, subtree)) - { - throw new CertPathValidatorException("Subject distinguished name is from an excluded subtree"); - } - } - } - - private Set intersectDN( - Set permitted, - ASN1Sequence dn) - { - if (permitted.isEmpty()) - { - permitted.add(dn); - - return permitted; - } - else - { - Set intersect = new HashSet(); - - Iterator _iter = permitted.iterator(); - while (_iter.hasNext()) - { - ASN1Sequence subtree = (ASN1Sequence)_iter.next(); - - if (withinDNSubtree(dn, subtree)) - { - intersect.add(dn); - } - else if (withinDNSubtree(subtree, dn)) - { - intersect.add(subtree); - } - } - - return intersect; - } - } - - private Set unionDN( - Set excluded, - ASN1Sequence dn) - { - if (excluded.isEmpty()) - { - excluded.add(dn); - - return excluded; - } - else - { - Set intersect = new HashSet(); - - Iterator _iter = excluded.iterator(); - while (_iter.hasNext()) - { - ASN1Sequence subtree = (ASN1Sequence)_iter.next(); - - if (withinDNSubtree(dn, subtree)) - { - intersect.add(subtree); - } - else if (withinDNSubtree(subtree, dn)) - { - intersect.add(dn); - } - else - { - intersect.add(subtree); - intersect.add(dn); - } - } - - return intersect; - } - } - - private Set intersectEmail( - Set permitted, - String email) - { - String _sub = email.substring(email.indexOf('@') + 1); - - if (permitted.isEmpty()) - { - permitted.add(_sub); - - return permitted; - } - else - { - Set intersect = new HashSet(); - - Iterator _iter = permitted.iterator(); - while (_iter.hasNext()) - { - String _permitted = (String)_iter.next(); - - if (_sub.endsWith(_permitted)) - { - intersect.add(_sub); - } - else if (_permitted.endsWith(_sub)) - { - intersect.add(_permitted); - } - } - - return intersect; - } - } - - private Set unionEmail( - Set excluded, - String email) - { - String _sub = email.substring(email.indexOf('@') + 1); - - if (excluded.isEmpty()) - { - excluded.add(_sub); - return excluded; - } - else - { - Set intersect = new HashSet(); - - Iterator _iter = excluded.iterator(); - while (_iter.hasNext()) - { - String _excluded = (String)_iter.next(); - - if (_sub.endsWith(_excluded)) - { - intersect.add(_excluded); - } - else if (_excluded.endsWith(_sub)) - { - intersect.add(_sub); - } - else - { - intersect.add(_excluded); - intersect.add(_sub); - } - } - - return intersect; - } - } - - private Set intersectIP( - Set permitted, - byte[] ip) - { - // TBD - return permitted; - } - - private Set unionIP( - Set excluded, - byte[] ip) - { - // TBD - return excluded; - } - - private void checkPermittedEmail( - Set permitted, - String email) - throws CertPathValidatorException - { - if (permitted.isEmpty()) - { - return; - } - - String sub = email.substring(email.indexOf('@') + 1); - Iterator it = permitted.iterator(); - - while (it.hasNext()) - { - String str = (String)it.next(); - - if (sub.endsWith(str)) - { - return; - } - } - - throw new CertPathValidatorException("Subject email address is not from a permitted subtree"); - } - - private void checkExcludedEmail( - Set excluded, - String email) - throws CertPathValidatorException - { - if (excluded.isEmpty()) - { - return; - } - - String sub = email.substring(email.indexOf('@') + 1); - Iterator it = excluded.iterator(); - - while (it.hasNext()) - { - String str = (String)it.next(); - if (sub.endsWith(str)) - { - throw new CertPathValidatorException("Subject email address is from an excluded subtree"); - } - } - } - - private void checkPermittedIP( - Set permitted, - byte[] ip) - throws CertPathValidatorException - { - if (permitted.isEmpty()) - { - return; - } - - // TODO: ??? Something here - } - - private void checkExcludedIP( - Set excluded, - byte[] ip) - throws CertPathValidatorException - { - if (excluded.isEmpty()) - { - return; - } - - // TODO, check RFC791 and RFC1883 for IP bytes definition. - } - - private PKIXPolicyNode removePolicyNode( - PKIXPolicyNode validPolicyTree, - List [] policyNodes, - PKIXPolicyNode _node) - { - PKIXPolicyNode _parent = (PKIXPolicyNode)_node.getParent(); - - if (validPolicyTree == null) - { - return null; - } - - if (_parent == null) - { - for (int j = 0; j < policyNodes.length; j++) - { - policyNodes[j] = new ArrayList(); - } - - return null; - } - else - { - _parent.removeChild(_node); - removePolicyNodeRecurse(policyNodes, _node); - - return validPolicyTree; - } - } - - private void removePolicyNodeRecurse( - List [] policyNodes, - PKIXPolicyNode _node) - { - policyNodes[_node.getDepth()].remove(_node); - - if (_node.hasChildren()) - { - Iterator _iter = _node.getChildren(); - while (_iter.hasNext()) - { - PKIXPolicyNode _child = (PKIXPolicyNode)_iter.next(); - removePolicyNodeRecurse(policyNodes, _child); - } - } - } - - private boolean isSelfIssued( - X509Certificate cert) - { - return cert.getSubjectDN().equals(cert.getIssuerDN()); - } - - private boolean isAnyPolicy( - Set policySet) - { - return policySet == null || policySet.contains(ANY_POLICY) || policySet.isEmpty(); - } - - private AlgorithmIdentifier getAlgorithmIdentifier( - PublicKey key) - throws CertPathValidatorException - { - try - { - ASN1InputStream aIn = new ASN1InputStream( - new ByteArrayInputStream(key.getEncoded())); - - SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); - - return info.getAlgorithmId(); - } - catch (IOException e) - { - throw new CertPathValidatorException("exception processing public key"); - } - } - - private Set getQualifierSet(ASN1Sequence qualifiers) - throws CertPathValidatorException - { - Set pq = new HashSet(); - - if (qualifiers == null) - { - return pq; - } - - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ASN1OutputStream aOut = new ASN1OutputStream(bOut); - - Enumeration e = qualifiers.getObjects(); - - while (e.hasMoreElements()) - { - try - { - aOut.writeObject((ASN1Encodable)e.nextElement()); - - pq.add(new PolicyQualifierInfo(bOut.toByteArray())); - } - catch (IOException ex) - { - throw new CertPathValidatorException("exception building qualifier set: " + ex); - } - - bOut.reset(); - } - - return pq; - } - - private boolean processCertD1i( - int index, - List [] policyNodes, - ASN1ObjectIdentifier pOid, - Set pq) - { - List policyNodeVec = policyNodes[index - 1]; - - for (int j = 0; j < policyNodeVec.size(); j++) - { - PKIXPolicyNode node = (PKIXPolicyNode)policyNodeVec.get(j); - Set expectedPolicies = node.getExpectedPolicies(); - - if (expectedPolicies.contains(pOid.getId())) - { - Set childExpectedPolicies = new HashSet(); - childExpectedPolicies.add(pOid.getId()); - - PKIXPolicyNode child = new PKIXPolicyNode(new ArrayList(), - index, - childExpectedPolicies, - node, - pq, - pOid.getId(), - false); - node.addChild(child); - policyNodes[index].add(child); - - return true; - } - } - - return false; - } - - private void processCertD1ii( - int index, - List [] policyNodes, - ASN1ObjectIdentifier _poid, - Set _pq) - { - List policyNodeVec = policyNodes[index - 1]; - - for (int j = 0; j < policyNodeVec.size(); j++) - { - PKIXPolicyNode _node = (PKIXPolicyNode)policyNodeVec.get(j); - Set _expectedPolicies = _node.getExpectedPolicies(); - - if (ANY_POLICY.equals(_node.getValidPolicy())) - { - Set _childExpectedPolicies = new HashSet(); - _childExpectedPolicies.add(_poid.getId()); - - PKIXPolicyNode _child = new PKIXPolicyNode(new ArrayList(), - index, - _childExpectedPolicies, - _node, - _pq, - _poid.getId(), - false); - _node.addChild(_child); - policyNodes[index].add(_child); - return; - } - } - } - - public CertPathValidatorResult engineValidate( - CertPath certPath, - CertPathParameters params) - throws CertPathValidatorException, InvalidAlgorithmParameterException - { - if (!(params instanceof PKIXParameters)) - { - throw new InvalidAlgorithmParameterException("params must be a PKIXParameters instance"); - } - - PKIXParameters paramsPKIX = (PKIXParameters)params; - if (paramsPKIX.getTrustAnchors() == null) - { - throw new InvalidAlgorithmParameterException("trustAnchors is null, this is not allowed for path validation"); - } - - // - // 6.1.1 - inputs - // - - // - // (a) - // - List certs = certPath.getCertificates(); - int n = certs.size(); - - if (certs.isEmpty()) - { - throw new CertPathValidatorException("CertPath is empty", null, certPath, 0); - } - - // - // (b) - // - Date validDate = getValidDate(paramsPKIX); - - // - // (c) - // - Set userInitialPolicySet = paramsPKIX.getInitialPolicies(); - - // - // (d) - // - TrustAnchor trust = findTrustAnchor((X509Certificate)certs.get(certs.size() - 1), certPath, certs.size() - 1, paramsPKIX.getTrustAnchors()); - - if (trust == null) - { - throw new CertPathValidatorException("TrustAnchor for CertPath not found.", null, certPath, -1); - } - - // - // (e), (f), (g) are part of the paramsPKIX object. - // - - Iterator certIter; - int index = 0; - int i; - //Certificate for each interation of the validation loop - //Signature information for each iteration of the validation loop - Set subTreeContraints = new HashSet(); - Set subTreeExcludes = new HashSet(); - - // - // 6.1.2 - setup - // - - // - // (a) - // - List [] policyNodes = new ArrayList[n + 1]; - for (int j = 0; j < policyNodes.length; j++) - { - policyNodes[j] = new ArrayList(); - } - - Set policySet = new HashSet(); - - policySet.add(ANY_POLICY); - - PKIXPolicyNode validPolicyTree = new PKIXPolicyNode(new ArrayList(), 0, policySet, null, new HashSet(), ANY_POLICY, false); - - policyNodes[0].add(validPolicyTree); - - // - // (b) - // - Set permittedSubtreesDN = new HashSet(); - Set permittedSubtreesEmail = new HashSet(); - Set permittedSubtreesIP = new HashSet(); - - // - // (c) - // - Set excludedSubtreesDN = new HashSet(); - Set excludedSubtreesEmail = new HashSet(); - Set excludedSubtreesIP = new HashSet(); - - // - // (d) - // - int explicitPolicy; - Set acceptablePolicies = null; - - if (paramsPKIX.isExplicitPolicyRequired()) - { - explicitPolicy = 0; - } - else - { - explicitPolicy = n + 1; - } - - // - // (e) - // - int inhibitAnyPolicy; - - if (paramsPKIX.isAnyPolicyInhibited()) - { - inhibitAnyPolicy = 0; - } - else - { - inhibitAnyPolicy = n + 1; - } - - // - // (f) - // - int policyMapping; - - if (paramsPKIX.isPolicyMappingInhibited()) - { - policyMapping = 0; - } - else - { - policyMapping = n + 1; - } - - // - // (g), (h), (i), (j) - // - PublicKey workingPublicKey; - X509Principal workingIssuerName; - - X509Certificate sign = trust.getTrustedCert(); - try - { - if (sign != null) - { - workingIssuerName = getSubjectPrincipal(sign); - workingPublicKey = sign.getPublicKey(); - } - else - { - workingIssuerName = new X509Principal(trust.getCAName()); - workingPublicKey = trust.getCAPublicKey(); - } - } - catch (IllegalArgumentException ex) - { - throw new CertPathValidatorException("TrustAnchor subjectDN: " + ex.toString()); - } - catch (AnnotatedException ex) - { - throw new CertPathValidatorException(ex.getMessage(), ex.getUnderlyingException(), certPath, index); - } - - AlgorithmIdentifier workingAlgId = getAlgorithmIdentifier(workingPublicKey); - ASN1ObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.getObjectId(); - ASN1Encodable workingPublicKeyParameters = workingAlgId.getParameters(); - - // - // (k) - // - int maxPathLength = n; - - // - // 6.1.3 - // - Iterator tmpIter; - int tmpInt; - - if (paramsPKIX.getTargetCertConstraints() != null - && !paramsPKIX.getTargetCertConstraints().match((X509Certificate)certs.get(0))) - { - throw new CertPathValidatorException("target certificate in certpath does not match targetcertconstraints", null, certPath, 0); - } - - - // - // initialise CertPathChecker's - // - List pathCheckers = paramsPKIX.getCertPathCheckers(); - certIter = pathCheckers.iterator(); - while (certIter.hasNext()) - { - ((PKIXCertPathChecker)certIter.next()).init(false); - } - - X509Certificate cert = null; - - for (index = certs.size() - 1; index >= 0 ; index--) - { - try - { - // - // i as defined in the algorithm description - // - i = n - index; - - // - // set certificate to be checked in this round - // sign and workingPublicKey and workingIssuerName are set - // at the end of the for loop and initialied the - // first time from the TrustAnchor - // - cert = (X509Certificate)certs.get(index); - - // - // 6.1.3 - // - - // - // (a) verify - // - try - { - // (a) (1) - // - cert.verify(workingPublicKey, "SC"); - } - catch (Exception e) - { - throw new CertPathValidatorException("Could not validate certificate signature.", e, certPath, index); - } - - try - { - // (a) (2) - // - cert.checkValidity(validDate); - } - catch (CertificateExpiredException e) - { - throw new CertPathValidatorException("Could not validate certificate: " + e.getMessage(), e, certPath, index); - } - catch (CertificateNotYetValidException e) - { - throw new CertPathValidatorException("Could not validate certificate: " + e.getMessage(), e, certPath, index); - } - - // - // (a) (3) - // - if (paramsPKIX.isRevocationEnabled()) - { - checkCRLs(paramsPKIX, cert, validDate, sign, workingPublicKey); - } - - // - // (a) (4) name chaining - // - if (!getEncodedIssuerPrincipal(cert).equals(workingIssuerName)) - { - throw new CertPathValidatorException( - "IssuerName(" + getEncodedIssuerPrincipal(cert) + - ") does not match SubjectName(" + workingIssuerName + - ") of signing certificate", null, certPath, index); - } - - // - // (b), (c) permitted and excluded subtree checking. - // - if (!(isSelfIssued(cert) && (i < n))) - { - X509Principal principal = getSubjectPrincipal(cert); - ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(principal.getEncoded())); - ASN1Sequence dns; - - try - { - dns = (ASN1Sequence)aIn.readObject(); - } - catch (IOException e) - { - throw new CertPathValidatorException("exception extracting subject name when checking subtrees"); - } - - checkPermittedDN(permittedSubtreesDN, dns); - - checkExcludedDN(excludedSubtreesDN, dns); - - ASN1Sequence altName = (ASN1Sequence)getExtensionValue(cert, SUBJECT_ALTERNATIVE_NAME); - if (altName != null) - { - for (int j = 0; j < altName.size(); j++) - { - ASN1TaggedObject o = (ASN1TaggedObject)altName.getObjectAt(j); - - switch(o.getTagNo()) - { - case 1: - String email = DERIA5String.getInstance(o, true).getString(); - - checkPermittedEmail(permittedSubtreesEmail, email); - checkExcludedEmail(excludedSubtreesEmail, email); - break; - case 4: - ASN1Sequence altDN = ASN1Sequence.getInstance(o, true); - - checkPermittedDN(permittedSubtreesDN, altDN); - checkExcludedDN(excludedSubtreesDN, altDN); - break; - case 7: - byte[] ip = ASN1OctetString.getInstance(o, true).getOctets(); - - checkPermittedIP(permittedSubtreesIP, ip); - checkExcludedIP(excludedSubtreesIP, ip); - } - } - } - } - - // - // (d) policy Information checking against initial policy and - // policy mapping - // - ASN1Sequence certPolicies = (ASN1Sequence)getExtensionValue(cert, CERTIFICATE_POLICIES); - if (certPolicies != null && validPolicyTree != null) - { - // - // (d) (1) - // - Enumeration e = certPolicies.getObjects(); - Set pols = new HashSet(); - - while (e.hasMoreElements()) - { - PolicyInformation pInfo = PolicyInformation.getInstance(e.nextElement()); - ASN1ObjectIdentifier pOid = pInfo.getPolicyIdentifier(); - - pols.add(pOid.getId()); - - if (!ANY_POLICY.equals(pOid.getId())) - { - Set pq = getQualifierSet(pInfo.getPolicyQualifiers()); - - boolean match = processCertD1i(i, policyNodes, pOid, pq); - - if (!match) - { - processCertD1ii(i, policyNodes, pOid, pq); - } - } - } - - if (acceptablePolicies == null || acceptablePolicies.contains(ANY_POLICY)) - { - acceptablePolicies = pols; - } - else - { - Iterator it = acceptablePolicies.iterator(); - Set t1 = new HashSet(); - - while (it.hasNext()) - { - Object o = it.next(); - - if (pols.contains(o)) - { - t1.add(o); - } - } - - acceptablePolicies = t1; - } - - // - // (d) (2) - // - if ((inhibitAnyPolicy > 0) || ((i < n) && isSelfIssued(cert))) - { - e = certPolicies.getObjects(); - - while (e.hasMoreElements()) - { - PolicyInformation pInfo = PolicyInformation.getInstance(e.nextElement()); - - if (ANY_POLICY.equals(pInfo.getPolicyIdentifier().getId())) - { - Set _apq = getQualifierSet(pInfo.getPolicyQualifiers()); - List _nodes = policyNodes[i - 1]; - - for (int k = 0; k < _nodes.size(); k++) - { - PKIXPolicyNode _node = (PKIXPolicyNode)_nodes.get(k); - - Iterator _policySetIter = _node.getExpectedPolicies().iterator(); - while (_policySetIter.hasNext()) - { - Object _tmp = _policySetIter.next(); - - String _policy; - if (_tmp instanceof String) - { - _policy = (String)_tmp; - } - else if (_tmp instanceof ASN1ObjectIdentifier) - { - _policy = ((ASN1ObjectIdentifier)_tmp).getId(); - } - else - { - continue; - } - - boolean _found = false; - Iterator _childrenIter = _node.getChildren(); - - while (_childrenIter.hasNext()) - { - PKIXPolicyNode _child = (PKIXPolicyNode)_childrenIter.next(); - - if (_policy.equals(_child.getValidPolicy())) - { - _found = true; - } - } - - if (!_found) - { - Set _newChildExpectedPolicies = new HashSet(); - _newChildExpectedPolicies.add(_policy); - - PKIXPolicyNode _newChild = new PKIXPolicyNode(new ArrayList(), - i, - _newChildExpectedPolicies, - _node, - _apq, - _policy, - false); - _node.addChild(_newChild); - policyNodes[i].add(_newChild); - } - } - } - break; - } - } - } - - // - // (d) (3) - // - for (int j = (i - 1); j >= 0; j--) - { - List nodes = policyNodes[j]; - - for (int k = 0; k < nodes.size(); k++) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes.get(k); - if (!node.hasChildren()) - { - validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, node); - if (validPolicyTree == null) - { - break; - } - } - } - } - - // - // d (4) - // - Set criticalExtensionOids = cert.getCriticalExtensionOIDs(); - - if (criticalExtensionOids != null) - { - boolean critical = criticalExtensionOids.contains(CERTIFICATE_POLICIES); - - List nodes = policyNodes[i]; - for (int j = 0; j < nodes.size(); j++) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes.get(j); - node.setCritical(critical); - } - } - } - - // - // (e) - // - if (certPolicies == null) - { - validPolicyTree = null; - } - - // - // (f) - // - if (explicitPolicy <= 0 && validPolicyTree == null) - { - throw new CertPathValidatorException("No valid policy tree found when one expected."); - } - - // - // 6.1.4 - // - - if (i != n) - { - if (cert != null && cert.getVersion() == 1) - { - throw new CertPathValidatorException( - "Version 1 certs can't be used as CA ones"); - } - - // - // - // (a) check the policy mappings - // - ASN1Primitive pm = getExtensionValue(cert, POLICY_MAPPINGS); - if (pm != null) - { - ASN1Sequence mappings = (ASN1Sequence)pm; - - for (int j = 0; j < mappings.size(); j++) - { - ASN1Sequence mapping = (ASN1Sequence)mappings.getObjectAt(j); - - ASN1ObjectIdentifier issuerDomainPolicy = (ASN1ObjectIdentifier)mapping.getObjectAt(0); - ASN1ObjectIdentifier subjectDomainPolicy = (ASN1ObjectIdentifier)mapping.getObjectAt(1); - - if (ANY_POLICY.equals(issuerDomainPolicy.getId())) - { - - throw new CertPathValidatorException("IssuerDomainPolicy is anyPolicy"); - } - - if (ANY_POLICY.equals(subjectDomainPolicy.getId())) - { - - throw new CertPathValidatorException("SubjectDomainPolicy is anyPolicy"); - } - } - } - - // (b) - // - if (pm != null) - { - ASN1Sequence mappings = (ASN1Sequence)pm; - Map m_idp = new HashMap(); - Set s_idp = new HashSet(); - - for (int j = 0; j < mappings.size(); j++) - { - ASN1Sequence mapping = (ASN1Sequence)mappings.getObjectAt(j); - String id_p = ((ASN1ObjectIdentifier)mapping.getObjectAt(0)).getId(); - String sd_p = ((ASN1ObjectIdentifier)mapping.getObjectAt(1)).getId(); - Set tmp; - - if (!m_idp.containsKey(id_p)) - { - tmp = new HashSet(); - tmp.add(sd_p); - m_idp.put(id_p, tmp); - s_idp.add(id_p); - } - else - { - tmp = (Set)m_idp.get(id_p); - tmp.add(sd_p); - } - } - - Iterator it_idp = s_idp.iterator(); - while (it_idp.hasNext()) - { - String id_p = (String)it_idp.next(); - - // - // (1) - // - if (policyMapping > 0) - { - boolean idp_found = false; - Iterator nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (node.getValidPolicy().equals(id_p)) - { - idp_found = true; - node.expectedPolicies = (Set)m_idp.get(id_p); - break; - } - } - - if (!idp_found) - { - nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (ANY_POLICY.equals(node.getValidPolicy())) - { - Set pq = null; - ASN1Sequence policies = (ASN1Sequence)getExtensionValue( - cert, CERTIFICATE_POLICIES); - Enumeration e = policies.getObjects(); - while (e.hasMoreElements()) - { - PolicyInformation pinfo = PolicyInformation.getInstance(e.nextElement()); - if (ANY_POLICY.equals(pinfo.getPolicyIdentifier().getId())) - { - pq = getQualifierSet(pinfo.getPolicyQualifiers()); - break; - } - } - boolean ci = false; - if (cert.getCriticalExtensionOIDs() != null) - { - ci = cert.getCriticalExtensionOIDs().contains(CERTIFICATE_POLICIES); - } - - PKIXPolicyNode p_node = (PKIXPolicyNode)node.getParent(); - if (ANY_POLICY.equals(p_node.getValidPolicy())) - { - PKIXPolicyNode c_node = new PKIXPolicyNode( - new ArrayList(), i, - (Set)m_idp.get(id_p), - p_node, pq, id_p, ci); - p_node.addChild(c_node); - policyNodes[i].add(c_node); - } - break; - } - } - } - - // - // (2) - // - } - else if (policyMapping <= 0) - { - Iterator nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (node.getValidPolicy().equals(id_p)) - { - PKIXPolicyNode p_node = (PKIXPolicyNode)node.getParent(); - p_node.removeChild(node); - nodes_i.remove(); - for (int k = (i - 1); k >= 0; k--) - { - List nodes = policyNodes[k]; - for (int l = 0; l < nodes.size(); l++) - { - PKIXPolicyNode node2 = (PKIXPolicyNode)nodes.get(l); - if (!node2.hasChildren()) - { - validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, node2); - if (validPolicyTree == null) - { - break; - } - } - } - } - } - } - } - } - } - - // - // (g) handle the name constraints extension - // - ASN1Sequence ncSeq = (ASN1Sequence)getExtensionValue(cert, NAME_CONSTRAINTS); - if (ncSeq != null) - { - NameConstraints nc = NameConstraints.getInstance(ncSeq); - - // - // (g) (1) permitted subtrees - // - GeneralSubtree[] permitted = nc.getPermittedSubtrees(); - if (permitted != null) - { - for (int indx = 0; indx != permitted.length; indx++) - { - GeneralSubtree subtree = permitted[indx]; - GeneralName base = subtree.getBase(); - - switch(base.getTagNo()) - { - case 1: - permittedSubtreesEmail = intersectEmail(permittedSubtreesEmail, DERIA5String.getInstance(base.getName()).getString()); - break; - case 4: - permittedSubtreesDN = intersectDN(permittedSubtreesDN, (ASN1Sequence)base.getName()); - break; - case 7: - permittedSubtreesIP = intersectIP(permittedSubtreesIP, BERConstructedOctetString.fromSequence((ASN1Sequence)base.getName()).getOctets()); - break; - } - } - } - - // - // (g) (2) excluded subtrees - // - GeneralSubtree[] excluded = nc.getExcludedSubtrees(); - if (excluded != null) - { - for (int indx = 0; indx != excluded.length; indx++) - { - GeneralSubtree subtree = excluded[indx]; - GeneralName base = subtree.getBase(); - - switch(base.getTagNo()) - { - case 1: - excludedSubtreesEmail = unionEmail(excludedSubtreesEmail, DERIA5String.getInstance(base.getName()).getString()); - break; - case 4: - excludedSubtreesDN = unionDN(excludedSubtreesDN, (ASN1Sequence)base.getName()); - break; - case 7: - excludedSubtreesIP = unionIP(excludedSubtreesIP, BERConstructedOctetString.fromSequence((ASN1Sequence)base.getName()).getOctets()); - break; - } - } - } - } - - // - // (h) - // - if (!isSelfIssued(cert)) - { - // - // (1) - // - if (explicitPolicy != 0) - { - explicitPolicy--; - } - - // - // (2) - // - if (policyMapping != 0) - { - policyMapping--; - } - - // - // (3) - // - if (inhibitAnyPolicy != 0) - { - inhibitAnyPolicy--; - } - } - - // - // (i) - // - ASN1Sequence pc = (ASN1Sequence)getExtensionValue(cert, POLICY_CONSTRAINTS); - - if (pc != null) - { - Enumeration policyConstraints = pc.getObjects(); - - while (policyConstraints.hasMoreElements()) - { - ASN1TaggedObject constraint = (ASN1TaggedObject)policyConstraints.nextElement(); - switch (constraint.getTagNo()) - { - case 0: - tmpInt = ASN1Integer.getInstance(constraint).getValue().intValue(); - if (tmpInt < explicitPolicy) - { - explicitPolicy = tmpInt; - } - break; - case 1: - tmpInt = ASN1Integer.getInstance(constraint).getValue().intValue(); - if (tmpInt < policyMapping) - { - policyMapping = tmpInt; - } - break; - } - } - } - - // - // (j) - // - ASN1Integer iap = (ASN1Integer)getExtensionValue(cert, INHIBIT_ANY_POLICY); - - if (iap != null) - { - int _inhibitAnyPolicy = iap.getValue().intValue(); - - if (_inhibitAnyPolicy < inhibitAnyPolicy) - { - inhibitAnyPolicy = _inhibitAnyPolicy; - } - } - - // - // (k) - // - BasicConstraints bc = BasicConstraints.getInstance( - getExtensionValue(cert, BASIC_CONSTRAINTS)); - if (bc != null) - { - if (!(bc.isCA())) - { - throw new CertPathValidatorException("Not a CA certificate"); - } - } - else - { - throw new CertPathValidatorException("Intermediate certificate lacks BasicConstraints"); - } - - // - // (l) - // - if (!isSelfIssued(cert)) - { - if (maxPathLength <= 0) - { - throw new CertPathValidatorException("Max path length not greater than zero"); - } - - maxPathLength--; - } - - // - // (m) - // - if (bc != null) - { - BigInteger _pathLengthConstraint = bc.getPathLenConstraint(); - - if (_pathLengthConstraint != null) - { - int _plc = _pathLengthConstraint.intValue(); - - if (_plc < maxPathLength) - { - maxPathLength = _plc; - } - } - } - - // - // (n) - // - boolean[] _usage = cert.getKeyUsage(); - - if ((_usage != null) && !_usage[5]) - { - throw new CertPathValidatorException( - "Issuer certificate keyusage extension is critical an does not permit key signing.\n", - null, certPath, index); - } - - // - // (o) - // - Set criticalExtensions = new HashSet(cert.getCriticalExtensionOIDs()); - // these extensions are handle by the algorithem - criticalExtensions.remove(KEY_USAGE); - criticalExtensions.remove(CERTIFICATE_POLICIES); - criticalExtensions.remove(POLICY_MAPPINGS); - criticalExtensions.remove(INHIBIT_ANY_POLICY); - criticalExtensions.remove(ISSUING_DISTRIBUTION_POINT); - criticalExtensions.remove(DELTA_CRL_INDICATOR); - criticalExtensions.remove(POLICY_CONSTRAINTS); - criticalExtensions.remove(BASIC_CONSTRAINTS); - criticalExtensions.remove(SUBJECT_ALTERNATIVE_NAME); - criticalExtensions.remove(NAME_CONSTRAINTS); - - tmpIter = pathCheckers.iterator(); - while (tmpIter.hasNext()) - { - try - { - ((PKIXCertPathChecker)tmpIter.next()).check(cert, criticalExtensions); - } - catch (CertPathValidatorException e) - { - throw new CertPathValidatorException(e.getMessage(), e.getCause(), certPath, index); - } - } - if (!criticalExtensions.isEmpty()) - { - throw new CertPathValidatorException( - "Certificate has unsupported critical extension", null, certPath, index); - } - } - - // set signing certificate for next round - sign = cert; - workingPublicKey = sign.getPublicKey(); - try - { - workingIssuerName = getSubjectPrincipal(sign); - } - catch (IllegalArgumentException ex) - { - throw new CertPathValidatorException(sign.getSubjectDN().getName() + " :" + ex.toString()); - } - workingAlgId = getAlgorithmIdentifier(workingPublicKey); - workingPublicKeyAlgorithm = workingAlgId.getObjectId(); - workingPublicKeyParameters = workingAlgId.getParameters(); - } - catch (AnnotatedException e) - { - throw new CertPathValidatorException(e.getMessage(), e.getUnderlyingException(), certPath, index); - } - } - - // - // 6.1.5 Wrap-up procedure - // - - // - // (a) - // - if (!isSelfIssued(cert) && (explicitPolicy != 0)) - { - explicitPolicy--; - } - - // - // (b) - // - try - { - ASN1Sequence pc = (ASN1Sequence)getExtensionValue(cert, POLICY_CONSTRAINTS); - if (pc != null) - { - Enumeration policyConstraints = pc.getObjects(); - - while (policyConstraints.hasMoreElements()) - { - ASN1TaggedObject constraint = (ASN1TaggedObject)policyConstraints.nextElement(); - switch (constraint.getTagNo()) - { - case 0: - tmpInt = ASN1Integer.getInstance(constraint).getValue().intValue(); - if (tmpInt == 0) - { - explicitPolicy = 0; - } - break; - } - } - } - } - catch (AnnotatedException e) - { - throw new CertPathValidatorException(e.getMessage(), e.getUnderlyingException(), certPath, index); - } - - // - // (c) (d) and (e) are already done - // - - // - // (f) - // - Set criticalExtensions = cert.getCriticalExtensionOIDs(); - - if (criticalExtensions != null) - { - criticalExtensions = new HashSet(criticalExtensions); - // these extensions are handle by the algorithm - criticalExtensions.remove(KEY_USAGE); - criticalExtensions.remove(CERTIFICATE_POLICIES); - criticalExtensions.remove(POLICY_MAPPINGS); - criticalExtensions.remove(INHIBIT_ANY_POLICY); - criticalExtensions.remove(ISSUING_DISTRIBUTION_POINT); - criticalExtensions.remove(DELTA_CRL_INDICATOR); - criticalExtensions.remove(POLICY_CONSTRAINTS); - criticalExtensions.remove(BASIC_CONSTRAINTS); - criticalExtensions.remove(SUBJECT_ALTERNATIVE_NAME); - criticalExtensions.remove(NAME_CONSTRAINTS); - } - else - { - criticalExtensions = new HashSet(); - } - - tmpIter = pathCheckers.iterator(); - while (tmpIter.hasNext()) - { - try - { - ((PKIXCertPathChecker)tmpIter.next()).check(cert, criticalExtensions); - } - catch (CertPathValidatorException e) - { - throw new CertPathValidatorException(e.getMessage(), e.getCause(), certPath, index); - } - } - - if (!criticalExtensions.isEmpty()) - { - throw new CertPathValidatorException( - "Certificate has unsupported critical extension", null, certPath, index); - } - - // - // (g) - // - PKIXPolicyNode intersection; - - - // - // (g) (i) - // - if (validPolicyTree == null) - { - if (paramsPKIX.isExplicitPolicyRequired()) - { - throw new CertPathValidatorException("Explicit policy requested but none available."); - } - intersection = null; - } - else if (isAnyPolicy(userInitialPolicySet)) // (g) (ii) - { - if (paramsPKIX.isExplicitPolicyRequired()) - { - if (acceptablePolicies.isEmpty()) - { - throw new CertPathValidatorException("Explicit policy requested but none available."); - } - else - { - Set _validPolicyNodeSet = new HashSet(); - - for (int j = 0; j < policyNodes.length; j++) - { - List _nodeDepth = policyNodes[j]; - - for (int k = 0; k < _nodeDepth.size(); k++) - { - PKIXPolicyNode _node = (PKIXPolicyNode)_nodeDepth.get(k); - - if (ANY_POLICY.equals(_node.getValidPolicy())) - { - Iterator _iter = _node.getChildren(); - while (_iter.hasNext()) - { - _validPolicyNodeSet.add(_iter.next()); - } - } - } - } - - Iterator _vpnsIter = _validPolicyNodeSet.iterator(); - while (_vpnsIter.hasNext()) - { - PKIXPolicyNode _node = (PKIXPolicyNode)_vpnsIter.next(); - String _validPolicy = _node.getValidPolicy(); - - if (!acceptablePolicies.contains(_validPolicy)) - { - //validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, _node); - } - } - if (validPolicyTree != null) - { - for (int j = (n - 1); j >= 0; j--) - { - List nodes = policyNodes[j]; - - for (int k = 0; k < nodes.size(); k++) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes.get(k); - if (!node.hasChildren()) - { - validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, node); - } - } - } - } - } - } - - intersection = validPolicyTree; - } - else - { - // - // (g) (iii) - // - // This implementation is not exactly same as the one described in RFC3280. - // However, as far as the validation result is concerned, both produce - // adequate result. The only difference is whether AnyPolicy is remain - // in the policy tree or not. - // - // (g) (iii) 1 - // - Set _validPolicyNodeSet = new HashSet(); - - for (int j = 0; j < policyNodes.length; j++) - { - List _nodeDepth = policyNodes[j]; - - for (int k = 0; k < _nodeDepth.size(); k++) - { - PKIXPolicyNode _node = (PKIXPolicyNode)_nodeDepth.get(k); - - if (ANY_POLICY.equals(_node.getValidPolicy())) - { - Iterator _iter = _node.getChildren(); - while (_iter.hasNext()) - { - PKIXPolicyNode _c_node = (PKIXPolicyNode)_iter.next(); - if (!ANY_POLICY.equals(_c_node.getValidPolicy())) - { - _validPolicyNodeSet.add(_c_node); - } - } - } - } - } - - // - // (g) (iii) 2 - // - Iterator _vpnsIter = _validPolicyNodeSet.iterator(); - while (_vpnsIter.hasNext()) - { - PKIXPolicyNode _node = (PKIXPolicyNode)_vpnsIter.next(); - String _validPolicy = _node.getValidPolicy(); - - if (!userInitialPolicySet.contains(_validPolicy)) - { - validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, _node); - } - } - - // - // (g) (iii) 4 - // - if (validPolicyTree != null) - { - for (int j = (n - 1); j >= 0; j--) - { - List nodes = policyNodes[j]; - - for (int k = 0; k < nodes.size(); k++) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes.get(k); - if (!node.hasChildren()) - { - validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, node); - } - } - } - } - - intersection = validPolicyTree; - } - - if ((explicitPolicy > 0) || (intersection != null)) - { - return new PKIXCertPathValidatorResult(trust, intersection, workingPublicKey); - } - - throw new CertPathValidatorException("Path processing failed on policy.", null, certPath, index); - } - - private Date getValidDate( - PKIXParameters paramsPKIX) - { - Date validDate = paramsPKIX.getDate(); - - if (validDate == null) - { - validDate = new Date(); - } - - return validDate; - } - - private void checkCRLs(PKIXParameters paramsPKIX, X509Certificate cert, Date validDate, X509Certificate sign, PublicKey workingPublicKey) - throws AnnotatedException - { - X509CRLSelector crlselect; - crlselect = new X509CRLSelector(); - - try - { - crlselect.addIssuerName(getEncodedIssuerPrincipal(cert).getEncoded()); - } - catch (IOException e) - { - throw new AnnotatedException("Cannot extract issuer from certificate: " + e, e); - } - - crlselect.setCertificateChecking(cert); - - Iterator crl_iter = findCRLs(crlselect, paramsPKIX.getCertStores()).iterator(); - boolean validCrlFound = false; - X509CRLEntry crl_entry; - while (crl_iter.hasNext()) - { - X509CRL crl = (X509CRL)crl_iter.next(); - - if (cert.getNotAfter().after(crl.getThisUpdate())) - { - if (crl.getNextUpdate() == null - || validDate.before(crl.getNextUpdate())) - { - validCrlFound = true; - } - - if (sign != null) - { - boolean[] keyusage = sign.getKeyUsage(); - - if (keyusage != null - && (keyusage.length < 7 || !keyusage[CRL_SIGN])) - { - throw new AnnotatedException( - "Issuer certificate keyusage extension does not permit crl signing.\n" + sign); - } - } - - try - { - crl.verify(workingPublicKey, "SC"); - } - catch (Exception e) - { - throw new AnnotatedException("can't verify CRL: " + e, e); - } - - crl_entry = crl.getRevokedCertificate(cert.getSerialNumber()); - if (crl_entry != null - && !validDate.before(crl_entry.getRevocationDate())) - { - String reason = null; - - if (crl_entry.hasExtensions()) - { - ASN1Enumerated reasonCode = ASN1Enumerated.getInstance(getExtensionValue(crl_entry, X509Extensions.ReasonCode.getId())); - if (reasonCode != null) - { - reason = crlReasons[reasonCode.getValue().intValue()]; - } - } - - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); - df.setTimeZone(TimeZone.getTimeZone("UTC")); - String message = "Certificate revocation after " + df.format(crl_entry.getRevocationDate()); - - if (reason != null) - { - message += ", reason: " + reason; - } - - throw new AnnotatedException(message); - } - - // - // check the DeltaCRL indicator, base point and the issuing distribution point - // - ASN1Primitive idp = getExtensionValue(crl, ISSUING_DISTRIBUTION_POINT); - ASN1Primitive dci = getExtensionValue(crl, DELTA_CRL_INDICATOR); - - if (dci != null) - { - X509CRLSelector baseSelect = new X509CRLSelector(); - - try - { - baseSelect.addIssuerName(getIssuerPrincipal(crl).getEncoded()); - } - catch (IOException e) - { - throw new AnnotatedException("can't extract issuer from certificate: " + e, e); - } - - baseSelect.setMinCRLNumber(((ASN1Integer)dci).getPositiveValue()); - baseSelect.setMaxCRLNumber(((ASN1Integer)getExtensionValue(crl, CRL_NUMBER)).getPositiveValue().subtract(BigInteger.valueOf(1))); - - boolean foundBase = false; - Iterator it = findCRLs(baseSelect, paramsPKIX.getCertStores()).iterator(); - while (it.hasNext()) - { - X509CRL base = (X509CRL)it.next(); - - ASN1Primitive baseIdp = getExtensionValue(base, ISSUING_DISTRIBUTION_POINT); - - if (idp == null) - { - if (baseIdp == null) - { - foundBase = true; - break; - } - } - else - { - if (idp.equals(baseIdp)) - { - foundBase = true; - break; - } - } - } - - if (!foundBase) - { - throw new AnnotatedException("No base CRL for delta CRL"); - } - } - - if (idp != null) - { - IssuingDistributionPoint p = IssuingDistributionPoint.getInstance(idp); - BasicConstraints bc = BasicConstraints.getInstance(getExtensionValue(cert, BASIC_CONSTRAINTS)); - - if (p.onlyContainsUserCerts() && (bc != null && bc.isCA())) - { - throw new AnnotatedException("CA Cert CRL only contains user certificates"); - } - - if (p.onlyContainsCACerts() && (bc == null || !bc.isCA())) - { - throw new AnnotatedException("End CRL only contains CA certificates"); - } - - if (p.onlyContainsAttributeCerts()) - { - throw new AnnotatedException("onlyContainsAttributeCerts boolean is asserted"); - } - } - } - } - - if (!validCrlFound) - { - throw new AnnotatedException("no valid CRL found"); - } - } - - /** - * Return a Collection of all CRLs found in the - * CertStore's that are matching the crlSelect criteriums. - * - * @param certSelector a {@link CertSelector CertSelector} - * object that will be used to select the certificates - * @param certStores a List containing only {@link CertStore - * CertStore} objects. These are used to search for - * CRLs - * - * @return a Collection of all found {@link CRL CRL} - * objects. May be empty but never null. - */ - private Collection findCRLs( - X509CRLSelector crlSelect, - List crlStores) - throws AnnotatedException - { - Set crls = new HashSet(); - Iterator iter = crlStores.iterator(); - - while (iter.hasNext()) - { - CertStore certStore = (CertStore)iter.next(); - - try - { - crls.addAll(certStore.getCRLs(crlSelect)); - } - catch (CertStoreException e) - { - throw new AnnotatedException("cannot extract crl: " + e, e); - } - } - - return crls; - } - - /** - * Search the given Set of TrustAnchor's for one that is the - * issuer of the fiven X509 certificate. - * - * @param cert the X509 certificate - * @param trustAnchors a Set of TrustAnchor's - * - * @return the TrustAnchor object if found or - * null if not. - * - * @exception CertPathValidatorException if a TrustAnchor was - * found but the signature verification on the given certificate - * has thrown an exception. This Exception can be obtainted with - * getCause() method. - **/ - final TrustAnchor findTrustAnchor( - X509Certificate cert, - CertPath certPath, - int index, - Set trustAnchors) - throws CertPathValidatorException - { - Iterator iter = trustAnchors.iterator(); - TrustAnchor trust = null; - PublicKey trustPublicKey = null; - Exception invalidKeyEx = null; - - X509CertSelector certSelectX509 = new X509CertSelector(); - - try - { - certSelectX509.setSubject(getEncodedIssuerPrincipal(cert).getEncoded()); - } - catch (IOException ex) - { - throw new CertPathValidatorException(ex); - } - catch (AnnotatedException ex) - { - throw new CertPathValidatorException(ex.getUnderlyingException()); - } - - while (iter.hasNext() && trust == null) - { - trust = (TrustAnchor)iter.next(); - if (trust.getTrustedCert() != null) - { - if (certSelectX509.match(trust.getTrustedCert())) - { - trustPublicKey = trust.getTrustedCert().getPublicKey(); - } - else - { - trust = null; - } - } - else if (trust.getCAName() != null - && trust.getCAPublicKey() != null) - { - try - { - X509Principal certIssuer = getEncodedIssuerPrincipal(cert); - X509Principal caName = new X509Principal(trust.getCAName()); - if (certIssuer.equals(caName)) - { - trustPublicKey = trust.getCAPublicKey(); - } - else - { - trust = null; - } - } - catch (AnnotatedException ex) - { - throw new CertPathValidatorException(ex.getMessage(), ex.getUnderlyingException(), certPath, index); - } - catch (IllegalArgumentException ex) - { - trust = null; - } - } - else - { - trust = null; - } - - if (trustPublicKey != null) - { - try - { - cert.verify(trustPublicKey); - } - catch (Exception ex) - { - invalidKeyEx = ex; - trust = null; - } - } - } - - if (trust == null && invalidKeyEx != null) - { - throw new CertPathValidatorException("TrustAnchor found but certificate validation failed.", invalidKeyEx, certPath, index); - } - - return trust; - } - - private X509Principal getIssuerPrincipal(X509CRL crl) - throws AnnotatedException - { - try - { - return PrincipalUtil.getIssuerX509Principal(crl); - } - catch (CRLException e) - { - throw new AnnotatedException("can't get CRL issuer principal", e); - } - } - - private X509Principal getEncodedIssuerPrincipal(X509Certificate cert) - throws AnnotatedException - { - try - { - return PrincipalUtil.getIssuerX509Principal(cert); - } - catch (CertificateEncodingException e) - { - throw new AnnotatedException("can't get issuer principal.", e); - } - } - - private X509Principal getSubjectPrincipal(X509Certificate cert) - throws AnnotatedException - { - try - { - return PrincipalUtil.getSubjectX509Principal(cert); - } - catch (CertificateEncodingException e) - { - throw new AnnotatedException("can't get subject principal.", e); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/PKIXPolicyNode.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/PKIXPolicyNode.java deleted file mode 100644 index 9cb2fbbfd..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/PKIXPolicyNode.java +++ /dev/null @@ -1,167 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.security.cert.PolicyNode; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -public class PKIXPolicyNode - implements PolicyNode -{ - protected List children; - protected int depth; - protected Set expectedPolicies; - protected PolicyNode parent; - protected Set policyQualifiers; - protected String validPolicy; - protected boolean critical; - - /* - * - * CONSTRUCTORS - * - */ - - public PKIXPolicyNode( - List _children, - int _depth, - Set _expectedPolicies, - PolicyNode _parent, - Set _policyQualifiers, - String _validPolicy, - boolean _critical) - { - children = _children; - depth = _depth; - expectedPolicies = _expectedPolicies; - parent = _parent; - policyQualifiers = _policyQualifiers; - validPolicy = _validPolicy; - critical = _critical; - } - - public void addChild( - PKIXPolicyNode _child) - { - children.add(_child); - _child.setParent(this); - } - - public Iterator getChildren() - { - return children.iterator(); - } - - public int getDepth() - { - return depth; - } - - public Set getExpectedPolicies() - { - return expectedPolicies; - } - - public PolicyNode getParent() - { - return parent; - } - - public Set getPolicyQualifiers() - { - return policyQualifiers; - } - - public String getValidPolicy() - { - return validPolicy; - } - - public boolean hasChildren() - { - return !children.isEmpty(); - } - - public boolean isCritical() - { - return critical; - } - - public void removeChild(PKIXPolicyNode _child) - { - children.remove(_child); - } - - public void setCritical(boolean _critical) - { - critical = _critical; - } - - public void setParent(PKIXPolicyNode _parent) - { - parent = _parent; - } - - public String toString() - { - return toString(""); - } - - public String toString(String _indent) - { - StringBuffer _buf = new StringBuffer(); - _buf.append(_indent); - _buf.append(validPolicy); - _buf.append(" {\n"); - - for(int i = 0; i < children.size(); i++) { - _buf.append(((PKIXPolicyNode)children.get(i)).toString(_indent + " ")); - } - - _buf.append(_indent); - _buf.append("}\n"); - return _buf.toString(); - } - - public Object clone() - { - return copy(); - } - - public PKIXPolicyNode copy() - { - HashSet _expectedPolicies = new HashSet(); - Iterator _iter = expectedPolicies.iterator(); - while (_iter.hasNext()) - { - _expectedPolicies.add(new String((String)_iter.next())); - } - - HashSet _policyQualifiers = new HashSet(); - _iter = policyQualifiers.iterator(); - while (_iter.hasNext()) - { - _policyQualifiers.add(new String((String)_iter.next())); - } - - PKIXPolicyNode _node = new PKIXPolicyNode(new ArrayList(), - depth, - _expectedPolicies, - null, - _policyQualifiers, - new String(validPolicy), - critical); - - _iter = children.iterator(); - while (_iter.hasNext()) - { - PKIXPolicyNode _child = ((PKIXPolicyNode)_iter.next()).copy(); - _child.setParent(_node); - _node.addChild(_child); - } - - return _node; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/ProviderUtil.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/ProviderUtil.java deleted file mode 100644 index a67007e6d..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/ProviderUtil.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.spongycastle.jce.provider; - -import org.spongycastle.jcajce.provider.config.ConfigurableProvider; -import org.spongycastle.jce.spec.ECParameterSpec; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -public class ProviderUtil -{ - private static final long MAX_MEMORY = Integer.MAX_VALUE; - - private static volatile ECParameterSpec ecImplicitCaParams; - - static void setParameter(String parameterName, Object parameter) - { - if (parameterName.equals(ConfigurableProvider.EC_IMPLICITLY_CA)) - { - if (parameter instanceof ECParameterSpec || parameter == null) - { - ecImplicitCaParams = (ECParameterSpec)parameter; - } - } - } - - public static ECParameterSpec getEcImplicitlyCa() - { - return ecImplicitCaParams; - } - - static int getReadLimit(InputStream in) - throws IOException - { - if (in instanceof ByteArrayInputStream) - { - return in.available(); - } - - if (MAX_MEMORY > Integer.MAX_VALUE) - { - return Integer.MAX_VALUE; - } - - return (int)MAX_MEMORY; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/RFC3280CertPathUtilities.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/RFC3280CertPathUtilities.java deleted file mode 100644 index 2be3e0c28..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/RFC3280CertPathUtilities.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.PublicKey; -import java.security.cert.CertPath; -import java.security.cert.CertPathBuilder; -import java.security.cert.CertPathBuilderException; -import java.security.cert.CertPathValidatorException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.PKIXCertPathChecker; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.security.cert.X509Extension; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Vector; - -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1TaggedObject; -import org.spongycastle.asn1.x509.BasicConstraints; -import org.spongycastle.asn1.x509.CRLDistPoint; -import org.spongycastle.asn1.x509.CRLReason; -import org.spongycastle.asn1.x509.DistributionPoint; -import org.spongycastle.asn1.x509.DistributionPointName; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.GeneralNames; -import org.spongycastle.asn1.x509.GeneralSubtree; -import org.spongycastle.asn1.x509.IssuingDistributionPoint; -import org.spongycastle.asn1.x509.NameConstraints; -import org.spongycastle.asn1.x509.PolicyInformation; -import org.spongycastle.asn1.x509.X509Extensions; -import org.spongycastle.asn1.x509.X509Name; -import org.spongycastle.util.Arrays; - -public class RFC3280CertPathUtilities -{ - public static final String CERTIFICATE_POLICIES = X509Extensions.CertificatePolicies.getId(); - - public static final String POLICY_MAPPINGS = X509Extensions.PolicyMappings.getId(); - - public static final String INHIBIT_ANY_POLICY = X509Extensions.InhibitAnyPolicy.getId(); - - public static final String ISSUING_DISTRIBUTION_POINT = X509Extensions.IssuingDistributionPoint.getId(); - - public static final String FRESHEST_CRL = X509Extensions.FreshestCRL.getId(); - - public static final String DELTA_CRL_INDICATOR = X509Extensions.DeltaCRLIndicator.getId(); - - public static final String POLICY_CONSTRAINTS = X509Extensions.PolicyConstraints.getId(); - - public static final String BASIC_CONSTRAINTS = X509Extensions.BasicConstraints.getId(); - - public static final String CRL_DISTRIBUTION_POINTS = X509Extensions.CRLDistributionPoints.getId(); - - public static final String SUBJECT_ALTERNATIVE_NAME = X509Extensions.SubjectAlternativeName.getId(); - - public static final String NAME_CONSTRAINTS = X509Extensions.NameConstraints.getId(); - - public static final String AUTHORITY_KEY_IDENTIFIER = X509Extensions.AuthorityKeyIdentifier.getId(); - - public static final String KEY_USAGE = X509Extensions.KeyUsage.getId(); - - public static final String CRL_NUMBER = X509Extensions.CRLNumber.getId(); - - public static final String ANY_POLICY = "2.5.29.32.0"; - - /* - * key usage bits - */ - public static final int KEY_CERT_SIGN = 5; - - public static final int CRL_SIGN = 6; - -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/X509CRLObject.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/X509CRLObject.java deleted file mode 100644 index ff7745287..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/X509CRLObject.java +++ /dev/null @@ -1,554 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Principal; -import java.security.PublicKey; -import java.security.Signature; -import java.security.SignatureException; -import java.security.cert.CRLException; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509CRL; -import java.security.cert.X509CRLEntry; -import java.security.cert.X509Certificate; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.util.ASN1Dump; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x509.CRLDistPoint; -import org.spongycastle.asn1.x509.CRLNumber; -import org.spongycastle.asn1.x509.CertificateList; -import org.spongycastle.asn1.x509.Extension; -import org.spongycastle.asn1.x509.Extensions; -import org.spongycastle.asn1.x509.GeneralNames; -import org.spongycastle.asn1.x509.IssuingDistributionPoint; -import org.spongycastle.asn1.x509.TBSCertList; -import org.spongycastle.jce.X509Principal; -import org.spongycastle.util.encoders.Hex; -import org.spongycastle.x509.extension.X509ExtensionUtil; - -/** - * The following extensions are listed in RFC 2459 as relevant to CRLs - * - * Authority Key Identifier - * Issuer Alternative Name - * CRL Number - * Delta CRL Indicator (critical) - * Issuing Distribution Point (critical) - */ -public class X509CRLObject - extends X509CRL -{ - private CertificateList c; - private String sigAlgName; - private byte[] sigAlgParams; - private boolean isIndirect; - - static boolean isIndirectCRL(X509CRL crl) - throws CRLException - { - try - { - byte[] idp = crl.getExtensionValue(Extension.issuingDistributionPoint.getId()); - return idp != null - && IssuingDistributionPoint.getInstance(X509ExtensionUtil.fromExtensionValue(idp)).isIndirectCRL(); - } - catch (Exception e) - { - throw new ExtCRLException( - "Exception reading IssuingDistributionPoint", e); - } - } - - public X509CRLObject( - CertificateList c) - throws CRLException - { - this.c = c; - - try - { - this.sigAlgName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm()); - - if (c.getSignatureAlgorithm().getParameters() != null) - { - this.sigAlgParams = ((ASN1Encodable)c.getSignatureAlgorithm().getParameters()).toASN1Primitive().getEncoded(ASN1Encoding.DER); - } - else - { - this.sigAlgParams = null; - } - - this.isIndirect = isIndirectCRL(this); - } - catch (Exception e) - { - throw new CRLException("CRL contents invalid: " + e); - } - } - - /** - * Will return true if any extensions are present and marked - * as critical as we currently dont handle any extensions! - */ - public boolean hasUnsupportedCriticalExtension() - { - Set extns = getCriticalExtensionOIDs(); - - if (extns == null) - { - return false; - } - - extns.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT); - extns.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR); - - return !extns.isEmpty(); - } - - private Set getExtensionOIDs(boolean critical) - { - if (this.getVersion() == 2) - { - Extensions extensions = c.getTBSCertList().getExtensions(); - - if (extensions != null) - { - Set set = new HashSet(); - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (critical == ext.isCritical()) - { - set.add(oid.getId()); - } - } - - return set; - } - } - - return null; - } - - public Set getCriticalExtensionOIDs() - { - return getExtensionOIDs(true); - } - - public Set getNonCriticalExtensionOIDs() - { - return getExtensionOIDs(false); - } - - public byte[] getExtensionValue(String oid) - { - Extensions exts = c.getTBSCertList().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - } - - return null; - } - - public byte[] getEncoded() - throws CRLException - { - try - { - return c.getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CRLException(e.toString()); - } - } - - public void verify(PublicKey key) - throws CRLException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - verify(key, BouncyCastleProvider.PROVIDER_NAME); - } - - public void verify(PublicKey key, String sigProvider) - throws CRLException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - if (!c.getSignatureAlgorithm().equals(c.getTBSCertList().getSignature())) - { - throw new CRLException("Signature algorithm on CertificateList does not match TBSCertList."); - } - - Signature sig; - - if (sigProvider != null) - { - sig = Signature.getInstance(getSigAlgName(), sigProvider); - } - else - { - sig = Signature.getInstance(getSigAlgName()); - } - - sig.initVerify(key); - sig.update(this.getTBSCertList()); - - if (!sig.verify(this.getSignature())) - { - throw new SignatureException("CRL does not verify with supplied public key."); - } - } - - public int getVersion() - { - return c.getVersionNumber(); - } - - public Principal getIssuerDN() - { - return new X509Principal(X500Name.getInstance(c.getIssuer().toASN1Primitive())); - } - - public Date getThisUpdate() - { - return c.getThisUpdate().getDate(); - } - - public Date getNextUpdate() - { - if (c.getNextUpdate() != null) - { - return c.getNextUpdate().getDate(); - } - - return null; - } - - private Set loadCRLEntries() - { - Set entrySet = new HashSet(); - Enumeration certs = c.getRevokedCertificateEnumeration(); - - X500Name previousCertificateIssuer = c.getIssuer(); - while (certs.hasMoreElements()) - { - TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)certs.nextElement(); - X509CRLEntryObject crlEntry = new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer); - entrySet.add(crlEntry); - if (isIndirect && entry.hasExtensions()) - { - Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); - - if (currentCaName != null) - { - previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); - } - } - } - - return entrySet; - } - - public X509CRLEntry getRevokedCertificate(BigInteger serialNumber) - { - Enumeration certs = c.getRevokedCertificateEnumeration(); - - X500Name previousCertificateIssuer = c.getIssuer(); - while (certs.hasMoreElements()) - { - TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)certs.nextElement(); - - if (serialNumber.equals(entry.getUserCertificate().getValue())) - { - return new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer); - } - - if (isIndirect && entry.hasExtensions()) - { - Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); - - if (currentCaName != null) - { - previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); - } - } - } - - return null; - } - - public Set getRevokedCertificates() - { - Set entrySet = loadCRLEntries(); - - if (!entrySet.isEmpty()) - { - return Collections.unmodifiableSet(entrySet); - } - - return null; - } - - public byte[] getTBSCertList() - throws CRLException - { - try - { - return c.getTBSCertList().getEncoded("DER"); - } - catch (IOException e) - { - throw new CRLException(e.toString()); - } - } - - public byte[] getSignature() - { - return c.getSignature().getBytes(); - } - - public String getSigAlgName() - { - return sigAlgName; - } - - public String getSigAlgOID() - { - return c.getSignatureAlgorithm().getAlgorithm().getId(); - } - - public byte[] getSigAlgParams() - { - if (sigAlgParams != null) - { - byte[] tmp = new byte[sigAlgParams.length]; - - System.arraycopy(sigAlgParams, 0, tmp, 0, tmp.length); - - return tmp; - } - - return null; - } - - /** - * Returns a string representation of this CRL. - * - * @return a string representation of this CRL. - */ - public String toString() - { - StringBuffer buf = new StringBuffer(); - String nl = System.getProperty("line.separator"); - - buf.append(" Version: ").append(this.getVersion()).append( - nl); - buf.append(" IssuerDN: ").append(this.getIssuerDN()) - .append(nl); - buf.append(" This update: ").append(this.getThisUpdate()) - .append(nl); - buf.append(" Next update: ").append(this.getNextUpdate()) - .append(nl); - buf.append(" Signature Algorithm: ").append(this.getSigAlgName()) - .append(nl); - - byte[] sig = this.getSignature(); - - buf.append(" Signature: ").append( - new String(Hex.encode(sig, 0, 20))).append(nl); - for (int i = 20; i < sig.length; i += 20) - { - if (i < sig.length - 20) - { - buf.append(" ").append( - new String(Hex.encode(sig, i, 20))).append(nl); - } - else - { - buf.append(" ").append( - new String(Hex.encode(sig, i, sig.length - i))).append(nl); - } - } - - Extensions extensions = c.getTBSCertList().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - if (e.hasMoreElements()) - { - buf.append(" Extensions: ").append(nl); - } - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (ext.getExtnValue() != null) - { - byte[] octs = ext.getExtnValue().getOctets(); - ASN1InputStream dIn = new ASN1InputStream(octs); - buf.append(" critical(").append( - ext.isCritical()).append(") "); - try - { - if (oid.equals(Extension.cRLNumber)) - { - buf.append( - new CRLNumber(ASN1Integer.getInstance( - dIn.readObject()).getPositiveValue())) - .append(nl); - } - else if (oid.equals(Extension.deltaCRLIndicator)) - { - buf.append( - "Base CRL: " - + new CRLNumber(ASN1Integer.getInstance( - dIn.readObject()).getPositiveValue())) - .append(nl); - } - else if (oid - .equals(Extension.issuingDistributionPoint)) - { - buf.append( - IssuingDistributionPoint.getInstance(dIn.readObject())).append(nl); - } - else if (oid - .equals(Extension.cRLDistributionPoints)) - { - buf.append( - CRLDistPoint.getInstance(dIn.readObject())).append(nl); - } - else if (oid.equals(Extension.freshestCRL)) - { - buf.append( - CRLDistPoint.getInstance(dIn.readObject())).append(nl); - } - else - { - buf.append(oid.getId()); - buf.append(" value = ").append( - ASN1Dump.dumpAsString(dIn.readObject())) - .append(nl); - } - } - catch (Exception ex) - { - buf.append(oid.getId()); - buf.append(" value = ").append("*****").append(nl); - } - } - else - { - buf.append(nl); - } - } - } - Set set = getRevokedCertificates(); - if (set != null) - { - Iterator it = set.iterator(); - while (it.hasNext()) - { - buf.append(it.next()); - buf.append(nl); - } - } - return buf.toString(); - } - - /** - * Checks whether the given certificate is on this CRL. - * - * @param cert the certificate to check for. - * @return true if the given certificate is on this CRL, - * false otherwise. - */ - public boolean isRevoked(Certificate cert) - { - if (!cert.getType().equals("X.509")) - { - throw new RuntimeException("X.509 CRL used with non X.509 Cert"); - } - - TBSCertList.CRLEntry[] certs = c.getRevokedCertificates(); - - X500Name caName = c.getIssuer(); - - if (certs != null) - { - BigInteger serial = ((X509Certificate)cert).getSerialNumber(); - - for (int i = 0; i < certs.length; i++) - { - if (isIndirect && certs[i].hasExtensions()) - { - Extension currentCaName = certs[i].getExtensions().getExtension(Extension.certificateIssuer); - - if (currentCaName != null) - { - caName = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); - } - } - - if (certs[i].getUserCertificate().getValue().equals(serial)) - { - X500Name issuer; - - try - { - issuer = org.spongycastle.asn1.x509.Certificate.getInstance(cert.getEncoded()).getIssuer(); - } - catch (CertificateEncodingException e) - { - throw new RuntimeException("Cannot process certificate"); - } - - if (!caName.equals(issuer)) - { - return false; - } - - return true; - } - } - } - - return false; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/X509CertificateObject.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/X509CertificateObject.java deleted file mode 100644 index cd1c6d7c9..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/jce/provider/X509CertificateObject.java +++ /dev/null @@ -1,856 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Principal; -import java.security.Provider; -import java.security.PublicKey; -import java.security.Security; -import java.security.Signature; -import java.security.SignatureException; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1OutputStream; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1String; -import org.spongycastle.asn1.DERBitString; -import org.spongycastle.asn1.DERIA5String; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.misc.MiscObjectIdentifiers; -import org.spongycastle.asn1.misc.NetscapeCertType; -import org.spongycastle.asn1.misc.NetscapeRevocationURL; -import org.spongycastle.asn1.misc.VerisignCzagExtension; -import org.spongycastle.asn1.util.ASN1Dump; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x500.style.RFC4519Style; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.BasicConstraints; -import org.spongycastle.asn1.x509.Extension; -import org.spongycastle.asn1.x509.Extensions; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.KeyUsage; -import org.spongycastle.jcajce.provider.asymmetric.util.PKCS12BagAttributeCarrierImpl; -import org.spongycastle.jce.X509Principal; -import org.spongycastle.jce.interfaces.PKCS12BagAttributeCarrier; -import org.spongycastle.util.Arrays; -import org.spongycastle.util.Integers; -import org.spongycastle.util.encoders.Hex; - -public class X509CertificateObject - extends X509Certificate - implements PKCS12BagAttributeCarrier -{ - private org.spongycastle.asn1.x509.Certificate c; - private BasicConstraints basicConstraints; - private boolean[] keyUsage; - private boolean hashValueSet; - private int hashValue; - - private PKCS12BagAttributeCarrier attrCarrier = new PKCS12BagAttributeCarrierImpl(); - - public X509CertificateObject( - org.spongycastle.asn1.x509.Certificate c) - throws CertificateParsingException - { - this.c = c; - - try - { - byte[] bytes = this.getExtensionBytes("2.5.29.19"); - - if (bytes != null) - { - basicConstraints = BasicConstraints.getInstance(ASN1Primitive.fromByteArray(bytes)); - } - } - catch (Exception e) - { - throw new CertificateParsingException("cannot construct BasicConstraints: " + e); - } - - try - { - byte[] bytes = this.getExtensionBytes("2.5.29.15"); - if (bytes != null) - { - DERBitString bits = DERBitString.getInstance(ASN1Primitive.fromByteArray(bytes)); - - bytes = bits.getBytes(); - int length = (bytes.length * 8) - bits.getPadBits(); - - keyUsage = new boolean[(length < 9) ? 9 : length]; - - for (int i = 0; i != length; i++) - { - keyUsage[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0; - } - } - else - { - keyUsage = null; - } - } - catch (Exception e) - { - throw new CertificateParsingException("cannot construct KeyUsage: " + e); - } - } - - public void checkValidity() - throws CertificateExpiredException, CertificateNotYetValidException - { - this.checkValidity(new Date()); - } - - public void checkValidity( - Date date) - throws CertificateExpiredException, CertificateNotYetValidException - { - if (date.getTime() > this.getNotAfter().getTime()) // for other VM compatibility - { - throw new CertificateExpiredException("certificate expired on " + c.getEndDate().getTime()); - } - - if (date.getTime() < this.getNotBefore().getTime()) - { - throw new CertificateNotYetValidException("certificate not valid till " + c.getStartDate().getTime()); - } - } - - public int getVersion() - { - return c.getVersionNumber(); - } - - public BigInteger getSerialNumber() - { - return c.getSerialNumber().getValue(); - } - - public Principal getIssuerDN() - { - try - { - return new X509Principal(X500Name.getInstance(c.getIssuer().getEncoded())); - } - catch (IOException e) - { - return null; - } - } - - public Principal getSubjectDN() - { - return new X509Principal(X500Name.getInstance(c.getSubject().toASN1Primitive())); - } - - public Date getNotBefore() - { - return c.getStartDate().getDate(); - } - - public Date getNotAfter() - { - return c.getEndDate().getDate(); - } - - public byte[] getTBSCertificate() - throws CertificateEncodingException - { - try - { - return c.getTBSCertificate().getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CertificateEncodingException(e.toString()); - } - } - - public byte[] getSignature() - { - return c.getSignature().getBytes(); - } - - /** - * return a more "meaningful" representation for the signature algorithm used in - * the certficate. - */ - public String getSigAlgName() - { - Provider prov = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME); - - if (prov != null) - { - String algName = prov.getProperty("Alg.Alias.Signature." + this.getSigAlgOID()); - - if (algName != null) - { - return algName; - } - } - - Provider[] provs = Security.getProviders(); - - // - // search every provider looking for a real algorithm - // - for (int i = 0; i != provs.length; i++) - { - String algName = provs[i].getProperty("Alg.Alias.Signature." + this.getSigAlgOID()); - if (algName != null) - { - return algName; - } - } - - return this.getSigAlgOID(); - } - - /** - * return the object identifier for the signature. - */ - public String getSigAlgOID() - { - return c.getSignatureAlgorithm().getAlgorithm().getId(); - } - - /** - * return the signature parameters, or null if there aren't any. - */ - public byte[] getSigAlgParams() - { - if (c.getSignatureAlgorithm().getParameters() != null) - { - try - { - return c.getSignatureAlgorithm().getParameters().toASN1Primitive().getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - return null; - } - } - else - { - return null; - } - } - - public boolean[] getIssuerUniqueID() - { - DERBitString id = c.getTBSCertificate().getIssuerUniqueId(); - - if (id != null) - { - byte[] bytes = id.getBytes(); - boolean[] boolId = new boolean[bytes.length * 8 - id.getPadBits()]; - - for (int i = 0; i != boolId.length; i++) - { - boolId[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0; - } - - return boolId; - } - - return null; - } - - public boolean[] getSubjectUniqueID() - { - DERBitString id = c.getTBSCertificate().getSubjectUniqueId(); - - if (id != null) - { - byte[] bytes = id.getBytes(); - boolean[] boolId = new boolean[bytes.length * 8 - id.getPadBits()]; - - for (int i = 0; i != boolId.length; i++) - { - boolId[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0; - } - - return boolId; - } - - return null; - } - - public boolean[] getKeyUsage() - { - return keyUsage; - } - - public List getExtendedKeyUsage() - throws CertificateParsingException - { - byte[] bytes = this.getExtensionBytes("2.5.29.37"); - - if (bytes != null) - { - try - { - ASN1InputStream dIn = new ASN1InputStream(bytes); - ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); - List list = new ArrayList(); - - for (int i = 0; i != seq.size(); i++) - { - list.add(((ASN1ObjectIdentifier)seq.getObjectAt(i)).getId()); - } - - return Collections.unmodifiableList(list); - } - catch (Exception e) - { - throw new CertificateParsingException("error processing extended key usage extension"); - } - } - - return null; - } - - public int getBasicConstraints() - { - if (basicConstraints != null) - { - if (basicConstraints.isCA()) - { - if (basicConstraints.getPathLenConstraint() == null) - { - return Integer.MAX_VALUE; - } - else - { - return basicConstraints.getPathLenConstraint().intValue(); - } - } - else - { - return -1; - } - } - - return -1; - } - - public Collection getSubjectAlternativeNames() - throws CertificateParsingException - { - return getAlternativeNames(getExtensionBytes(Extension.subjectAlternativeName.getId())); - } - - public Collection getIssuerAlternativeNames() - throws CertificateParsingException - { - return getAlternativeNames(getExtensionBytes(Extension.issuerAlternativeName.getId())); - } - - public Set getCriticalExtensionOIDs() - { - if (this.getVersion() == 3) - { - Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (ext.isCritical()) - { - set.add(oid.getId()); - } - } - - return set; - } - } - - return null; - } - - private byte[] getExtensionBytes(String oid) - { - Extensions exts = c.getTBSCertificate().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - if (ext != null) - { - return ext.getExtnValue().getOctets(); - } - } - - return null; - } - - public byte[] getExtensionValue(String oid) - { - Extensions exts = c.getTBSCertificate().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - } - - return null; - } - - public Set getNonCriticalExtensionOIDs() - { - if (this.getVersion() == 3) - { - Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (!ext.isCritical()) - { - set.add(oid.getId()); - } - } - - return set; - } - } - - return null; - } - - public boolean hasUnsupportedCriticalExtension() - { - if (this.getVersion() == 3) - { - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - String oidId = oid.getId(); - - if (oidId.equals(RFC3280CertPathUtilities.KEY_USAGE) - || oidId.equals(RFC3280CertPathUtilities.CERTIFICATE_POLICIES) - || oidId.equals(RFC3280CertPathUtilities.POLICY_MAPPINGS) - || oidId.equals(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY) - || oidId.equals(RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS) - || oidId.equals(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT) - || oidId.equals(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR) - || oidId.equals(RFC3280CertPathUtilities.POLICY_CONSTRAINTS) - || oidId.equals(RFC3280CertPathUtilities.BASIC_CONSTRAINTS) - || oidId.equals(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME) - || oidId.equals(RFC3280CertPathUtilities.NAME_CONSTRAINTS)) - { - continue; - } - - Extension ext = extensions.getExtension(oid); - - if (ext.isCritical()) - { - return true; - } - } - } - } - - return false; - } - - public PublicKey getPublicKey() - { - try - { - return BouncyCastleProvider.getPublicKey(c.getSubjectPublicKeyInfo()); - } - catch (IOException e) - { - return null; // should never happen... - } - } - - public byte[] getEncoded() - throws CertificateEncodingException - { - try - { - return c.getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CertificateEncodingException(e.toString()); - } - } - - public boolean equals( - Object o) - { - if (o == this) - { - return true; - } - - if (!(o instanceof Certificate)) - { - return false; - } - - Certificate other = (Certificate)o; - - try - { - byte[] b1 = this.getEncoded(); - byte[] b2 = other.getEncoded(); - - return Arrays.areEqual(b1, b2); - } - catch (CertificateEncodingException e) - { - return false; - } - } - - public synchronized int hashCode() - { - if (!hashValueSet) - { - hashValue = calculateHashCode(); - hashValueSet = true; - } - - return hashValue; - } - - private int calculateHashCode() - { - try - { - int hashCode = 0; - byte[] certData = this.getEncoded(); - for (int i = 1; i < certData.length; i++) - { - hashCode += certData[i] * i; - } - return hashCode; - } - catch (CertificateEncodingException e) - { - return 0; - } - } - - public void setBagAttribute( - ASN1ObjectIdentifier oid, - ASN1Encodable attribute) - { - attrCarrier.setBagAttribute(oid, attribute); - } - - public ASN1Encodable getBagAttribute( - ASN1ObjectIdentifier oid) - { - return attrCarrier.getBagAttribute(oid); - } - - public Enumeration getBagAttributeKeys() - { - return attrCarrier.getBagAttributeKeys(); - } - - public String toString() - { - StringBuffer buf = new StringBuffer(); - String nl = System.getProperty("line.separator"); - - buf.append(" [0] Version: ").append(this.getVersion()).append(nl); - buf.append(" SerialNumber: ").append(this.getSerialNumber()).append(nl); - buf.append(" IssuerDN: ").append(this.getIssuerDN()).append(nl); - buf.append(" Start Date: ").append(this.getNotBefore()).append(nl); - buf.append(" Final Date: ").append(this.getNotAfter()).append(nl); - buf.append(" SubjectDN: ").append(this.getSubjectDN()).append(nl); - buf.append(" Public Key: ").append(this.getPublicKey()).append(nl); - buf.append(" Signature Algorithm: ").append(this.getSigAlgName()).append(nl); - - byte[] sig = this.getSignature(); - - buf.append(" Signature: ").append(new String(Hex.encode(sig, 0, 20))).append(nl); - for (int i = 20; i < sig.length; i += 20) - { - if (i < sig.length - 20) - { - buf.append(" ").append(new String(Hex.encode(sig, i, 20))).append(nl); - } - else - { - buf.append(" ").append(new String(Hex.encode(sig, i, sig.length - i))).append(nl); - } - } - - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - if (e.hasMoreElements()) - { - buf.append(" Extensions: \n"); - } - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (ext.getExtnValue() != null) - { - byte[] octs = ext.getExtnValue().getOctets(); - ASN1InputStream dIn = new ASN1InputStream(octs); - buf.append(" critical(").append(ext.isCritical()).append(") "); - try - { - if (oid.equals(Extension.basicConstraints)) - { - buf.append(BasicConstraints.getInstance(dIn.readObject())).append(nl); - } - else if (oid.equals(Extension.keyUsage)) - { - buf.append(KeyUsage.getInstance(dIn.readObject())).append(nl); - } - else if (oid.equals(MiscObjectIdentifiers.netscapeCertType)) - { - buf.append(new NetscapeCertType((DERBitString)dIn.readObject())).append(nl); - } - else if (oid.equals(MiscObjectIdentifiers.netscapeRevocationURL)) - { - buf.append(new NetscapeRevocationURL((DERIA5String)dIn.readObject())).append(nl); - } - else if (oid.equals(MiscObjectIdentifiers.verisignCzagExtension)) - { - buf.append(new VerisignCzagExtension((DERIA5String)dIn.readObject())).append(nl); - } - else - { - buf.append(oid.getId()); - buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl); - //buf.append(" value = ").append("*****").append(nl); - } - } - catch (Exception ex) - { - buf.append(oid.getId()); - // buf.append(" value = ").append(new String(Hex.encode(ext.getExtnValue().getOctets()))).append(nl); - buf.append(" value = ").append("*****").append(nl); - } - } - else - { - buf.append(nl); - } - } - } - - return buf.toString(); - } - - public final void verify( - PublicKey key) - throws CertificateException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - Signature signature; - String sigName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm()); - - try - { - signature = Signature.getInstance(sigName, BouncyCastleProvider.PROVIDER_NAME); - } - catch (Exception e) - { - signature = Signature.getInstance(sigName); - } - - checkSignature(key, signature); - } - - public final void verify( - PublicKey key, - String sigProvider) - throws CertificateException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - String sigName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm()); - Signature signature = Signature.getInstance(sigName, sigProvider); - - checkSignature(key, signature); - } - - private void checkSignature( - PublicKey key, - Signature signature) - throws CertificateException, NoSuchAlgorithmException, - SignatureException, InvalidKeyException - { - if (!isAlgIdEqual(c.getSignatureAlgorithm(), c.getTBSCertificate().getSignature())) - { - throw new CertificateException("signature algorithm in TBS cert not same as outer cert"); - } - - ASN1Encodable params = c.getSignatureAlgorithm().getParameters(); - - // TODO This should go after the initVerify? - X509SignatureUtil.setSignatureParameters(signature, params); - - signature.initVerify(key); - - signature.update(this.getTBSCertificate()); - - if (!signature.verify(this.getSignature())) - { - throw new SignatureException("certificate does not verify with supplied key"); - } - } - - private boolean isAlgIdEqual(AlgorithmIdentifier id1, AlgorithmIdentifier id2) - { - if (!id1.getAlgorithm().equals(id2.getAlgorithm())) - { - return false; - } - - if (id1.getParameters() == null) - { - if (id2.getParameters() != null && !id2.getParameters().equals(DERNull.INSTANCE)) - { - return false; - } - - return true; - } - - if (id2.getParameters() == null) - { - if (id1.getParameters() != null && !id1.getParameters().equals(DERNull.INSTANCE)) - { - return false; - } - - return true; - } - - return id1.getParameters().equals(id2.getParameters()); - } - - private static Collection getAlternativeNames(byte[] extVal) - throws CertificateParsingException - { - if (extVal == null) - { - return null; - } - try - { - Collection temp = new ArrayList(); - Enumeration it = ASN1Sequence.getInstance(extVal).getObjects(); - while (it.hasMoreElements()) - { - GeneralName genName = GeneralName.getInstance(it.nextElement()); - List list = new ArrayList(); - list.add(Integers.valueOf(genName.getTagNo())); - switch (genName.getTagNo()) - { - case GeneralName.ediPartyName: - case GeneralName.x400Address: - case GeneralName.otherName: - list.add(genName.getEncoded()); - break; - case GeneralName.directoryName: - list.add(X500Name.getInstance(RFC4519Style.INSTANCE, genName.getName()).toString()); - break; - case GeneralName.dNSName: - case GeneralName.rfc822Name: - case GeneralName.uniformResourceIdentifier: - list.add(((ASN1String)genName.getName()).getString()); - break; - case GeneralName.registeredID: - list.add(ASN1ObjectIdentifier.getInstance(genName.getName()).getId()); - break; - case GeneralName.iPAddress: - byte[] addrBytes = DEROctetString.getInstance(genName.getName()).getOctets(); - list.add(addrBytes); - break; - default: - throw new IOException("Bad tag number: " + genName.getTagNo()); - } - - temp.add(list); - } - if (temp.size() == 0) - { - return null; - } - return Collections.unmodifiableCollection(temp); - } - catch (Exception e) - { - throw new CertificateParsingException(e.getMessage()); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/AttributeCertificateHolder.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/AttributeCertificateHolder.java deleted file mode 100644 index 644883d4e..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/AttributeCertificateHolder.java +++ /dev/null @@ -1,406 +0,0 @@ -package org.spongycastle.x509; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.Principal; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.GeneralNames; -import org.spongycastle.asn1.x509.Holder; -import org.spongycastle.asn1.x509.IssuerSerial; -import org.spongycastle.asn1.x509.ObjectDigestInfo; -import org.spongycastle.jce.PrincipalUtil; -import org.spongycastle.jce.X509Principal; -import java.security.cert.CertSelector; -import org.spongycastle.util.Arrays; -import org.spongycastle.util.Selector; - -/** - * The Holder object. - * - *

- *          Holder ::= SEQUENCE {
- *                baseCertificateID   [0] IssuerSerial OPTIONAL,
- *                         -- the issuer and serial number of
- *                         -- the holder's Public Key Certificate
- *                entityName          [1] GeneralNames OPTIONAL,
- *                         -- the name of the claimant or role
- *                objectDigestInfo    [2] ObjectDigestInfo OPTIONAL
- *                         -- used to directly authenticate the holder,
- *                         -- for example, an executable
- *          }
- * 
- * @deprecated use org.spongycastle.cert.AttributeCertificateHolder - */ -public class AttributeCertificateHolder - implements CertSelector, Selector -{ - final Holder holder; - - AttributeCertificateHolder(ASN1Sequence seq) - { - holder = Holder.getInstance(seq); - } - - public AttributeCertificateHolder(X509Principal issuerName, - BigInteger serialNumber) - { - holder = new org.spongycastle.asn1.x509.Holder(new IssuerSerial( - new GeneralNames(new GeneralName(issuerName)), - new ASN1Integer(serialNumber))); - } - - public AttributeCertificateHolder(X509Certificate cert) - throws CertificateParsingException - { - X509Principal name; - - try - { - name = PrincipalUtil.getIssuerX509Principal(cert); - } - catch (Exception e) - { - throw new CertificateParsingException(e.getMessage()); - } - - holder = new Holder(new IssuerSerial(generateGeneralNames(name), - new ASN1Integer(cert.getSerialNumber()))); - } - - public AttributeCertificateHolder(X509Principal principal) - { - holder = new Holder(generateGeneralNames(principal)); - } - - /** - * Constructs a holder for v2 attribute certificates with a hash value for - * some type of object. - *

- * digestedObjectType can be one of the following: - *

    - *
  • 0 - publicKey - A hash of the public key of the holder must be - * passed. - *
  • 1 - publicKeyCert - A hash of the public key certificate of the - * holder must be passed. - *
  • 2 - otherObjectDigest - A hash of some other object type must be - * passed. otherObjectTypeID must not be empty. - *
- *

- * This cannot be used if a v1 attribute certificate is used. - * - * @param digestedObjectType The digest object type. - * @param digestAlgorithm The algorithm identifier for the hash. - * @param otherObjectTypeID The object type ID if - * digestedObjectType is - * otherObjectDigest. - * @param objectDigest The hash value. - */ - public AttributeCertificateHolder(int digestedObjectType, - String digestAlgorithm, String otherObjectTypeID, byte[] objectDigest) - { - holder = new Holder(new ObjectDigestInfo(digestedObjectType, - new ASN1ObjectIdentifier(otherObjectTypeID), new AlgorithmIdentifier(digestAlgorithm), Arrays - .clone(objectDigest))); - } - - /** - * Returns the digest object type if an object digest info is used. - *

- *

    - *
  • 0 - publicKey - A hash of the public key of the holder must be - * passed. - *
  • 1 - publicKeyCert - A hash of the public key certificate of the - * holder must be passed. - *
  • 2 - otherObjectDigest - A hash of some other object type must be - * passed. otherObjectTypeID must not be empty. - *
- * - * @return The digest object type or -1 if no object digest info is set. - */ - public int getDigestedObjectType() - { - if (holder.getObjectDigestInfo() != null) - { - return holder.getObjectDigestInfo().getDigestedObjectType() - .getValue().intValue(); - } - return -1; - } - - /** - * Returns the other object type ID if an object digest info is used. - * - * @return The other object type ID or null if no object - * digest info is set. - */ - public String getDigestAlgorithm() - { - if (holder.getObjectDigestInfo() != null) - { - return holder.getObjectDigestInfo().getDigestAlgorithm().getObjectId() - .getId(); - } - return null; - } - - /** - * Returns the hash if an object digest info is used. - * - * @return The hash or null if no object digest info is set. - */ - public byte[] getObjectDigest() - { - if (holder.getObjectDigestInfo() != null) - { - return holder.getObjectDigestInfo().getObjectDigest().getBytes(); - } - return null; - } - - /** - * Returns the digest algorithm ID if an object digest info is used. - * - * @return The digest algorithm ID or null if no object - * digest info is set. - */ - public String getOtherObjectTypeID() - { - if (holder.getObjectDigestInfo() != null) - { - holder.getObjectDigestInfo().getOtherObjectTypeID().getId(); - } - return null; - } - - private GeneralNames generateGeneralNames(X509Principal principal) - { - return new GeneralNames(new GeneralName(principal)); - } - - private boolean matchesDN(X509Principal subject, GeneralNames targets) - { - GeneralName[] names = targets.getNames(); - - for (int i = 0; i != names.length; i++) - { - GeneralName gn = names[i]; - - if (gn.getTagNo() == GeneralName.directoryName) - { - try - { - if (new X509Principal(((ASN1Encodable)gn.getName()).toASN1Primitive() - .getEncoded()).equals(subject)) - { - return true; - } - } - catch (IOException e) - { - } - } - } - - return false; - } - - private Object[] getNames(GeneralName[] names) - { - List l = new ArrayList(names.length); - - for (int i = 0; i != names.length; i++) - { - if (names[i].getTagNo() == GeneralName.directoryName) - { - try - { - l.add(new X509Principal( - ((ASN1Encodable)names[i].getName()).toASN1Primitive().getEncoded())); - } - catch (IOException e) - { - throw new RuntimeException("badly formed Name object"); - } - } - } - - return l.toArray(new Object[l.size()]); - } - - private Principal[] getPrincipals(GeneralNames names) - { - Object[] p = this.getNames(names.getNames()); - List l = new ArrayList(); - - for (int i = 0; i != p.length; i++) - { - if (p[i] instanceof Principal) - { - l.add(p[i]); - } - } - - return (Principal[])l.toArray(new Principal[l.size()]); - } - - /** - * Return any principal objects inside the attribute certificate holder - * entity names field. - * - * @return an array of Principal objects (usually X509Principal), null if no - * entity names field is set. - */ - public Principal[] getEntityNames() - { - if (holder.getEntityName() != null) - { - return getPrincipals(holder.getEntityName()); - } - - return null; - } - - /** - * Return the principals associated with the issuer attached to this holder - * - * @return an array of principals, null if no BaseCertificateID is set. - */ - public Principal[] getIssuer() - { - if (holder.getBaseCertificateID() != null) - { - return getPrincipals(holder.getBaseCertificateID().getIssuer()); - } - - return null; - } - - /** - * Return the serial number associated with the issuer attached to this - * holder. - * - * @return the certificate serial number, null if no BaseCertificateID is - * set. - */ - public BigInteger getSerialNumber() - { - if (holder.getBaseCertificateID() != null) - { - return holder.getBaseCertificateID().getSerial().getValue(); - } - - return null; - } - - public Object clone() - { - return new AttributeCertificateHolder((ASN1Sequence)holder - .toASN1Object()); - } - - public boolean match(Certificate cert) - { - if (!(cert instanceof X509Certificate)) - { - return false; - } - - X509Certificate x509Cert = (X509Certificate)cert; - - try - { - if (holder.getBaseCertificateID() != null) - { - return holder.getBaseCertificateID().getSerial().getValue().equals(x509Cert.getSerialNumber()) - && matchesDN(PrincipalUtil.getIssuerX509Principal(x509Cert), holder.getBaseCertificateID().getIssuer()); - } - - if (holder.getEntityName() != null) - { - if (matchesDN(PrincipalUtil.getSubjectX509Principal(x509Cert), - holder.getEntityName())) - { - return true; - } - } - if (holder.getObjectDigestInfo() != null) - { - MessageDigest md = null; - try - { - md = MessageDigest.getInstance(getDigestAlgorithm(), "SC"); - - } - catch (Exception e) - { - return false; - } - switch (getDigestedObjectType()) - { - case ObjectDigestInfo.publicKey: - // TODO: DSA Dss-parms - md.update(cert.getPublicKey().getEncoded()); - break; - case ObjectDigestInfo.publicKeyCert: - md.update(cert.getEncoded()); - break; - } - if (!Arrays.areEqual(md.digest(), getObjectDigest())) - { - return false; - } - } - } - catch (CertificateEncodingException e) - { - return false; - } - - return false; - } - - public boolean equals(Object obj) - { - if (obj == this) - { - return true; - } - - if (!(obj instanceof AttributeCertificateHolder)) - { - return false; - } - - AttributeCertificateHolder other = (AttributeCertificateHolder)obj; - - return this.holder.equals(other.holder); - } - - public int hashCode() - { - return this.holder.hashCode(); - } - - public boolean match(Object obj) - { - if (!(obj instanceof X509Certificate)) - { - return false; - } - - return match((Certificate)obj); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/AttributeCertificateIssuer.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/AttributeCertificateIssuer.java deleted file mode 100644 index 383292d78..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/AttributeCertificateIssuer.java +++ /dev/null @@ -1,212 +0,0 @@ -package org.spongycastle.x509; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.x509.AttCertIssuer; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.GeneralNames; -import org.spongycastle.asn1.x509.V2Form; -import org.spongycastle.jce.PrincipalUtil; -import org.spongycastle.jce.X509Principal; -import org.spongycastle.util.Selector; - -import java.io.IOException; -import java.security.Principal; -import java.security.cert.CertSelector; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; - -/** - * Carrying class for an attribute certificate issuer. - */ -public class AttributeCertificateIssuer - implements CertSelector, Selector -{ - final ASN1Encodable form; - - /** - * @param issuer - */ - AttributeCertificateIssuer( - AttCertIssuer issuer) - { - form = issuer.getIssuer(); - } - - public AttributeCertificateIssuer( - X509Principal principal) - { - form = new V2Form(new GeneralNames(new GeneralName(principal))); - } - - private Object[] getNames() - { - GeneralNames name; - - if (form instanceof V2Form) - { - name = ((V2Form)form).getIssuerName(); - } - else - { - name = (GeneralNames)form; - } - - GeneralName[] names = name.getNames(); - - List l = new ArrayList(names.length); - - for (int i = 0; i != names.length; i++) - { - if (names[i].getTagNo() == GeneralName.directoryName) - { - try - { - l.add(new X509Principal(((ASN1Encodable)names[i].getName()).toASN1Primitive().getEncoded())); - } - catch (IOException e) - { - throw new RuntimeException("badly formed Name object"); - } - } - } - - return l.toArray(new Object[l.size()]); - } - - /** - * Return any principal objects inside the attribute certificate issuer object. - * - * @return an array of Principal objects (usually X509Principal) - */ - public Principal[] getPrincipals() - { - Object[] p = this.getNames(); - List l = new ArrayList(); - - for (int i = 0; i != p.length; i++) - { - if (p[i] instanceof Principal) - { - l.add(p[i]); - } - } - - return (Principal[])l.toArray(new Principal[l.size()]); - } - - private boolean matchesDN(X509Principal subject, GeneralNames targets) - { - GeneralName[] names = targets.getNames(); - - for (int i = 0; i != names.length; i++) - { - GeneralName gn = names[i]; - - if (gn.getTagNo() == GeneralName.directoryName) - { - try - { - if (new X509Principal(((ASN1Encodable)gn.getName()).toASN1Primitive().getEncoded()).equals(subject)) - { - return true; - } - } - catch (IOException e) - { - } - } - } - - return false; - } - - /* (non-Javadoc) - * @see java.security.cert.CertSelector#clone() - */ - public Object clone() - { - return new AttributeCertificateIssuer(AttCertIssuer.getInstance(form)); - } - - /* (non-Javadoc) - * @see java.security.cert.CertSelector#match(java.security.cert.Certificate) - */ - public boolean match(Certificate cert) - { - if (!(cert instanceof X509Certificate)) - { - return false; - } - - X509Certificate x509Cert = (X509Certificate)cert; - - try - { - if (form instanceof V2Form) - { - V2Form issuer = (V2Form)form; - if (issuer.getBaseCertificateID() != null) - { - return issuer.getBaseCertificateID().getSerial().getValue().equals(x509Cert.getSerialNumber()) - && matchesDN(PrincipalUtil.getIssuerX509Principal(x509Cert), issuer.getBaseCertificateID().getIssuer()); - } - - GeneralNames name = issuer.getIssuerName(); - if (matchesDN(PrincipalUtil.getSubjectX509Principal(x509Cert), name)) - { - return true; - } - } - else - { - GeneralNames name = (GeneralNames)form; - if (matchesDN(PrincipalUtil.getSubjectX509Principal(x509Cert), name)) - { - return true; - } - } - } - catch (CertificateEncodingException e) - { - return false; - } - - return false; - } - - public boolean equals(Object obj) - { - if (obj == this) - { - return true; - } - - if (!(obj instanceof AttributeCertificateIssuer)) - { - return false; - } - - AttributeCertificateIssuer other = (AttributeCertificateIssuer)obj; - - return this.form.equals(other.form); - } - - public int hashCode() - { - return this.form.hashCode(); - } - - public boolean match(Object obj) - { - if (!(obj instanceof X509Certificate)) - { - return false; - } - - return match((Certificate)obj); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509AttributeCertStoreSelector.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509AttributeCertStoreSelector.java deleted file mode 100644 index eafa21d0f..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509AttributeCertStoreSelector.java +++ /dev/null @@ -1,488 +0,0 @@ -package org.spongycastle.x509; - -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Object; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.Target; -import org.spongycastle.asn1.x509.TargetInformation; -import org.spongycastle.asn1.x509.Targets; -import org.spongycastle.asn1.x509.X509Extensions; -import org.spongycastle.util.Selector; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.X509CertSelector; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -/** - * This class is an Selector like implementation to select - * attribute certificates from a given set of criteria. - * - * @see org.spongycastle.x509.X509AttributeCertificate - * @see org.spongycastle.x509.X509Store - */ -public class X509AttributeCertStoreSelector - implements Selector -{ - - // TODO: name constraints??? - - private AttributeCertificateHolder holder; - - private AttributeCertificateIssuer issuer; - - private BigInteger serialNumber; - - private Date attributeCertificateValid; - - private X509AttributeCertificate attributeCert; - - private Collection targetNames = new HashSet(); - - private Collection targetGroups = new HashSet(); - - public X509AttributeCertStoreSelector() - { - super(); - } - - /** - * Decides if the given attribute certificate should be selected. - * - * @param obj The attribute certificate which should be checked. - * @return true if the attribute certificate can be selected, - * false otherwise. - */ - public boolean match(Object obj) - { - if (!(obj instanceof X509AttributeCertificate)) - { - return false; - } - - X509AttributeCertificate attrCert = (X509AttributeCertificate) obj; - - if (this.attributeCert != null) - { - if (!this.attributeCert.equals(attrCert)) - { - return false; - } - } - if (serialNumber != null) - { - if (!attrCert.getSerialNumber().equals(serialNumber)) - { - return false; - } - } - if (holder != null) - { - if (!attrCert.getHolder().equals(holder)) - { - return false; - } - } - if (issuer != null) - { - if (!attrCert.getIssuer().equals(issuer)) - { - return false; - } - } - - if (attributeCertificateValid != null) - { - try - { - attrCert.checkValidity(attributeCertificateValid); - } - catch (CertificateExpiredException e) - { - return false; - } - catch (CertificateNotYetValidException e) - { - return false; - } - } - if (!targetNames.isEmpty() || !targetGroups.isEmpty()) - { - - byte[] targetInfoExt = attrCert - .getExtensionValue(X509Extensions.TargetInformation.getId()); - if (targetInfoExt != null) - { - TargetInformation targetinfo; - try - { - targetinfo = TargetInformation - .getInstance(new ASN1InputStream( - ((DEROctetString) DEROctetString - .fromByteArray(targetInfoExt)).getOctets()) - .readObject()); - } - catch (IOException e) - { - return false; - } - catch (IllegalArgumentException e) - { - return false; - } - Targets[] targetss = targetinfo.getTargetsObjects(); - if (!targetNames.isEmpty()) - { - boolean found = false; - - for (int i=0; inull
is - * given any will do. - * - * @param attributeCert The attribute certificate to set. - */ - public void setAttributeCert(X509AttributeCertificate attributeCert) - { - this.attributeCert = attributeCert; - } - - /** - * Get the criteria for the validity. - * - * @return Returns the attributeCertificateValid. - */ - public Date getAttributeCertificateValid() - { - if (attributeCertificateValid != null) - { - return new Date(attributeCertificateValid.getTime()); - } - - return null; - } - - /** - * Set the time, when the certificate must be valid. If null - * is given any will do. - * - * @param attributeCertificateValid The attribute certificate validation - * time to set. - */ - public void setAttributeCertificateValid(Date attributeCertificateValid) - { - if (attributeCertificateValid != null) - { - this.attributeCertificateValid = new Date(attributeCertificateValid - .getTime()); - } - else - { - this.attributeCertificateValid = null; - } - } - - /** - * Gets the holder. - * - * @return Returns the holder. - */ - public AttributeCertificateHolder getHolder() - { - return holder; - } - - /** - * Sets the holder. If null is given any will do. - * - * @param holder The holder to set. - */ - public void setHolder(AttributeCertificateHolder holder) - { - this.holder = holder; - } - - /** - * Returns the issuer criterion. - * - * @return Returns the issuer. - */ - public AttributeCertificateIssuer getIssuer() - { - return issuer; - } - - /** - * Sets the issuer the attribute certificate must have. If null - * is given any will do. - * - * @param issuer The issuer to set. - */ - public void setIssuer(AttributeCertificateIssuer issuer) - { - this.issuer = issuer; - } - - /** - * Gets the serial number the attribute certificate must have. - * - * @return Returns the serialNumber. - */ - public BigInteger getSerialNumber() - { - return serialNumber; - } - - /** - * Sets the serial number the attribute certificate must have. If - * null is given any will do. - * - * @param serialNumber The serialNumber to set. - */ - public void setSerialNumber(BigInteger serialNumber) - { - this.serialNumber = serialNumber; - } - - /** - * Adds a target name criterion for the attribute certificate to the target - * information extension criteria. The X509AttributeCertificate - * must contain at least one of the specified target names. - *

- * Each attribute certificate may contain a target information extension - * limiting the servers where this attribute certificate can be used. If - * this extension is not present, the attribute certificate is not targeted - * and may be accepted by any server. - * - * @param name The name as a GeneralName (not null) - */ - public void addTargetName(GeneralName name) - { - targetNames.add(name); - } - - /** - * Adds a target name criterion for the attribute certificate to the target - * information extension criteria. The X509AttributeCertificate - * must contain at least one of the specified target names. - *

- * Each attribute certificate may contain a target information extension - * limiting the servers where this attribute certificate can be used. If - * this extension is not present, the attribute certificate is not targeted - * and may be accepted by any server. - * - * @param name a byte array containing the name in ASN.1 DER encoded form of a GeneralName - * @throws IOException if a parsing error occurs. - */ - public void addTargetName(byte[] name) throws IOException - { - addTargetName(GeneralName.getInstance(ASN1Primitive.fromByteArray(name))); - } - - /** - * Adds a collection with target names criteria. If null is - * given any will do. - *

- * The collection consists of either GeneralName objects or byte[] arrays representing - * DER encoded GeneralName structures. - * - * @param names A collection of target names. - * @throws IOException if a parsing error occurs. - * @see #addTargetName(byte[]) - * @see #addTargetName(GeneralName) - */ - public void setTargetNames(Collection names) throws IOException - { - targetNames = extractGeneralNames(names); - } - - /** - * Gets the target names. The collection consists of Lists - * made up of an Integer in the first entry and a DER encoded - * byte array or a String in the second entry. - *

- * The returned collection is immutable. - * - * @return The collection of target names - * @see #setTargetNames(Collection) - */ - public Collection getTargetNames() - { - return Collections.unmodifiableCollection(targetNames); - } - - /** - * Adds a target group criterion for the attribute certificate to the target - * information extension criteria. The X509AttributeCertificate - * must contain at least one of the specified target groups. - *

- * Each attribute certificate may contain a target information extension - * limiting the servers where this attribute certificate can be used. If - * this extension is not present, the attribute certificate is not targeted - * and may be accepted by any server. - * - * @param group The group as GeneralName form (not null) - */ - public void addTargetGroup(GeneralName group) - { - targetGroups.add(group); - } - - /** - * Adds a target group criterion for the attribute certificate to the target - * information extension criteria. The X509AttributeCertificate - * must contain at least one of the specified target groups. - *

- * Each attribute certificate may contain a target information extension - * limiting the servers where this attribute certificate can be used. If - * this extension is not present, the attribute certificate is not targeted - * and may be accepted by any server. - * - * @param name a byte array containing the group in ASN.1 DER encoded form of a GeneralName - * @throws IOException if a parsing error occurs. - */ - public void addTargetGroup(byte[] name) throws IOException - { - addTargetGroup(GeneralName.getInstance(ASN1Primitive.fromByteArray(name))); - } - - /** - * Adds a collection with target groups criteria. If null is - * given any will do. - *

- * The collection consists of GeneralName objects or byte[]Lists - * made up of an Integer in the first entry and a DER encoded - * byte array or a String in the second entry. - *

- * The returned collection is immutable. - * - * @return The collection of target groups. - * @see #setTargetGroups(Collection) - */ - public Collection getTargetGroups() - { - return Collections.unmodifiableCollection(targetGroups); - } - - private Set extractGeneralNames(Collection names) - throws IOException - { - if (names == null || names.isEmpty()) - { - return new HashSet(); - } - Set temp = new HashSet(); - for (Iterator it = names.iterator(); it.hasNext();) - { - Object o = it.next(); - if (o instanceof GeneralName) - { - temp.add(o); - } - else - { - temp.add(GeneralName.getInstance(ASN1Primitive.fromByteArray((byte[])o))); - } - } - return temp; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509CRLStoreSelector.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509CRLStoreSelector.java deleted file mode 100644 index a6c8cc31f..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509CRLStoreSelector.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.spongycastle.x509; - -import org.spongycastle.util.Selector; - -import java.security.cert.X509CRLSelector; -import java.security.cert.CRL; - -public class X509CRLStoreSelector - extends X509CRLSelector - implements Selector -{ - public boolean match(Object obj) - { - if (!(obj instanceof CRL)) - { - return false; - } - - return super.match((CRL)obj); - } - - public boolean match(CRL obj) - { - return this.match((Object)obj); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509CertStoreSelector.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509CertStoreSelector.java deleted file mode 100644 index 2c0e6cc34..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509CertStoreSelector.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.spongycastle.x509; - -import org.spongycastle.util.Selector; - -import java.security.cert.X509CertSelector; -import java.security.cert.Certificate; - -public class X509CertStoreSelector - extends X509CertSelector - implements Selector -{ - public boolean match(Object obj) - { - if (!(obj instanceof Certificate)) - { - return false; - } - - return super.match((Certificate)obj); - } - - public boolean match(Certificate obj) - { - return this.match((Object)obj); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509Util.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509Util.java deleted file mode 100644 index 74aa897bb..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509Util.java +++ /dev/null @@ -1,397 +0,0 @@ -package org.spongycastle.x509; - -import java.io.IOException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.SecureRandom; -import java.security.Security; -import java.security.Signature; -import java.security.SignatureException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.spongycastle.asn1.nist.NISTObjectIdentifiers; -import org.spongycastle.asn1.oiw.OIWObjectIdentifiers; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.pkcs.RSASSAPSSparams; -import org.spongycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x9.X9ObjectIdentifiers; -import org.spongycastle.jce.X509Principal; -import org.spongycastle.util.Strings; - -class X509Util -{ - private static Hashtable algorithms = new Hashtable(); - private static Hashtable params = new Hashtable(); - private static Set noParams = new HashSet(); - - static - { - algorithms.put("MD2WITHRSAENCRYPTION", PKCSObjectIdentifiers.md2WithRSAEncryption); - algorithms.put("MD2WITHRSA", PKCSObjectIdentifiers.md2WithRSAEncryption); - algorithms.put("MD5WITHRSAENCRYPTION", PKCSObjectIdentifiers.md5WithRSAEncryption); - algorithms.put("MD5WITHRSA", PKCSObjectIdentifiers.md5WithRSAEncryption); - algorithms.put("SHA1WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha1WithRSAEncryption); - algorithms.put("SHA1WITHRSA", PKCSObjectIdentifiers.sha1WithRSAEncryption); - algorithms.put("SHA224WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha224WithRSAEncryption); - algorithms.put("SHA224WITHRSA", PKCSObjectIdentifiers.sha224WithRSAEncryption); - algorithms.put("SHA256WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha256WithRSAEncryption); - algorithms.put("SHA256WITHRSA", PKCSObjectIdentifiers.sha256WithRSAEncryption); - algorithms.put("SHA384WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha384WithRSAEncryption); - algorithms.put("SHA384WITHRSA", PKCSObjectIdentifiers.sha384WithRSAEncryption); - algorithms.put("SHA512WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha512WithRSAEncryption); - algorithms.put("SHA512WITHRSA", PKCSObjectIdentifiers.sha512WithRSAEncryption); - algorithms.put("SHA1WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA224WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA256WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA384WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA512WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160); - algorithms.put("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160); - algorithms.put("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128); - algorithms.put("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128); - algorithms.put("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256); - algorithms.put("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256); - algorithms.put("SHA1WITHDSA", X9ObjectIdentifiers.id_dsa_with_sha1); - algorithms.put("DSAWITHSHA1", X9ObjectIdentifiers.id_dsa_with_sha1); - algorithms.put("SHA224WITHDSA", NISTObjectIdentifiers.dsa_with_sha224); - algorithms.put("SHA256WITHDSA", NISTObjectIdentifiers.dsa_with_sha256); - algorithms.put("SHA384WITHDSA", NISTObjectIdentifiers.dsa_with_sha384); - algorithms.put("SHA512WITHDSA", NISTObjectIdentifiers.dsa_with_sha512); - algorithms.put("SHA1WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA1); - algorithms.put("ECDSAWITHSHA1", X9ObjectIdentifiers.ecdsa_with_SHA1); - algorithms.put("SHA224WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); - algorithms.put("SHA256WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); - algorithms.put("SHA384WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); - algorithms.put("SHA512WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); - algorithms.put("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); - algorithms.put("GOST3411WITHGOST3410-94", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); - algorithms.put("GOST3411WITHECGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - algorithms.put("GOST3411WITHECGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - algorithms.put("GOST3411WITHGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - - // - // According to RFC 3279, the ASN.1 encoding SHALL (id-dsa-with-sha1) or MUST (ecdsa-with-SHA*) omit the parameters field. - // The parameters field SHALL be NULL for RSA based signature algorithms. - // - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA1); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA224); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA256); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA384); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA512); - noParams.add(X9ObjectIdentifiers.id_dsa_with_sha1); - noParams.add(NISTObjectIdentifiers.dsa_with_sha224); - noParams.add(NISTObjectIdentifiers.dsa_with_sha256); - noParams.add(NISTObjectIdentifiers.dsa_with_sha384); - noParams.add(NISTObjectIdentifiers.dsa_with_sha512); - - // - // RFC 4491 - // - noParams.add(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); - noParams.add(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - - // - // explicit params - // - AlgorithmIdentifier sha1AlgId = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, new DERNull()); - params.put("SHA1WITHRSAANDMGF1", creatPSSParams(sha1AlgId, 20)); - - AlgorithmIdentifier sha224AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha224, new DERNull()); - params.put("SHA224WITHRSAANDMGF1", creatPSSParams(sha224AlgId, 28)); - - AlgorithmIdentifier sha256AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, new DERNull()); - params.put("SHA256WITHRSAANDMGF1", creatPSSParams(sha256AlgId, 32)); - - AlgorithmIdentifier sha384AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha384, new DERNull()); - params.put("SHA384WITHRSAANDMGF1", creatPSSParams(sha384AlgId, 48)); - - AlgorithmIdentifier sha512AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512, new DERNull()); - params.put("SHA512WITHRSAANDMGF1", creatPSSParams(sha512AlgId, 64)); - } - - private static RSASSAPSSparams creatPSSParams(AlgorithmIdentifier hashAlgId, int saltSize) - { - return new RSASSAPSSparams( - hashAlgId, - new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, hashAlgId), - new ASN1Integer(saltSize), - new ASN1Integer(1)); - } - - static ASN1ObjectIdentifier getAlgorithmOID( - String algorithmName) - { - algorithmName = Strings.toUpperCase(algorithmName); - - if (algorithms.containsKey(algorithmName)) - { - return (ASN1ObjectIdentifier)algorithms.get(algorithmName); - } - - return new ASN1ObjectIdentifier(algorithmName); - } - - static AlgorithmIdentifier getSigAlgID( - ASN1ObjectIdentifier sigOid, - String algorithmName) - { - if (noParams.contains(sigOid)) - { - return new AlgorithmIdentifier(sigOid); - } - - algorithmName = Strings.toUpperCase(algorithmName); - - if (params.containsKey(algorithmName)) - { - return new AlgorithmIdentifier(sigOid, (ASN1Encodable)params.get(algorithmName)); - } - else - { - return new AlgorithmIdentifier(sigOid, new DERNull()); - } - } - - static Iterator getAlgNames() - { - Enumeration e = algorithms.keys(); - List l = new ArrayList(); - - while (e.hasMoreElements()) - { - l.add(e.nextElement()); - } - - return l.iterator(); - } - - static Signature getSignatureInstance( - String algorithm) - throws NoSuchAlgorithmException - { - return Signature.getInstance(algorithm); - } - - static Signature getSignatureInstance( - String algorithm, - String provider) - throws NoSuchProviderException, NoSuchAlgorithmException - { - if (provider != null) - { - return Signature.getInstance(algorithm, provider); - } - else - { - return Signature.getInstance(algorithm); - } - } - - static byte[] calculateSignature( - ASN1ObjectIdentifier sigOid, - String sigName, - PrivateKey key, - SecureRandom random, - ASN1Encodable object) - throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException - { - Signature sig; - - if (sigOid == null) - { - throw new IllegalStateException("no signature algorithm specified"); - } - - sig = X509Util.getSignatureInstance(sigName); - - if (random != null) - { - sig.initSign(key); - } - else - { - sig.initSign(key); - } - - sig.update(object.toASN1Primitive().getEncoded(ASN1Encoding.DER)); - - return sig.sign(); - } - - static byte[] calculateSignature( - ASN1ObjectIdentifier sigOid, - String sigName, - String provider, - PrivateKey key, - SecureRandom random, - ASN1Encodable object) - throws IOException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException - { - Signature sig; - - if (sigOid == null) - { - throw new IllegalStateException("no signature algorithm specified"); - } - - sig = X509Util.getSignatureInstance(sigName, provider); - - if (random != null) - { - sig.initSign(key); - } - else - { - sig.initSign(key); - } - - sig.update(object.toASN1Primitive().getEncoded(ASN1Encoding.DER)); - - return sig.sign(); - } - - static class Implementation - { - Object engine; - Provider provider; - - Implementation( - Object engine, - Provider provider) - { - this.engine = engine; - this.provider = provider; - } - - Object getEngine() - { - return engine; - } - - Provider getProvider() - { - return provider; - } - } - - /** - * see if we can find an algorithm (or its alias and what it represents) in - * the property table for the given provider. - */ - static Implementation getImplementation( - String baseName, - String algorithm, - Provider prov) - throws NoSuchAlgorithmException - { - algorithm = Strings.toUpperCase(algorithm); - - String alias; - - while ((alias = prov.getProperty("Alg.Alias." + baseName + "." + algorithm)) != null) - { - algorithm = alias; - } - - String className = prov.getProperty(baseName + "." + algorithm); - - if (className != null) - { - try - { - Class cls; - ClassLoader clsLoader = prov.getClass().getClassLoader(); - - if (clsLoader != null) - { - cls = clsLoader.loadClass(className); - } - else - { - cls = Class.forName(className); - } - - return new Implementation(cls.newInstance(), prov); - } - catch (ClassNotFoundException e) - { - throw new IllegalStateException( - "algorithm " + algorithm + " in provider " + prov.getName() + " but no class \"" + className + "\" found!"); - } - catch (Exception e) - { - throw new IllegalStateException( - "algorithm " + algorithm + " in provider " + prov.getName() + " but class \"" + className + "\" inaccessible!"); - } - } - - throw new NoSuchAlgorithmException("cannot find implementation " + algorithm + " for provider " + prov.getName()); - } - - /** - * return an implementation for a given algorithm/provider. - * If the provider is null, we grab the first avalaible who has the required algorithm. - */ - static Implementation getImplementation( - String baseName, - String algorithm) - throws NoSuchAlgorithmException - { - Provider[] prov = Security.getProviders(); - - // - // search every provider looking for the algorithm we want. - // - for (int i = 0; i != prov.length; i++) - { - // - // try case insensitive - // - Implementation imp = getImplementation(baseName, Strings.toUpperCase(algorithm), prov[i]); - if (imp != null) - { - return imp; - } - - try - { - imp = getImplementation(baseName, algorithm, prov[i]); - } - catch (NoSuchAlgorithmException e) - { - // continue - } - } - - throw new NoSuchAlgorithmException("cannot find implementation " + algorithm); - } - - static Provider getProvider(String provider) - throws NoSuchProviderException - { - Provider prov = Security.getProvider(provider); - - if (prov == null) - { - throw new NoSuchProviderException("Provider " + provider + " not found"); - } - - return prov; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509V1CertificateGenerator.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509V1CertificateGenerator.java deleted file mode 100644 index 95cf7d6ad..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509V1CertificateGenerator.java +++ /dev/null @@ -1,345 +0,0 @@ -package org.spongycastle.x509; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.Date; -import java.util.Iterator; - -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.DERBitString; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x509.TBSCertificate; -import org.spongycastle.asn1.x509.Time; -import org.spongycastle.asn1.x509.V1TBSCertificateGenerator; -import org.spongycastle.asn1.x509.Certificate; -import org.spongycastle.asn1.x509.X509Name; -import org.spongycastle.jce.provider.X509CertificateObject; - -/** - * class to produce an X.509 Version 1 certificate. - * @deprecated use org.spongycastle.cert.X509v1CertificateBuilder. - */ -public class X509V1CertificateGenerator -{ - private V1TBSCertificateGenerator tbsGen; - private ASN1ObjectIdentifier sigOID; - private AlgorithmIdentifier sigAlgId; - private String signatureAlgorithm; - - public X509V1CertificateGenerator() - { - tbsGen = new V1TBSCertificateGenerator(); - } - - /** - * reset the generator - */ - public void reset() - { - tbsGen = new V1TBSCertificateGenerator(); - } - - /** - * set the serial number for the certificate. - */ - public void setSerialNumber( - BigInteger serialNumber) - { - if (serialNumber.compareTo(BigInteger.valueOf(0)) <= 0) - { - throw new IllegalArgumentException("serial number must be a positive integer"); - } - - tbsGen.setSerialNumber(new ASN1Integer(serialNumber)); - } - - /** - * Set the issuer distinguished name - the issuer is the entity whose private key is used to sign the - * certificate. - */ - public void setIssuerDN( - X509Name issuer) - { - tbsGen.setIssuer(issuer); - } - - public void setNotBefore( - Date date) - { - tbsGen.setStartDate(new Time(date)); - } - - public void setNotAfter( - Date date) - { - tbsGen.setEndDate(new Time(date)); - } - - /** - * Set the subject distinguished name. The subject describes the entity associated with the public key. - */ - public void setSubjectDN( - X509Name subject) - { - tbsGen.setSubject(subject); - } - - public void setPublicKey( - PublicKey key) - { - try - { - tbsGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo((ASN1Sequence)new ASN1InputStream( - new ByteArrayInputStream(key.getEncoded())).readObject())); - } - catch (Exception e) - { - throw new IllegalArgumentException("unable to process key - " + e.toString()); - } - } - - /** - * Set the signature algorithm. This can be either a name or an OID, names - * are treated as case insensitive. - * - * @param signatureAlgorithm string representation of the algorithm name. - */ - public void setSignatureAlgorithm( - String signatureAlgorithm) - { - this.signatureAlgorithm = signatureAlgorithm; - - try - { - sigOID = X509Util.getAlgorithmOID(signatureAlgorithm); - } - catch (Exception e) - { - throw new IllegalArgumentException("Unknown signature type requested"); - } - - sigAlgId = X509Util.getSigAlgID(sigOID, signatureAlgorithm); - - tbsGen.setSignature(sigAlgId); - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider "SC". - * @deprecated use generate(key, "SC") - */ - public X509Certificate generateX509Certificate( - PrivateKey key) - throws SecurityException, SignatureException, InvalidKeyException - { - try - { - return generateX509Certificate(key, "SC", null); - } - catch (NoSuchProviderException e) - { - throw new SecurityException("BC provider not installed!"); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider "SC" and the passed in source of randomness - * @deprecated use generate(key, random, "SC") - */ - public X509Certificate generateX509Certificate( - PrivateKey key, - SecureRandom random) - throws SecurityException, SignatureException, InvalidKeyException - { - try - { - return generateX509Certificate(key, "SC", random); - } - catch (NoSuchProviderException e) - { - throw new SecurityException("BC provider not installed!"); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing, and the passed in source - * of randomness (if required). - * @deprecated use generate() - */ - public X509Certificate generateX509Certificate( - PrivateKey key, - String provider) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - return generateX509Certificate(key, provider, null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing, and the passed in source - * of randomness (if required). - * @deprecated use generate() - */ - public X509Certificate generateX509Certificate( - PrivateKey key, - String provider, - SecureRandom random) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - try - { - return generate(key, provider, random); - } - catch (NoSuchProviderException e) - { - throw e; - } - catch (SignatureException e) - { - throw e; - } - catch (InvalidKeyException e) - { - throw e; - } - catch (NoSuchAlgorithmException e) - { - throw new SecurityException("exception: " + e); - } - catch (GeneralSecurityException e) - { - throw new SecurityException("exception: " + e); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider. - *

- * Note: this differs from the deprecated method in that the default provider is - * used - not "SC". - *

- */ - public X509Certificate generate( - PrivateKey key) - throws CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - return generate(key, (SecureRandom)null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider and the passed in source of randomness - *

- * Note: this differs from the deprecated method in that the default provider is - * used - not "SC". - *

- */ - public X509Certificate generate( - PrivateKey key, - SecureRandom random) - throws CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - TBSCertificate tbsCert = tbsGen.generateTBSCertificate(); - byte[] signature; - - try - { - signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, key, random, tbsCert); - } - catch (IOException e) - { - throw new ExtCertificateEncodingException("exception encoding TBS cert", e); - } - - return generateJcaObject(tbsCert, signature); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing, and the passed in source - * of randomness (if required). - */ - public X509Certificate generate( - PrivateKey key, - String provider) - throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - return generate(key, provider, null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing, and the passed in source - * of randomness (if required). - */ - public X509Certificate generate( - PrivateKey key, - String provider, - SecureRandom random) - throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - TBSCertificate tbsCert = tbsGen.generateTBSCertificate(); - byte[] signature; - - try - { - signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, provider, key, random, tbsCert); - } - catch (IOException e) - { - throw new ExtCertificateEncodingException("exception encoding TBS cert", e); - } - - return generateJcaObject(tbsCert, signature); - } - - private X509Certificate generateJcaObject(TBSCertificate tbsCert, byte[] signature) - throws CertificateEncodingException - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(tbsCert); - v.add(sigAlgId); - v.add(new DERBitString(signature)); - - try - { - return new X509CertificateObject(Certificate.getInstance((new DERSequence(v)))); - } - catch (CertificateParsingException e) - { - throw new ExtCertificateEncodingException("exception producing certificate object", e); - } - } - - /** - * Return an iterator of the signature names supported by the generator. - * - * @return an iterator containing recognised names. - */ - public Iterator getSignatureAlgNames() - { - return X509Util.getAlgNames(); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509V2AttributeCertificateGenerator.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509V2AttributeCertificateGenerator.java deleted file mode 100644 index 9aae6e850..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509V2AttributeCertificateGenerator.java +++ /dev/null @@ -1,281 +0,0 @@ -package org.spongycastle.x509; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.Signature; -import java.security.SignatureException; -import java.util.Date; -import java.util.Hashtable; -import java.util.Vector; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.DERBitString; -import org.spongycastle.asn1.ASN1GeneralizedTime; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.DEROutputStream; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.AttCertIssuer; -import org.spongycastle.asn1.x509.Attribute; -import org.spongycastle.asn1.x509.AttributeCertificate; -import org.spongycastle.asn1.x509.V2AttributeCertificateInfoGenerator; -import org.spongycastle.asn1.x509.AttributeCertificateInfo; -import org.spongycastle.asn1.x509.X509Extension; -import org.spongycastle.asn1.x509.X509Extensions; -import org.spongycastle.util.Strings; - -/** - * class to produce an X.509 Version 2 AttributeCertificate. - */ -public class X509V2AttributeCertificateGenerator -{ - private V2AttributeCertificateInfoGenerator acInfoGen; - private ASN1ObjectIdentifier sigOID; - private AlgorithmIdentifier sigAlgId; - private String signatureAlgorithm; - private Hashtable extensions = null; - private Vector extOrdering = null; - private static Hashtable algorithms = new Hashtable(); - - static - { - algorithms.put("MD2WITHRSAENCRYPTION", new ASN1ObjectIdentifier("1.2.840.113549.1.1.2")); - algorithms.put("MD2WITHRSA", new ASN1ObjectIdentifier("1.2.840.113549.1.1.2")); - algorithms.put("MD5WITHRSAENCRYPTION", new ASN1ObjectIdentifier("1.2.840.113549.1.1.4")); - algorithms.put("MD5WITHRSA", new ASN1ObjectIdentifier("1.2.840.113549.1.1.4")); - algorithms.put("SHA1WITHRSAENCRYPTION", new ASN1ObjectIdentifier("1.2.840.113549.1.1.5")); - algorithms.put("SHA1WITHRSA", new ASN1ObjectIdentifier("1.2.840.113549.1.1.5")); - algorithms.put("RIPEMD160WITHRSAENCRYPTION", new ASN1ObjectIdentifier("1.3.36.3.3.1.2")); - algorithms.put("RIPEMD160WITHRSA", new ASN1ObjectIdentifier("1.3.36.3.3.1.2")); - algorithms.put("SHA1WITHDSA", new ASN1ObjectIdentifier("1.2.840.10040.4.3")); - algorithms.put("DSAWITHSHA1", new ASN1ObjectIdentifier("1.2.840.10040.4.3")); - algorithms.put("SHA1WITHECDSA", new ASN1ObjectIdentifier("1.2.840.10045.4.1")); - algorithms.put("ECDSAWITHSHA1", new ASN1ObjectIdentifier("1.2.840.10045.4.1")); - } - - public X509V2AttributeCertificateGenerator() - { - acInfoGen = new V2AttributeCertificateInfoGenerator(); - } - - /** - * reset the generator - */ - public void reset() - { - acInfoGen = new V2AttributeCertificateInfoGenerator(); - extensions = null; - extOrdering = null; - } - - /** - * Set the Holder of this Attribute Certificate - */ - public void setHolder( - AttributeCertificateHolder holder) - { - acInfoGen.setHolder(holder.holder); - } - - /** - * Set the issuer - */ - public void setIssuer( - AttributeCertificateIssuer issuer) - { - acInfoGen.setIssuer(AttCertIssuer.getInstance(issuer.form)); - } - - /** - * Set the Signature inside the AttributeCertificateInfo - */ - public void setSignature( - AlgorithmIdentifier sig) - { - acInfoGen.setSignature(sig); - } - - /** - * set the serial number for the certificate. - */ - public void setSerialNumber( - BigInteger serialNumber) - { - acInfoGen.setSerialNumber(new ASN1Integer(serialNumber)); - } - - public void setNotBefore( - Date date) - { - acInfoGen.setStartDate(new ASN1GeneralizedTime(date)); - } - - public void setNotAfter( - Date date) - { - acInfoGen.setEndDate(new ASN1GeneralizedTime(date)); - } - - public void setSignatureAlgorithm( - String signatureAlgorithm) - { - this.signatureAlgorithm = signatureAlgorithm; - - sigOID = (ASN1ObjectIdentifier)algorithms.get(Strings.toUpperCase(signatureAlgorithm)); - - if (sigOID == null) - { - throw new IllegalArgumentException("Unknown signature type requested"); - } - - sigAlgId = new AlgorithmIdentifier(this.sigOID, new DERNull()); - - acInfoGen.setSignature(sigAlgId); - } - - /** - * add an attribute - */ - public void addAttribute( - X509Attribute attribute) - { - acInfoGen.addAttribute(Attribute.getInstance(attribute.toASN1Object())); - } - - public void setIssuerUniqueId( - boolean[] iui) - { - // [TODO] convert boolean array to bit string - //acInfoGen.setIssuerUniqueID(iui); - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - * @throws IOException - */ - public void addExtension( - String OID, - boolean critical, - ASN1Encodable value) - throws IOException - { - this.addExtension(OID, critical, value.toASN1Primitive().getEncoded()); - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - * The value parameter becomes the contents of the octet string associated - * with the extension. - */ - public void addExtension( - String OID, - boolean critical, - byte[] value) - { - if (extensions == null) - { - extensions = new Hashtable(); - extOrdering = new Vector(); - } - - ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(OID); - - extensions.put(oid, new X509Extension(critical, new DEROctetString(value))); - extOrdering.addElement(oid); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing. - */ - public X509AttributeCertificate generateCertificate( - PrivateKey key, - String provider) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - return generateCertificate(key, provider, null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing and the supplied source - * of randomness, if required. - */ - public X509AttributeCertificate generateCertificate( - PrivateKey key, - String provider, - SecureRandom random) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - Signature sig = null; - - if (sigOID == null) - { - throw new IllegalStateException("no signature algorithm specified"); - } - - try - { - sig = Signature.getInstance(sigOID.getId(), provider); - } - catch (NoSuchAlgorithmException ex) - { - try - { - sig = Signature.getInstance(signatureAlgorithm, provider); - } - catch (NoSuchAlgorithmException e) - { - throw new SecurityException("exception creating signature: " + e.toString()); - } - } - - sig.initSign(key); - - if (extensions != null) - { - acInfoGen.setExtensions(new X509Extensions(extOrdering, extensions)); - } - - AttributeCertificateInfo acInfo = acInfoGen.generateAttributeCertificateInfo(); - - try - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - DEROutputStream dOut = new DEROutputStream(bOut); - - dOut.writeObject(acInfo); - - sig.update(bOut.toByteArray()); - } - catch (Exception e) - { - throw new SecurityException("exception encoding Attribute cert - " + e); - } - - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(acInfo); - v.add(sigAlgId); - v.add(new DERBitString(sig.sign())); - - try - { - return new X509V2AttributeCertificate(new AttributeCertificate(new DERSequence(v))); - } - catch (IOException e) - { - throw new RuntimeException("constructed invalid certificate!"); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509V2CRLGenerator.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509V2CRLGenerator.java deleted file mode 100644 index ac9ad6ddb..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509V2CRLGenerator.java +++ /dev/null @@ -1,434 +0,0 @@ -package org.spongycastle.x509; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.security.cert.CRLException; -import java.security.cert.X509CRL; -import java.security.cert.X509CRLEntry; -import java.util.Date; -import java.util.Iterator; -import java.util.Set; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.DERBitString; -import org.spongycastle.asn1.ASN1GeneralizedTime; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.CertificateList; -import org.spongycastle.asn1.x509.TBSCertList; -import org.spongycastle.asn1.x509.Time; -import org.spongycastle.asn1.x509.V2TBSCertListGenerator; -import org.spongycastle.asn1.x509.X509Extensions; -import org.spongycastle.asn1.x509.Extensions; -import org.spongycastle.asn1.x509.X509ExtensionsGenerator; -import org.spongycastle.asn1.x509.X509Name; -import org.spongycastle.jce.provider.X509CRLObject; - -/** - * class to produce an X.509 Version 2 CRL. - * @deprecated use org.spongycastle.cert.X509v2CRLBuilder. - */ -public class X509V2CRLGenerator -{ - private V2TBSCertListGenerator tbsGen; - private ASN1ObjectIdentifier sigOID; - private AlgorithmIdentifier sigAlgId; - private String signatureAlgorithm; - private X509ExtensionsGenerator extGenerator; - - public X509V2CRLGenerator() - { - tbsGen = new V2TBSCertListGenerator(); - extGenerator = new X509ExtensionsGenerator(); - } - - /** - * reset the generator - */ - public void reset() - { - tbsGen = new V2TBSCertListGenerator(); - extGenerator.reset(); - } - - /** - * Set the issuer distinguished name - the issuer is the entity whose private key is used to sign the - * certificate. - */ - public void setIssuerDN( - X509Name issuer) - { - tbsGen.setIssuer(issuer); - } - - public void setThisUpdate( - Date date) - { - tbsGen.setThisUpdate(new Time(date)); - } - - public void setNextUpdate( - Date date) - { - tbsGen.setNextUpdate(new Time(date)); - } - - /** - * Reason being as indicated by CRLReason, i.e. CRLReason.keyCompromise - * or 0 if CRLReason is not to be used - **/ - public void addCRLEntry(BigInteger userCertificate, Date revocationDate, int reason) - { - tbsGen.addCRLEntry(new ASN1Integer(userCertificate), new Time(revocationDate), reason); - } - - /** - * Add a CRL entry with an Invalidity Date extension as well as a CRLReason extension. - * Reason being as indicated by CRLReason, i.e. CRLReason.keyCompromise - * or 0 if CRLReason is not to be used - **/ - public void addCRLEntry(BigInteger userCertificate, Date revocationDate, int reason, Date invalidityDate) - { - tbsGen.addCRLEntry(new ASN1Integer(userCertificate), new Time(revocationDate), reason, new ASN1GeneralizedTime(invalidityDate)); - } - - /** - * Add a CRL entry with extensions. - **/ - public void addCRLEntry(BigInteger userCertificate, Date revocationDate, X509Extensions extensions) - { - tbsGen.addCRLEntry(new ASN1Integer(userCertificate), new Time(revocationDate), Extensions.getInstance(extensions)); - } - - /** - * Add the CRLEntry objects contained in a previous CRL. - * - * @param other the X509CRL to source the other entries from. - */ - public void addCRL(X509CRL other) - throws CRLException - { - Set revocations = other.getRevokedCertificates(); - - if (revocations != null) - { - Iterator it = revocations.iterator(); - while (it.hasNext()) - { - X509CRLEntry entry = (X509CRLEntry)it.next(); - - ASN1InputStream aIn = new ASN1InputStream(entry.getEncoded()); - - try - { - tbsGen.addCRLEntry(ASN1Sequence.getInstance(aIn.readObject())); - } - catch (IOException e) - { - throw new CRLException("exception processing encoding of CRL: " + e.toString()); - } - } - } - } - - /** - * Set the signature algorithm. This can be either a name or an OID, names - * are treated as case insensitive. - * - * @param signatureAlgorithm string representation of the algorithm name. - */ - public void setSignatureAlgorithm( - String signatureAlgorithm) - { - this.signatureAlgorithm = signatureAlgorithm; - - try - { - sigOID = X509Util.getAlgorithmOID(signatureAlgorithm); - } - catch (Exception e) - { - throw new IllegalArgumentException("Unknown signature type requested"); - } - - sigAlgId = X509Util.getSigAlgID(sigOID, signatureAlgorithm); - - tbsGen.setSignature(sigAlgId); - } - - /** - * add a given extension field for the standard extensions tag (tag 0) - */ - public void addExtension( - String oid, - boolean critical, - ASN1Encodable value) - { - this.addExtension(new ASN1ObjectIdentifier(oid), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 0) - */ - public void addExtension( - ASN1ObjectIdentifier oid, - boolean critical, - ASN1Encodable value) - { - extGenerator.addExtension(new ASN1ObjectIdentifier(oid.getId()), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 0) - */ - public void addExtension( - String oid, - boolean critical, - byte[] value) - { - this.addExtension(new ASN1ObjectIdentifier(oid), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 0) - */ - public void addExtension( - ASN1ObjectIdentifier oid, - boolean critical, - byte[] value) - { - extGenerator.addExtension(new ASN1ObjectIdentifier(oid.getId()), critical, value); - } - - /** - * generate an X509 CRL, based on the current issuer and subject - * using the default provider "SC". - * @deprecated use generate(key, "SC") - */ - public X509CRL generateX509CRL( - PrivateKey key) - throws SecurityException, SignatureException, InvalidKeyException - { - try - { - return generateX509CRL(key, "SC", null); - } - catch (NoSuchProviderException e) - { - throw new SecurityException("BC provider not installed!"); - } - } - - /** - * generate an X509 CRL, based on the current issuer and subject - * using the default provider "SC" and an user defined SecureRandom object as - * source of randomness. - * @deprecated use generate(key, random, "SC") - */ - public X509CRL generateX509CRL( - PrivateKey key, - SecureRandom random) - throws SecurityException, SignatureException, InvalidKeyException - { - try - { - return generateX509CRL(key, "SC", random); - } - catch (NoSuchProviderException e) - { - throw new SecurityException("BC provider not installed!"); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the passed in provider for the signing. - * @deprecated use generate() - */ - public X509CRL generateX509CRL( - PrivateKey key, - String provider) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - return generateX509CRL(key, provider, null); - } - - /** - * generate an X509 CRL, based on the current issuer and subject, - * using the passed in provider for the signing. - * @deprecated use generate() - */ - public X509CRL generateX509CRL( - PrivateKey key, - String provider, - SecureRandom random) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - try - { - return generate(key, provider, random); - } - catch (NoSuchProviderException e) - { - throw e; - } - catch (SignatureException e) - { - throw e; - } - catch (InvalidKeyException e) - { - throw e; - } - catch (NoSuchAlgorithmException e) - { - throw new SecurityException("exception: " + e); - } - catch (GeneralSecurityException e) - { - throw new SecurityException("exception: " + e); - } - } - - /** - * generate an X509 CRL, based on the current issuer and subject - * using the default provider. - *

- * Note: this differs from the deprecated method in that the default provider is - * used - not "SC". - *

- */ - public X509CRL generate( - PrivateKey key) - throws CRLException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - return generate(key, (SecureRandom)null); - } - - /** - * generate an X509 CRL, based on the current issuer and subject - * using the default provider and an user defined SecureRandom object as - * source of randomness. - *

- * Note: this differs from the deprecated method in that the default provider is - * used - not "SC". - *

- */ - public X509CRL generate( - PrivateKey key, - SecureRandom random) - throws CRLException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - TBSCertList tbsCrl = generateCertList(); - byte[] signature; - - try - { - signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, key, random, tbsCrl); - } - catch (IOException e) - { - throw new ExtCRLException("cannot generate CRL encoding", e); - } - - return generateJcaObject(tbsCrl, signature); - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the passed in provider for the signing. - */ - public X509CRL generate( - PrivateKey key, - String provider) - throws CRLException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - return generate(key, provider, null); - } - - /** - * generate an X509 CRL, based on the current issuer and subject, - * using the passed in provider for the signing. - */ - public X509CRL generate( - PrivateKey key, - String provider, - SecureRandom random) - throws CRLException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - TBSCertList tbsCrl = generateCertList(); - byte[] signature; - - try - { - signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, provider, key, random, tbsCrl); - } - catch (IOException e) - { - throw new ExtCRLException("cannot generate CRL encoding", e); - } - - return generateJcaObject(tbsCrl, signature); - } - - private TBSCertList generateCertList() - { - if (!extGenerator.isEmpty()) - { - tbsGen.setExtensions(extGenerator.generate()); - } - - return tbsGen.generateTBSCertList(); - } - - private X509CRL generateJcaObject(TBSCertList tbsCrl, byte[] signature) - throws CRLException - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(tbsCrl); - v.add(sigAlgId); - v.add(new DERBitString(signature)); - - return new X509CRLObject(new CertificateList(new DERSequence(v))); - } - - /** - * Return an iterator of the signature names supported by the generator. - * - * @return an iterator containing recognised names. - */ - public Iterator getSignatureAlgNames() - { - return X509Util.getAlgNames(); - } - - private static class ExtCRLException - extends CRLException - { - Throwable cause; - - ExtCRLException(String message, Throwable cause) - { - super(message); - this.cause = cause; - } - - public Throwable getCause() - { - return cause; - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509V3CertificateGenerator.java b/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509V3CertificateGenerator.java deleted file mode 100644 index 1a0dc95be..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.1/org/spongycastle/x509/X509V3CertificateGenerator.java +++ /dev/null @@ -1,495 +0,0 @@ -package org.spongycastle.x509; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.Date; -import java.util.Iterator; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DERBitString; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x509.TBSCertificate; -import org.spongycastle.asn1.x509.Time; -import org.spongycastle.asn1.x509.V3TBSCertificateGenerator; -import org.spongycastle.asn1.x509.Certificate; -import org.spongycastle.asn1.x509.X509ExtensionsGenerator; -import org.spongycastle.asn1.x509.X509Name; -import org.spongycastle.jce.provider.X509CertificateObject; -import org.spongycastle.x509.extension.X509ExtensionUtil; - -/** - * class to produce an X.509 Version 3 certificate. - * @deprecated use org.spongycastle.cert.X509v3CertificateBuilder. - */ -public class X509V3CertificateGenerator -{ - private V3TBSCertificateGenerator tbsGen; - private ASN1ObjectIdentifier sigOID; - private AlgorithmIdentifier sigAlgId; - private String signatureAlgorithm; - private X509ExtensionsGenerator extGenerator; - - public X509V3CertificateGenerator() - { - tbsGen = new V3TBSCertificateGenerator(); - extGenerator = new X509ExtensionsGenerator(); - } - - /** - * reset the generator - */ - public void reset() - { - tbsGen = new V3TBSCertificateGenerator(); - extGenerator.reset(); - } - - /** - * set the serial number for the certificate. - */ - public void setSerialNumber( - BigInteger serialNumber) - { - if (serialNumber.compareTo(BigInteger.valueOf(0)) <= 0) - { - throw new IllegalArgumentException("serial number must be a positive integer"); - } - - tbsGen.setSerialNumber(new ASN1Integer(serialNumber)); - } - - /** - * Set the issuer distinguished name - the issuer is the entity whose private key is used to sign the - * certificate. - */ - public void setIssuerDN( - X509Name issuer) - { - tbsGen.setIssuer(issuer); - } - - public void setNotBefore( - Date date) - { - tbsGen.setStartDate(new Time(date)); - } - - public void setNotAfter( - Date date) - { - tbsGen.setEndDate(new Time(date)); - } - - /** - * Set the subject distinguished name. The subject describes the entity associated with the public key. - */ - public void setSubjectDN( - X509Name subject) - { - tbsGen.setSubject(subject); - } - - public void setPublicKey( - PublicKey key) - throws IllegalArgumentException - { - try - { - tbsGen.setSubjectPublicKeyInfo( - SubjectPublicKeyInfo.getInstance(new ASN1InputStream(key.getEncoded()).readObject())); - } - catch (Exception e) - { - throw new IllegalArgumentException("unable to process key - " + e.toString()); - } - } - - /** - * Set the signature algorithm. This can be either a name or an OID, names - * are treated as case insensitive. - * - * @param signatureAlgorithm string representation of the algorithm name. - */ - public void setSignatureAlgorithm( - String signatureAlgorithm) - { - this.signatureAlgorithm = signatureAlgorithm; - - try - { - sigOID = X509Util.getAlgorithmOID(signatureAlgorithm); - } - catch (Exception e) - { - throw new IllegalArgumentException("Unknown signature type requested: " + signatureAlgorithm); - } - - sigAlgId = X509Util.getSigAlgID(sigOID, signatureAlgorithm); - - tbsGen.setSignature(sigAlgId); - } - - /** - * Set the subject unique ID - note: it is very rare that it is correct to do this. - */ - public void setSubjectUniqueID(boolean[] uniqueID) - { - tbsGen.setSubjectUniqueID(booleanToBitString(uniqueID)); - } - - /** - * Set the issuer unique ID - note: it is very rare that it is correct to do this. - */ - public void setIssuerUniqueID(boolean[] uniqueID) - { - tbsGen.setIssuerUniqueID(booleanToBitString(uniqueID)); - } - - private DERBitString booleanToBitString(boolean[] id) - { - byte[] bytes = new byte[(id.length + 7) / 8]; - - for (int i = 0; i != id.length; i++) - { - bytes[i / 8] |= (id[i]) ? (1 << ((7 - (i % 8)))) : 0; - } - - int pad = id.length % 8; - - if (pad == 0) - { - return new DERBitString(bytes); - } - else - { - return new DERBitString(bytes, 8 - pad); - } - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - */ - public void addExtension( - String oid, - boolean critical, - ASN1Encodable value) - { - this.addExtension(new ASN1ObjectIdentifier(oid), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - */ - public void addExtension( - ASN1ObjectIdentifier oid, - boolean critical, - ASN1Encodable value) - { - extGenerator.addExtension(new ASN1ObjectIdentifier(oid.getId()), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - * The value parameter becomes the contents of the octet string associated - * with the extension. - */ - public void addExtension( - String oid, - boolean critical, - byte[] value) - { - this.addExtension(new ASN1ObjectIdentifier(oid), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - */ - public void addExtension( - ASN1ObjectIdentifier oid, - boolean critical, - byte[] value) - { - extGenerator.addExtension(new ASN1ObjectIdentifier(oid.getId()), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - * copying the extension value from another certificate. - * @throws CertificateParsingException if the extension cannot be extracted. - */ - public void copyAndAddExtension( - String oid, - boolean critical, - X509Certificate cert) - throws CertificateParsingException - { - byte[] extValue = cert.getExtensionValue(oid); - - if (extValue == null) - { - throw new CertificateParsingException("extension " + oid + " not present"); - } - - try - { - ASN1Encodable value = X509ExtensionUtil.fromExtensionValue(extValue); - - this.addExtension(oid, critical, value); - } - catch (IOException e) - { - throw new CertificateParsingException(e.toString()); - } - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - * copying the extension value from another certificate. - * @throws CertificateParsingException if the extension cannot be extracted. - */ - public void copyAndAddExtension( - ASN1ObjectIdentifier oid, - boolean critical, - X509Certificate cert) - throws CertificateParsingException - { - this.copyAndAddExtension(oid.getId(), critical, cert); - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider "SC". - * @deprecated use generate(key, "SC") - */ - public X509Certificate generateX509Certificate( - PrivateKey key) - throws SecurityException, SignatureException, InvalidKeyException - { - try - { - return generateX509Certificate(key, "SC", null); - } - catch (NoSuchProviderException e) - { - throw new SecurityException("BC provider not installed!"); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider "SC", and the passed in source of randomness - * (if required). - * @deprecated use generate(key, random, "SC") - */ - public X509Certificate generateX509Certificate( - PrivateKey key, - SecureRandom random) - throws SecurityException, SignatureException, InvalidKeyException - { - try - { - return generateX509Certificate(key, "SC", random); - } - catch (NoSuchProviderException e) - { - throw new SecurityException("BC provider not installed!"); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing. - * @deprecated use generate() - */ - public X509Certificate generateX509Certificate( - PrivateKey key, - String provider) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - return generateX509Certificate(key, provider, null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing and the supplied source - * of randomness, if required. - * @deprecated use generate() - */ - public X509Certificate generateX509Certificate( - PrivateKey key, - String provider, - SecureRandom random) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - try - { - return generate(key, provider, random); - } - catch (NoSuchProviderException e) - { - throw e; - } - catch (SignatureException e) - { - throw e; - } - catch (InvalidKeyException e) - { - throw e; - } - catch (NoSuchAlgorithmException e) - { - throw new SecurityException("exception: " + e); - } - catch (GeneralSecurityException e) - { - throw new SecurityException("exception: " + e); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider. - *

- * Note: this differs from the deprecated method in that the default provider is - * used - not "SC". - *

- */ - public X509Certificate generate( - PrivateKey key) - throws CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - return generate(key, (SecureRandom)null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider, and the passed in source of randomness - * (if required). - *

- * Note: this differs from the deprecated method in that the default provider is - * used - not "SC". - *

- */ - public X509Certificate generate( - PrivateKey key, - SecureRandom random) - throws CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - TBSCertificate tbsCert = generateTbsCert(); - byte[] signature; - - try - { - signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, key, random, tbsCert); - } - catch (IOException e) - { - throw new ExtCertificateEncodingException("exception encoding TBS cert", e); - } - - try - { - return generateJcaObject(tbsCert, signature); - } - catch (CertificateParsingException e) - { - throw new ExtCertificateEncodingException("exception producing certificate object", e); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing. - */ - public X509Certificate generate( - PrivateKey key, - String provider) - throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - return generate(key, provider, null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing and the supplied source - * of randomness, if required. - */ - public X509Certificate generate( - PrivateKey key, - String provider, - SecureRandom random) - throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - TBSCertificate tbsCert = generateTbsCert(); - byte[] signature; - - try - { - signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, provider, key, random, tbsCert); - } - catch (IOException e) - { - throw new ExtCertificateEncodingException("exception encoding TBS cert", e); - } - - try - { - return generateJcaObject(tbsCert, signature); - } - catch (CertificateParsingException e) - { - throw new ExtCertificateEncodingException("exception producing certificate object", e); - } - } - - private TBSCertificate generateTbsCert() - { - if (!extGenerator.isEmpty()) - { - tbsGen.setExtensions(extGenerator.generate()); - } - - return tbsGen.generateTBSCertificate(); - } - - private X509Certificate generateJcaObject(TBSCertificate tbsCert, byte[] signature) - throws CertificateParsingException - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(tbsCert); - v.add(sigAlgId); - v.add(new DERBitString(signature)); - - return new X509CertificateObject(Certificate.getInstance(new DERSequence(v))); - } - - /** - * Return an iterator of the signature names supported by the generator. - * - * @return an iterator containing recognised names. - */ - public Iterator getSignatureAlgNames() - { - return X509Util.getAlgNames(); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.2/org/spongycastle/jce/exception/ExtCertPathBuilderException.java b/extern/spongycastle/prov/src/main/jdk1.2/org/spongycastle/jce/exception/ExtCertPathBuilderException.java deleted file mode 100644 index b238580f7..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.2/org/spongycastle/jce/exception/ExtCertPathBuilderException.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.spongycastle.jce.exception; - -import org.spongycastle.jce.cert.CertPath; -import org.spongycastle.jce.cert.CertPathBuilderException; - -public class ExtCertPathBuilderException - extends CertPathBuilderException - implements ExtException -{ - private Throwable cause; - - public ExtCertPathBuilderException(String message, Throwable cause) - { - super(message); - this.cause = cause; - } - - public ExtCertPathBuilderException(String msg, Throwable cause, - CertPath certPath, int index) - { - super(msg, cause); - this.cause = cause; - } - - public Throwable getCause() - { - return cause; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.2/org/spongycastle/jce/exception/ExtCertPathValidatorException.java b/extern/spongycastle/prov/src/main/jdk1.2/org/spongycastle/jce/exception/ExtCertPathValidatorException.java deleted file mode 100644 index bd6e42d09..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.2/org/spongycastle/jce/exception/ExtCertPathValidatorException.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.spongycastle.jce.exception; - -import org.spongycastle.jce.cert.CertPath; -import org.spongycastle.jce.cert.CertPathValidatorException; - -public class ExtCertPathValidatorException - extends CertPathValidatorException - implements ExtException -{ - private Throwable cause; - - public ExtCertPathValidatorException(String message, Throwable cause) - { - super(message); - this.cause = cause; - } - - public ExtCertPathValidatorException(String msg, Throwable cause, - CertPath certPath, int index) - { - super(msg, cause, certPath, index); - this.cause = cause; - } - - public Throwable getCause() - { - return cause; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/rsa/AlgorithmParametersSpi.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/rsa/AlgorithmParametersSpi.java deleted file mode 100644 index 390708bc6..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/rsa/AlgorithmParametersSpi.java +++ /dev/null @@ -1,201 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.rsa; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.security.spec.AlgorithmParameterSpec; -import java.security.spec.InvalidParameterSpecException; - -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.DEROutputStream; -import org.spongycastle.asn1.pkcs.RSAESOAEPparams; -import org.spongycastle.asn1.pkcs.RSASSAPSSparams; - -public abstract class AlgorithmParametersSpi - extends java.security.AlgorithmParametersSpi -{ - protected boolean isASN1FormatString(String format) - { - return format == null || format.equals("ASN.1"); - } - - protected AlgorithmParameterSpec engineGetParameterSpec( - Class paramSpec) - throws InvalidParameterSpecException - { - if (paramSpec == null) - { - throw new NullPointerException("argument to getParameterSpec must not be null"); - } - - return localEngineGetParameterSpec(paramSpec); - } - - protected abstract AlgorithmParameterSpec localEngineGetParameterSpec(Class paramSpec) - throws InvalidParameterSpecException; - - public static class OAEP - extends AlgorithmParametersSpi - { - AlgorithmParameterSpec currentSpec; - - /** - * Return the PKCS#1 ASN.1 structure RSAES-OAEP-params. - */ - protected byte[] engineGetEncoded() - { - return null; - } - - protected byte[] engineGetEncoded( - String format) - { - if (this.isASN1FormatString(format) || format.equalsIgnoreCase("X.509")) - { - return engineGetEncoded(); - } - - return null; - } - - protected AlgorithmParameterSpec localEngineGetParameterSpec( - Class paramSpec) - throws InvalidParameterSpecException - { - throw new InvalidParameterSpecException("unknown parameter spec passed to OAEP parameters object."); - } - - protected void engineInit( - AlgorithmParameterSpec paramSpec) - throws InvalidParameterSpecException - { - this.currentSpec = paramSpec; - } - - protected void engineInit( - byte[] params) - throws IOException - { - try - { - RSAESOAEPparams oaepP = RSAESOAEPparams.getInstance(params); - - throw new IOException("Operation not supported"); - } - catch (ClassCastException e) - { - throw new IOException("Not a valid OAEP Parameter encoding."); - } - catch (ArrayIndexOutOfBoundsException e) - { - throw new IOException("Not a valid OAEP Parameter encoding."); - } - } - - protected void engineInit( - byte[] params, - String format) - throws IOException - { - if (format.equalsIgnoreCase("X.509") - || format.equalsIgnoreCase("ASN.1")) - { - engineInit(params); - } - else - { - throw new IOException("Unknown parameter format " + format); - } - } - - protected String engineToString() - { - return "OAEP Parameters"; - } - } - - public static class PSS - extends AlgorithmParametersSpi - { - /** - * Return the PKCS#1 ASN.1 structure RSASSA-PSS-params. - */ - protected byte[] engineGetEncoded() - throws IOException - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - DEROutputStream dOut = new DEROutputStream(bOut); - RSASSAPSSparams pssP = new RSASSAPSSparams(RSASSAPSSparams.DEFAULT_HASH_ALGORITHM, RSASSAPSSparams.DEFAULT_MASK_GEN_FUNCTION, new ASN1Integer(20), RSASSAPSSparams.DEFAULT_TRAILER_FIELD); - - dOut.writeObject(pssP); - dOut.close(); - - return bOut.toByteArray(); - } - - protected byte[] engineGetEncoded( - String format) - throws IOException - { - if (format.equalsIgnoreCase("X.509") - || format.equalsIgnoreCase("ASN.1")) - { - return engineGetEncoded(); - } - - return null; - } - - protected AlgorithmParameterSpec localEngineGetParameterSpec( - Class paramSpec) - throws InvalidParameterSpecException - { - throw new InvalidParameterSpecException("unknown parameter spec passed to PSS parameters object."); - } - - protected void engineInit( - AlgorithmParameterSpec paramSpec) - throws InvalidParameterSpecException - { - throw new InvalidParameterSpecException("Not implemented"); - } - - protected void engineInit( - byte[] params) - throws IOException - { - try - { - RSASSAPSSparams pssP = RSASSAPSSparams.getInstance(params); - - } - catch (ClassCastException e) - { - throw new IOException("Not a valid PSS Parameter encoding."); - } - catch (ArrayIndexOutOfBoundsException e) - { - throw new IOException("Not a valid PSS Parameter encoding."); - } - } - - protected void engineInit( - byte[] params, - String format) - throws IOException - { - if (this.isASN1FormatString(format) || format.equalsIgnoreCase("X.509")) - { - engineInit(params); - } - else - { - throw new IOException("Unknown parameter format " + format); - } - } - - protected String engineToString() - { - return "PSS Parameters"; - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/rsa/PSSSignatureSpi.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/rsa/PSSSignatureSpi.java deleted file mode 100644 index be4083e3c..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/rsa/PSSSignatureSpi.java +++ /dev/null @@ -1,428 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.rsa; - -import java.io.ByteArrayOutputStream; -import java.security.AlgorithmParameters; -import java.security.InvalidKeyException; -import java.security.InvalidParameterException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.Signature; -import java.security.SignatureException; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.AlgorithmParameterSpec; - -import org.spongycastle.crypto.AsymmetricBlockCipher; -import org.spongycastle.crypto.CipherParameters; -import org.spongycastle.crypto.CryptoException; -import org.spongycastle.crypto.Digest; -import org.spongycastle.crypto.digests.SHA1Digest; -import org.spongycastle.crypto.digests.SHA224Digest; -import org.spongycastle.crypto.digests.SHA256Digest; -import org.spongycastle.crypto.digests.SHA384Digest; -import org.spongycastle.crypto.digests.SHA512Digest; -import org.spongycastle.crypto.engines.RSABlindedEngine; -import org.spongycastle.crypto.params.ParametersWithRandom; - -public class PSSSignatureSpi - extends Signature -{ - private AlgorithmParameters engineParams; - private AsymmetricBlockCipher signer; - private Digest contentDigest; - private Digest mgfDigest; - private int saltLength; - private byte trailer; - private boolean isRaw; - private ByteArrayOutputStream bOut; - private org.spongycastle.crypto.signers.PSSSigner pss; - private CipherParameters sigParams; - - private byte getTrailer( - int trailerField) - { - if (trailerField == 1) - { - return org.spongycastle.crypto.signers.PSSSigner.TRAILER_IMPLICIT; - } - - throw new IllegalArgumentException("unknown trailer field"); - } - - private void setupContentDigest() - { - if (isRaw) - { - this.contentDigest = new NullPssDigest(mgfDigest); - } - else - { - this.contentDigest = mgfDigest; - } - } - - protected PSSSignatureSpi( - String name, - AsymmetricBlockCipher signer, - Digest digest) - { - super(name); - - this.signer = signer; - this.mgfDigest = digest; - - if (digest != null) - { - this.saltLength = digest.getDigestSize(); - } - else - { - this.saltLength = 20; - } - - this.isRaw = false; - - setupContentDigest(); - } - - // care - this constructor is actually used by outside organisations - protected PSSSignatureSpi( - String name, - AsymmetricBlockCipher signer, - Digest digest, - boolean isRaw) - { - super(name); - - this.signer = signer; - this.mgfDigest = digest; - - if (digest != null) - { - this.saltLength = digest.getDigestSize(); - } - else - { - this.saltLength = 20; - } - - this.isRaw = isRaw; - - setupContentDigest(); - } - - protected void engineInitVerify( - PublicKey publicKey) - throws InvalidKeyException - { - if (!(publicKey instanceof RSAPublicKey)) - { - throw new InvalidKeyException("Supplied key is not a RSAPublicKey instance"); - } - - sigParams = RSAUtil.generatePublicKeyParameter((RSAPublicKey)publicKey); - - if (isRaw) - { - bOut = new ByteArrayOutputStream(); - } - else - { - pss = new org.spongycastle.crypto.signers.PSSSigner(signer, contentDigest, mgfDigest, saltLength); - pss.init(false, - sigParams); - } - } - - protected void engineInitSign( - PrivateKey privateKey, - SecureRandom random) - throws InvalidKeyException - { - if (!(privateKey instanceof RSAPrivateKey)) - { - throw new InvalidKeyException("Supplied key is not a RSAPrivateKey instance"); - } - - sigParams = new ParametersWithRandom(RSAUtil.generatePrivateKeyParameter((RSAPrivateKey)privateKey), random); - - if (isRaw) - { - bOut = new ByteArrayOutputStream(); - } - else - { - pss = new org.spongycastle.crypto.signers.PSSSigner(signer, contentDigest, mgfDigest, saltLength); - pss.init(true, sigParams); - } - } - - protected void engineInitSign( - PrivateKey privateKey) - throws InvalidKeyException - { - if (!(privateKey instanceof RSAPrivateKey)) - { - throw new InvalidKeyException("Supplied key is not a RSAPrivateKey instance"); - } - - sigParams = RSAUtil.generatePrivateKeyParameter((RSAPrivateKey)privateKey); - - if (isRaw) - { - bOut = new ByteArrayOutputStream(); - } - else - { - pss = new org.spongycastle.crypto.signers.PSSSigner(signer, contentDigest, mgfDigest, saltLength); - pss.init(true, sigParams); - } - } - - protected void engineUpdate( - byte b) - throws SignatureException - { - if (isRaw) - { - bOut.write(b); - } - else - { - pss.update(b); - } - } - - protected void engineUpdate( - byte[] b, - int off, - int len) - throws SignatureException - { - if (isRaw) - { - bOut.write(b, off, len); - } - else - { - pss.update(b, off, len); - } - } - - protected byte[] engineSign() - throws SignatureException - { - try - { - if (isRaw) - { - byte[] hash = bOut.toByteArray(); - contentDigest = mgfDigest = guessDigest(hash.length); - saltLength = contentDigest.getDigestSize(); - pss = new org.spongycastle.crypto.signers.PSSSigner(signer, new NullPssDigest(contentDigest), mgfDigest, saltLength); - - pss.init(true, sigParams); - } - return pss.generateSignature(); - } - catch (CryptoException e) - { - throw new SignatureException(e.getMessage()); - } - } - - protected boolean engineVerify( - byte[] sigBytes) - throws SignatureException - { - if (isRaw) - { - byte[] hash = bOut.toByteArray(); - contentDigest = mgfDigest = guessDigest(hash.length); - saltLength = contentDigest.getDigestSize(); - pss = new org.spongycastle.crypto.signers.PSSSigner(signer, new NullPssDigest(contentDigest), mgfDigest, saltLength); - - pss.init(false, sigParams); - - pss.update(hash, 0, hash.length); - } - return pss.verifySignature(sigBytes); - } - - protected void engineSetParameter( - AlgorithmParameterSpec params) - throws InvalidParameterException - { - throw new InvalidParameterException("Only PSSParameterSpec supported"); - } - - protected AlgorithmParameters engineGetParameters() - { - return engineParams; - } - - /** - * @deprecated replaced with
- */ - protected void engineSetParameter( - String param, - Object value) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - protected Object engineGetParameter( - String param) - { - throw new UnsupportedOperationException("engineGetParameter unsupported"); - } - - private Digest guessDigest(int size) - { - switch (size) - { - case 20: - return new SHA1Digest(); - case 28: - return new SHA224Digest(); - case 32: - return new SHA256Digest(); - case 48: - return new SHA384Digest(); - case 64: - return new SHA512Digest(); - } - - return null; - } - - static public class nonePSS - extends PSSSignatureSpi - { - public nonePSS() - { - super("NONEwithRSAandMGF1", new RSABlindedEngine(), null, true); - } - } - - static public class PSSwithRSA - extends PSSSignatureSpi - { - public PSSwithRSA() - { - super("SHA1withRSAandMGF1", new RSABlindedEngine(), null); - } - } - - static public class SHA1withRSA - extends PSSSignatureSpi - { - public SHA1withRSA() - { - super("SHA1withRSAandMGF1", new RSABlindedEngine(), new SHA1Digest()); - } - } - - static public class SHA224withRSA - extends PSSSignatureSpi - { - public SHA224withRSA() - { - super("SHA224withRSAandMGF1", new RSABlindedEngine(), new SHA224Digest()); - } - } - - static public class SHA256withRSA - extends PSSSignatureSpi - { - public SHA256withRSA() - { - super("SHA256withRSAandMGF1", new RSABlindedEngine(), new SHA256Digest()); - } - } - - static public class SHA384withRSA - extends PSSSignatureSpi - { - public SHA384withRSA() - { - super("SHA384withRSAandMGF1", new RSABlindedEngine(), new SHA384Digest()); - } - } - - static public class SHA512withRSA - extends PSSSignatureSpi - { - public SHA512withRSA() - { - super("SHA512withRSAandMGF1", new RSABlindedEngine(), new SHA512Digest()); - } - } - - private class NullPssDigest - implements Digest - { - private ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - private Digest baseDigest; - private boolean oddTime = true; - - public NullPssDigest(Digest mgfDigest) - { - this.baseDigest = mgfDigest; - } - - public String getAlgorithmName() - { - return "NULL"; - } - - public int getDigestSize() - { - return baseDigest.getDigestSize(); - } - - public void update(byte in) - { - bOut.write(in); - } - - public void update(byte[] in, int inOff, int len) - { - bOut.write(in, inOff, len); - } - - public int doFinal(byte[] out, int outOff) - { - byte[] res = bOut.toByteArray(); - - if (oddTime) - { - System.arraycopy(res, 0, out, outOff, res.length); - } - else - { - baseDigest.update(res, 0, res.length); - - baseDigest.doFinal(out, outOff); - } - - reset(); - - oddTime = !oddTime; - - return res.length; - } - - public void reset() - { - bOut.reset(); - baseDigest.reset(); - } - - public int getByteLength() - { - return 0; - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/CertificateFactory.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/CertificateFactory.java deleted file mode 100644 index 467893f37..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/CertificateFactory.java +++ /dev/null @@ -1,397 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.x509; - -import java.io.IOException; -import java.io.InputStream; -import java.io.PushbackInputStream; -import java.security.cert.CRL; -import java.security.cert.CRLException; -import org.spongycastle.jce.cert.CertPath; -import java.security.cert.CertificateException; -import org.spongycastle.jce.cert.CertificateFactorySpi; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1Set; -import org.spongycastle.asn1.ASN1TaggedObject; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.pkcs.SignedData; -import org.spongycastle.asn1.x509.Certificate; -import org.spongycastle.asn1.x509.CertificateList; -import org.spongycastle.jce.provider.X509CRLObject; -import org.spongycastle.jce.provider.X509CertificateObject; - -/** - * class for dealing with X509 certificates. - *

- * At the moment this will deal with "-----BEGIN CERTIFICATE-----" to "-----END CERTIFICATE-----" - * base 64 encoded certs, as well as the BER binaries of certificates and some classes of PKCS#7 - * objects. - */ -public class CertificateFactory - extends CertificateFactorySpi -{ - private static final PEMUtil PEM_CERT_PARSER = new PEMUtil("CERTIFICATE"); - private static final PEMUtil PEM_CRL_PARSER = new PEMUtil("CRL"); - - private ASN1Set sData = null; - private int sDataObjectCount = 0; - private InputStream currentStream = null; - - private ASN1Set sCrlData = null; - private int sCrlDataObjectCount = 0; - private InputStream currentCrlStream = null; - - private java.security.cert.Certificate readDERCertificate( - ASN1InputStream dIn) - throws IOException, CertificateParsingException - { - ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); - - if (seq.size() > 1 - && seq.getObjectAt(0) instanceof ASN1ObjectIdentifier) - { - if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) - { - sData = SignedData.getInstance(ASN1Sequence.getInstance( - (ASN1TaggedObject)seq.getObjectAt(1), true)).getCertificates(); - - return getCertificate(); - } - } - - return new X509CertificateObject( - Certificate.getInstance(seq)); - } - - private java.security.cert.Certificate getCertificate() - throws CertificateParsingException - { - if (sData != null) - { - while (sDataObjectCount < sData.size()) - { - Object obj = sData.getObjectAt(sDataObjectCount++); - - if (obj instanceof ASN1Sequence) - { - return new X509CertificateObject( - Certificate.getInstance(obj)); - } - } - } - - return null; - } - - private java.security.cert.Certificate readPEMCertificate( - InputStream in) - throws IOException, CertificateParsingException - { - ASN1Sequence seq = PEM_CERT_PARSER.readPEMObject(in); - - if (seq != null) - { - return new X509CertificateObject( - Certificate.getInstance(seq)); - } - - return null; - } - - protected CRL createCRL(CertificateList c) - throws CRLException - { - return new X509CRLObject(c); - } - - private CRL readPEMCRL( - InputStream in) - throws IOException, CRLException - { - ASN1Sequence seq = PEM_CRL_PARSER.readPEMObject(in); - - if (seq != null) - { - return createCRL( - CertificateList.getInstance(seq)); - } - - return null; - } - - private CRL readDERCRL( - ASN1InputStream aIn) - throws IOException, CRLException - { - ASN1Sequence seq = (ASN1Sequence)aIn.readObject(); - - if (seq.size() > 1 - && seq.getObjectAt(0) instanceof ASN1ObjectIdentifier) - { - if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) - { - sCrlData = SignedData.getInstance(ASN1Sequence.getInstance( - (ASN1TaggedObject)seq.getObjectAt(1), true)).getCRLs(); - - return getCRL(); - } - } - - return createCRL( - CertificateList.getInstance(seq)); - } - - private CRL getCRL() - throws CRLException - { - if (sCrlData == null || sCrlDataObjectCount >= sCrlData.size()) - { - return null; - } - - return createCRL( - CertificateList.getInstance( - sCrlData.getObjectAt(sCrlDataObjectCount++))); - } - - /** - * Generates a certificate object and initializes it with the data - * read from the input stream inStream. - */ - public java.security.cert.Certificate engineGenerateCertificate( - InputStream in) - throws CertificateException - { - if (currentStream == null) - { - currentStream = in; - sData = null; - sDataObjectCount = 0; - } - else if (currentStream != in) // reset if input stream has changed - { - currentStream = in; - sData = null; - sDataObjectCount = 0; - } - - try - { - if (sData != null) - { - if (sDataObjectCount != sData.size()) - { - return getCertificate(); - } - else - { - sData = null; - sDataObjectCount = 0; - return null; - } - } - - PushbackInputStream pis = new PushbackInputStream(in); - int tag = pis.read(); - - if (tag == -1) - { - return null; - } - - pis.unread(tag); - - if (tag != 0x30) // assume ascii PEM encoded. - { - return readPEMCertificate(pis); - } - else - { - return readDERCertificate(new ASN1InputStream(pis)); - } - } - catch (Exception e) - { - throw new ExCertificateException(e); - } - } - - /** - * Returns a (possibly empty) collection view of the certificates - * read from the given input stream inStream. - */ - public Collection engineGenerateCertificates( - InputStream inStream) - throws CertificateException - { - java.security.cert.Certificate cert; - List certs = new ArrayList(); - - while ((cert = engineGenerateCertificate(inStream)) != null) - { - certs.add(cert); - } - - return certs; - } - - /** - * Generates a certificate revocation list (CRL) object and initializes - * it with the data read from the input stream inStream. - */ - public CRL engineGenerateCRL( - InputStream inStream) - throws CRLException - { - if (currentCrlStream == null) - { - currentCrlStream = inStream; - sCrlData = null; - sCrlDataObjectCount = 0; - } - else if (currentCrlStream != inStream) // reset if input stream has changed - { - currentCrlStream = inStream; - sCrlData = null; - sCrlDataObjectCount = 0; - } - - try - { - if (sCrlData != null) - { - if (sCrlDataObjectCount != sCrlData.size()) - { - return getCRL(); - } - else - { - sCrlData = null; - sCrlDataObjectCount = 0; - return null; - } - } - - PushbackInputStream pis = new PushbackInputStream(inStream); - int tag = pis.read(); - - if (tag == -1) - { - return null; - } - - pis.unread(tag); - - if (tag != 0x30) // assume ascii PEM encoded. - { - return readPEMCRL(pis); - } - else - { // lazy evaluate to help processing of large CRLs - return readDERCRL(new ASN1InputStream(pis, true)); - } - } - catch (CRLException e) - { - throw e; - } - catch (Exception e) - { - throw new CRLException(e.toString()); - } - } - - /** - * Returns a (possibly empty) collection view of the CRLs read from - * the given input stream inStream. - * - * The inStream may contain a sequence of DER-encoded CRLs, or - * a PKCS#7 CRL set. This is a PKCS#7 SignedData object, with the - * only signficant field being crls. In particular the signature - * and the contents are ignored. - */ - public Collection engineGenerateCRLs( - InputStream inStream) - throws CRLException - { - CRL crl; - List crls = new ArrayList(); - - while ((crl = engineGenerateCRL(inStream)) != null) - { - crls.add(crl); - } - - return crls; - } - - public Iterator engineGetCertPathEncodings() - { - return null; // TODO: PKIXCertPath.certPathEncodings.iterator(); - } - - public CertPath engineGenerateCertPath( - InputStream inStream) - throws CertificateException - { - return engineGenerateCertPath(inStream, "PkiPath"); - } - - public CertPath engineGenerateCertPath( - InputStream inStream, - String encoding) - throws CertificateException - { - return new PKIXCertPath(inStream, encoding); - } - - public CertPath engineGenerateCertPath( - List certificates) - throws CertificateException - { - Iterator iter = certificates.iterator(); - Object obj; - while (iter.hasNext()) - { - obj = iter.next(); - if (obj != null) - { - if (!(obj instanceof X509Certificate)) - { - throw new CertificateException("list contains non X509Certificate object while creating CertPath\n" + obj.toString()); - } - } - } - return new PKIXCertPath(certificates); - } - - private class ExCertificateException - extends CertificateException - { - private Throwable cause; - - public ExCertificateException(Throwable cause) - { - this.cause = cause; - } - - public ExCertificateException(String msg, Throwable cause) - { - super(msg); - - this.cause = cause; - } - - public Throwable getCause() - { - return cause; - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/PKIXCertPath.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/PKIXCertPath.java deleted file mode 100644 index 0bc938326..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/PKIXCertPath.java +++ /dev/null @@ -1,379 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.x509; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStreamWriter; -import java.security.NoSuchProviderException; -import org.spongycastle.jce.cert.CertPath; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -import org.spongycastle.jce.X509Principal; -import org.spongycastle.jce.PrincipalUtil; -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.DERSet; -import org.spongycastle.asn1.pkcs.ContentInfo; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.pkcs.SignedData; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.util.io.pem.PemObject; -import org.spongycastle.util.io.pem.PemWriter; - -/** - * CertPath implementation for X.509 certificates. - *
- **/ -public class PKIXCertPath - extends CertPath -{ - static final List certPathEncodings; - - static - { - List encodings = new ArrayList(); - encodings.add("PkiPath"); - encodings.add("PEM"); - encodings.add("PKCS7"); - certPathEncodings = Collections.unmodifiableList(encodings); - } - - private List certificates; - - /** - * @param certs - */ - private List sortCerts( - List certs) - { - try - { - if (certs.size() < 2) - { - return certs; - } - - X509Principal issuer = PrincipalUtil.getIssuerX509Principal(((X509Certificate)certs.get(0))); - boolean okay = true; - - for (int i = 1; i != certs.size(); i++) - { - X509Certificate cert = (X509Certificate)certs.get(i); - - if (issuer.equals(PrincipalUtil.getSubjectX509Principal(cert))) - { - issuer = PrincipalUtil.getIssuerX509Principal(((X509Certificate)certs.get(i))); - } - else - { - okay = false; - break; - } - } - - if (okay) - { - return certs; - } - - // find end-entity cert - List retList = new ArrayList(certs.size()); - List orig = new ArrayList(certs); - - for (int i = 0; i < certs.size(); i++) - { - X509Certificate cert = (X509Certificate)certs.get(i); - boolean found = false; - - X509Principal subject = PrincipalUtil.getSubjectX509Principal(cert); - - for (int j = 0; j != certs.size(); j++) - { - X509Certificate c = (X509Certificate)certs.get(j); - if (PrincipalUtil.getIssuerX509Principal(c).equals(subject)) - { - found = true; - break; - } - } - - if (!found) - { - retList.add(cert); - certs.remove(i); - } - } - - // can only have one end entity cert - something's wrong, give up. - if (retList.size() > 1) - { - return orig; - } - - for (int i = 0; i != retList.size(); i++) - { - issuer = PrincipalUtil.getIssuerX509Principal(((X509Certificate)retList.get(i))); - - for (int j = 0; j < certs.size(); j++) - { - X509Certificate c = (X509Certificate)certs.get(j); - if (issuer.equals(PrincipalUtil.getSubjectX509Principal(c))) - { - retList.add(c); - certs.remove(j); - break; - } - } - } - - // make sure all certificates are accounted for. - if (certs.size() > 0) - { - return orig; - } - - return retList; - } - catch (Exception e) - { - return certs; - } - } - - PKIXCertPath(List certificates) - { - super("X.509"); - this.certificates = sortCerts(new ArrayList(certificates)); - } - - /** - * Creates a CertPath of the specified type. - * This constructor is protected because most users should use - * a CertificateFactory to create CertPaths. - **/ - PKIXCertPath( - InputStream inStream, - String encoding) - throws CertificateException - { - super("X.509"); - try - { - if (encoding.equalsIgnoreCase("PkiPath")) - { - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Primitive derObject = derInStream.readObject(); - if (!(derObject instanceof ASN1Sequence)) - { - throw new CertificateException("input stream does not contain a ASN1 SEQUENCE while reading PkiPath encoded data to load CertPath"); - } - Enumeration e = ((ASN1Sequence)derObject).getObjects(); - certificates = new ArrayList(); - CertificateFactory certFactory = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME); - while (e.hasMoreElements()) - { - ASN1Encodable element = (ASN1Encodable)e.nextElement(); - byte[] encoded = element.toASN1Primitive().getEncoded(ASN1Encoding.DER); - certificates.add(0, certFactory.generateCertificate( - new ByteArrayInputStream(encoded))); - } - } - else if (encoding.equalsIgnoreCase("PKCS7") || encoding.equalsIgnoreCase("PEM")) - { - inStream = new BufferedInputStream(inStream); - certificates = new ArrayList(); - CertificateFactory certFactory= CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME); - Certificate cert; - while ((cert = certFactory.generateCertificate(inStream)) != null) - { - certificates.add(cert); - } - } - else - { - throw new CertificateException("unsupported encoding: " + encoding); - } - } - catch (IOException ex) - { - throw new CertificateException("IOException throw while decoding CertPath:\n" + ex.toString()); - } - catch (NoSuchProviderException ex) - { - throw new CertificateException("BouncyCastle provider not found while trying to get a CertificateFactory:\n" + ex.toString()); - } - - this.certificates = sortCerts(certificates); - } - - /** - * Returns an iteration of the encodings supported by this - * certification path, with the default encoding - * first. Attempts to modify the returned Iterator via its - * remove method result in an UnsupportedOperationException. - * - * @return an Iterator over the names of the supported encodings (as Strings) - **/ - public Iterator getEncodings() - { - return certPathEncodings.iterator(); - } - - /** - * Returns the encoded form of this certification path, using - * the default encoding. - * - * @return the encoded bytes - * @exception java.security.cert.CertificateEncodingException if an encoding error occurs - **/ - public byte[] getEncoded() - throws CertificateEncodingException - { - Iterator iter = getEncodings(); - if (iter.hasNext()) - { - Object enc = iter.next(); - if (enc instanceof String) - { - return getEncoded((String)enc); - } - } - return null; - } - - /** - * Returns the encoded form of this certification path, using - * the specified encoding. - * - * @param encoding the name of the encoding to use - * @return the encoded bytes - * @exception java.security.cert.CertificateEncodingException if an encoding error - * occurs or the encoding requested is not supported - * - **/ - public byte[] getEncoded(String encoding) - throws CertificateEncodingException - { - if (encoding.equalsIgnoreCase("PkiPath")) - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - ListIterator iter = certificates.listIterator(certificates.size()); - while (iter.hasPrevious()) - { - v.add(toASN1Object((X509Certificate)iter.previous())); - } - - return toDEREncoded(new DERSequence(v)); - } - else if (encoding.equalsIgnoreCase("PKCS7")) - { - ContentInfo encInfo = new ContentInfo(PKCSObjectIdentifiers.data, null); - - ASN1EncodableVector v = new ASN1EncodableVector(); - for (int i = 0; i != certificates.size(); i++) - { - v.add(toASN1Object((X509Certificate)certificates.get(i))); - } - - SignedData sd = new SignedData( - new ASN1Integer(1), - new DERSet(), - encInfo, - new DERSet(v), - null, - new DERSet()); - - return toDEREncoded(new ContentInfo( - PKCSObjectIdentifiers.signedData, sd)); - } - else if (encoding.equalsIgnoreCase("PEM")) - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - PemWriter pWrt = new PemWriter(new OutputStreamWriter(bOut)); - - try - { - for (int i = 0; i != certificates.size(); i++) - { - pWrt.writeObject(new PemObject("CERTIFICATE", ((X509Certificate)certificates.get(i)).getEncoded())); - } - - pWrt.close(); - } - catch (Exception e) - { - throw new CertificateEncodingException("can't encode certificate for PEM encoded path"); - } - - return bOut.toByteArray(); - } - else - { - throw new CertificateEncodingException("unsupported encoding: " + encoding); - } - } - - /** - * Returns the list of certificates in this certification - * path. The List returned must be immutable and thread-safe. - * - * @return an immutable List of Certificates (may be empty, but not null) - **/ - public List getCertificates() - { - return Collections.unmodifiableList(new ArrayList(certificates)); - } - - /** - * Return a DERObject containing the encoded certificate. - * - * @param cert the X509Certificate object to be encoded - * - * @return the DERObject - **/ - private ASN1Primitive toASN1Object( - X509Certificate cert) - throws CertificateEncodingException - { - try - { - return new ASN1InputStream(cert.getEncoded()).readObject(); - } - catch (Exception e) - { - throw new CertificateEncodingException("Exception while encoding certificate: " + e.toString()); - } - } - - private byte[] toDEREncoded(ASN1Encodable obj) - throws CertificateEncodingException - { - try - { - return obj.toASN1Primitive().getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CertificateEncodingException("Exception thrown: " + e); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/SignatureUtil.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/SignatureUtil.java deleted file mode 100644 index 96a1529c2..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/SignatureUtil.java +++ /dev/null @@ -1,134 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.x509; - -import java.io.IOException; -import java.security.AlgorithmParameters; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Signature; -import java.security.SignatureException; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1Null; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.spongycastle.asn1.nist.NISTObjectIdentifiers; -import org.spongycastle.asn1.oiw.OIWObjectIdentifiers; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.pkcs.RSASSAPSSparams; -import org.spongycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x9.X9ObjectIdentifiers; - -class SignatureUtil -{ - private static final ASN1Null derNull = new DERNull(); - - static void setSignatureParameters( - Signature signature, - ASN1Encodable params) - throws NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - if (params != null && !derNull.equals(params.toASN1Primitive())) - { - try - { - AlgorithmParameters sigParams = AlgorithmParameters.getInstance(signature.getAlgorithm(), signature.getProvider().getName()); - - try - { - sigParams.init(params.toASN1Primitive().getEncoded(ASN1Encoding.DER)); - } - catch (IOException e) - { - throw new SignatureException("IOException decoding parameters: " + e.getMessage()); - } - } - catch (NoSuchProviderException e) - { - throw new SignatureException("cannot find provider: " + e.getMessage()); - } - } - } - - static String getSignatureName( - AlgorithmIdentifier sigAlgId) - { - ASN1Encodable params = sigAlgId.getParameters(); - - if (params != null && !derNull.equals(params)) - { - if (sigAlgId.getAlgorithm().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) - { - RSASSAPSSparams rsaParams = RSASSAPSSparams.getInstance(params); - - return getDigestAlgName(rsaParams.getHashAlgorithm().getAlgorithm()) + "withRSAandMGF1"; - } - if (sigAlgId.getAlgorithm().equals(X9ObjectIdentifiers.ecdsa_with_SHA2)) - { - ASN1Sequence ecDsaParams = ASN1Sequence.getInstance(params); - - return getDigestAlgName((ASN1ObjectIdentifier)ecDsaParams.getObjectAt(0)) + "withECDSA"; - } - } - - return sigAlgId.getAlgorithm().getId(); - } - - /** - * Return the digest algorithm using one of the standard JCA string - * representations rather the the algorithm identifier (if possible). - */ - private static String getDigestAlgName( - ASN1ObjectIdentifier digestAlgOID) - { - if (PKCSObjectIdentifiers.md5.equals(digestAlgOID)) - { - return "MD5"; - } - else if (OIWObjectIdentifiers.idSHA1.equals(digestAlgOID)) - { - return "SHA1"; - } - else if (NISTObjectIdentifiers.id_sha224.equals(digestAlgOID)) - { - return "SHA224"; - } - else if (NISTObjectIdentifiers.id_sha256.equals(digestAlgOID)) - { - return "SHA256"; - } - else if (NISTObjectIdentifiers.id_sha384.equals(digestAlgOID)) - { - return "SHA384"; - } - else if (NISTObjectIdentifiers.id_sha512.equals(digestAlgOID)) - { - return "SHA512"; - } - else if (TeleTrusTObjectIdentifiers.ripemd128.equals(digestAlgOID)) - { - return "RIPEMD128"; - } - else if (TeleTrusTObjectIdentifiers.ripemd160.equals(digestAlgOID)) - { - return "RIPEMD160"; - } - else if (TeleTrusTObjectIdentifiers.ripemd256.equals(digestAlgOID)) - { - return "RIPEMD256"; - } - else if (CryptoProObjectIdentifiers.gostR3411.equals(digestAlgOID)) - { - return "GOST3411"; - } - else - { - return digestAlgOID.getId(); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/X509CRLEntryObject.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/X509CRLEntryObject.java deleted file mode 100644 index dac30008b..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/X509CRLEntryObject.java +++ /dev/null @@ -1,293 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.x509; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.cert.CRLException; -import java.security.cert.X509CRLEntry; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Set; - -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Enumerated; -import org.spongycastle.asn1.util.ASN1Dump; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x509.CRLReason; -import org.spongycastle.asn1.x509.Extension; -import org.spongycastle.asn1.x509.Extensions; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.GeneralNames; -import org.spongycastle.asn1.x509.TBSCertList; -import org.spongycastle.asn1.x509.X509Extension; -import org.spongycastle.x509.extension.X509ExtensionUtil; -import org.spongycastle.jce.X509Principal; - -/** - * The following extensions are listed in RFC 2459 as relevant to CRL Entries - * - * ReasonCode Hode Instruction Code Invalidity Date Certificate Issuer - * (critical) - */ -class X509CRLEntryObject extends X509CRLEntry -{ - private TBSCertList.CRLEntry c; - - private X500Name certificateIssuer; - private int hashValue; - private boolean isHashValueSet; - - public X509CRLEntryObject(TBSCertList.CRLEntry c) - { - this.c = c; - this.certificateIssuer = null; - } - - /** - * Constructor for CRLEntries of indirect CRLs. If isIndirect - * is false {@link #getCertificateIssuer()} will always - * return null, previousCertificateIssuer is - * ignored. If this isIndirect is specified and this CRLEntry - * has no certificate issuer CRL entry extension - * previousCertificateIssuer is returned by - * {@link #getCertificateIssuer()}. - * - * @param c - * TBSCertList.CRLEntry object. - * @param isIndirect - * true if the corresponding CRL is a indirect - * CRL. - * @param previousCertificateIssuer - * Certificate issuer of the previous CRLEntry. - */ - public X509CRLEntryObject( - TBSCertList.CRLEntry c, - boolean isIndirect, - X500Name previousCertificateIssuer) - { - this.c = c; - this.certificateIssuer = loadCertificateIssuer(isIndirect, previousCertificateIssuer); - } - - /** - * Will return true if any extensions are present and marked as critical as - * we currently don't handle any extensions! - */ - public boolean hasUnsupportedCriticalExtension() - { - Set extns = getCriticalExtensionOIDs(); - - return extns != null && !extns.isEmpty(); - } - - private X500Name loadCertificateIssuer(boolean isIndirect, X500Name previousCertificateIssuer) - { - if (!isIndirect) - { - return null; - } - - byte[] ext = getExtensionValue(X509Extension.certificateIssuer.getId()); - if (ext == null) - { - return previousCertificateIssuer; - } - - try - { - GeneralName[] names = GeneralNames.getInstance( - X509ExtensionUtil.fromExtensionValue(ext)).getNames(); - for (int i = 0; i < names.length; i++) - { - if (names[i].getTagNo() == GeneralName.directoryName) - { - return X500Name.getInstance(names[i].getName()); - } - } - return null; - } - catch (IOException e) - { - return null; - } - } - - X509Principal getCertificateIssuer() - { - if (certificateIssuer == null) - { - return null; - } - try - { - return new X509Principal(certificateIssuer.getEncoded()); - } - catch (Exception e) - { - throw new IllegalStateException(e.toString()); - } - } - private Set getExtensionOIDs(boolean critical) - { - Extensions extensions = c.getExtensions(); - - if (extensions != null) - { - Set set = new HashSet(); - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (critical == ext.isCritical()) - { - set.add(oid.getId()); - } - } - - return set; - } - - return null; - } - - public Set getCriticalExtensionOIDs() - { - return getExtensionOIDs(true); - } - - public Set getNonCriticalExtensionOIDs() - { - return getExtensionOIDs(false); - } - - public byte[] getExtensionValue(String oid) - { - Extensions exts = c.getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new RuntimeException("error encoding " + e.toString()); - } - } - } - - return null; - } - - /** - * Cache the hashCode value - calculating it with the standard method. - * @return calculated hashCode. - */ - public int hashCode() - { - if (!isHashValueSet) - { - hashValue = super.hashCode(); - isHashValueSet = true; - } - - return hashValue; - } - - public byte[] getEncoded() - throws CRLException - { - try - { - return c.getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CRLException(e.toString()); - } - } - - public BigInteger getSerialNumber() - { - return c.getUserCertificate().getValue(); - } - - public Date getRevocationDate() - { - return c.getRevocationDate().getDate(); - } - - public boolean hasExtensions() - { - return c.getExtensions() != null; - } - - public String toString() - { - StringBuffer buf = new StringBuffer(); - String nl = System.getProperty("line.separator"); - - buf.append(" userCertificate: ").append(this.getSerialNumber()).append(nl); - buf.append(" revocationDate: ").append(this.getRevocationDate()).append(nl); - - Extensions extensions = c.getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - if (e.hasMoreElements()) - { - buf.append(" crlEntryExtensions:").append(nl); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - if (ext.getExtnValue() != null) - { - byte[] octs = ext.getExtnValue().getOctets(); - ASN1InputStream dIn = new ASN1InputStream(octs); - buf.append(" critical(").append(ext.isCritical()).append(") "); - try - { - if (oid.equals(X509Extension.reasonCode)) - { - buf.append(CRLReason.getInstance(ASN1Enumerated.getInstance(dIn.readObject()))).append(nl); - } - else if (oid.equals(X509Extension.certificateIssuer)) - { - buf.append("Certificate issuer: ").append(GeneralNames.getInstance(dIn.readObject())).append(nl); - } - else - { - buf.append(oid.getId()); - buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl); - } - } - catch (Exception ex) - { - buf.append(oid.getId()); - buf.append(" value = ").append("*****").append(nl); - } - } - else - { - buf.append(nl); - } - } - } - } - - return buf.toString(); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/X509CRLObject.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/X509CRLObject.java deleted file mode 100644 index f2b5f5d8d..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/X509CRLObject.java +++ /dev/null @@ -1,556 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.x509; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Principal; -import java.security.PublicKey; -import java.security.Signature; -import java.security.SignatureException; -import java.security.cert.CRLException; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509CRL; -import java.security.cert.X509CRLEntry; -import java.security.cert.X509Certificate; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.util.ASN1Dump; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x509.CRLDistPoint; -import org.spongycastle.asn1.x509.CRLNumber; -import org.spongycastle.asn1.x509.CertificateList; -import org.spongycastle.asn1.x509.Extension; -import org.spongycastle.asn1.x509.Extensions; -import org.spongycastle.asn1.x509.GeneralNames; -import org.spongycastle.asn1.x509.IssuingDistributionPoint; -import org.spongycastle.asn1.x509.TBSCertList; -import org.spongycastle.jce.X509Principal; -import org.spongycastle.jce.provider.RFC3280CertPathUtilities; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.util.encoders.Hex; -import org.spongycastle.x509.extension.X509ExtensionUtil; - -/** - * The following extensions are listed in RFC 2459 as relevant to CRLs - * - * Authority Key Identifier - * Issuer Alternative Name - * CRL Number - * Delta CRL Indicator (critical) - * Issuing Distribution Point (critical) - */ -class X509CRLObject - extends X509CRL -{ - private CertificateList c; - private String sigAlgName; - private byte[] sigAlgParams; - private boolean isIndirect; - - static boolean isIndirectCRL(X509CRL crl) - throws CRLException - { - try - { - byte[] idp = crl.getExtensionValue(Extension.issuingDistributionPoint.getId()); - return idp != null - && IssuingDistributionPoint.getInstance(X509ExtensionUtil.fromExtensionValue(idp)).isIndirectCRL(); - } - catch (Exception e) - { - throw new ExtCRLException( - "Exception reading IssuingDistributionPoint", e); - } - } - - public X509CRLObject( - CertificateList c) - throws CRLException - { - this.c = c; - - try - { - this.sigAlgName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm()); - - if (c.getSignatureAlgorithm().getParameters() != null) - { - this.sigAlgParams = ((ASN1Encodable)c.getSignatureAlgorithm().getParameters()).toASN1Primitive().getEncoded(ASN1Encoding.DER); - } - else - { - this.sigAlgParams = null; - } - - this.isIndirect = isIndirectCRL(this); - } - catch (Exception e) - { - throw new CRLException("CRL contents invalid: " + e); - } - } - - /** - * Will return true if any extensions are present and marked - * as critical as we currently dont handle any extensions! - */ - public boolean hasUnsupportedCriticalExtension() - { - Set extns = getCriticalExtensionOIDs(); - - if (extns == null) - { - return false; - } - - extns.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT); - extns.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR); - - return !extns.isEmpty(); - } - - private Set getExtensionOIDs(boolean critical) - { - if (this.getVersion() == 2) - { - Extensions extensions = c.getTBSCertList().getExtensions(); - - if (extensions != null) - { - Set set = new HashSet(); - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (critical == ext.isCritical()) - { - set.add(oid.getId()); - } - } - - return set; - } - } - - return null; - } - - public Set getCriticalExtensionOIDs() - { - return getExtensionOIDs(true); - } - - public Set getNonCriticalExtensionOIDs() - { - return getExtensionOIDs(false); - } - - public byte[] getExtensionValue(String oid) - { - Extensions exts = c.getTBSCertList().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - } - - return null; - } - - public byte[] getEncoded() - throws CRLException - { - try - { - return c.getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CRLException(e.toString()); - } - } - - public void verify(PublicKey key) - throws CRLException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - verify(key, BouncyCastleProvider.PROVIDER_NAME); - } - - public void verify(PublicKey key, String sigProvider) - throws CRLException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - if (!c.getSignatureAlgorithm().equals(c.getTBSCertList().getSignature())) - { - throw new CRLException("Signature algorithm on CertificateList does not match TBSCertList."); - } - - Signature sig; - - if (sigProvider != null) - { - sig = Signature.getInstance(getSigAlgName(), sigProvider); - } - else - { - sig = Signature.getInstance(getSigAlgName()); - } - - sig.initVerify(key); - sig.update(this.getTBSCertList()); - - if (!sig.verify(this.getSignature())) - { - throw new SignatureException("CRL does not verify with supplied public key."); - } - } - - public int getVersion() - { - return c.getVersionNumber(); - } - - public Principal getIssuerDN() - { - return new X509Principal(X500Name.getInstance(c.getIssuer().toASN1Primitive())); - } - - public Date getThisUpdate() - { - return c.getThisUpdate().getDate(); - } - - public Date getNextUpdate() - { - if (c.getNextUpdate() != null) - { - return c.getNextUpdate().getDate(); - } - - return null; - } - - private Set loadCRLEntries() - { - Set entrySet = new HashSet(); - Enumeration certs = c.getRevokedCertificateEnumeration(); - - X500Name previousCertificateIssuer = c.getIssuer(); - while (certs.hasMoreElements()) - { - TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)certs.nextElement(); - X509CRLEntryObject crlEntry = new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer); - entrySet.add(crlEntry); - if (isIndirect && entry.hasExtensions()) - { - Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); - - if (currentCaName != null) - { - previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); - } - } - } - - return entrySet; - } - - public X509CRLEntry getRevokedCertificate(BigInteger serialNumber) - { - Enumeration certs = c.getRevokedCertificateEnumeration(); - - X500Name previousCertificateIssuer = c.getIssuer(); - while (certs.hasMoreElements()) - { - TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)certs.nextElement(); - - if (serialNumber.equals(entry.getUserCertificate().getValue())) - { - return new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer); - } - - if (isIndirect && entry.hasExtensions()) - { - Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); - - if (currentCaName != null) - { - previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); - } - } - } - - return null; - } - - public Set getRevokedCertificates() - { - Set entrySet = loadCRLEntries(); - - if (!entrySet.isEmpty()) - { - return Collections.unmodifiableSet(entrySet); - } - - return null; - } - - public byte[] getTBSCertList() - throws CRLException - { - try - { - return c.getTBSCertList().getEncoded("DER"); - } - catch (IOException e) - { - throw new CRLException(e.toString()); - } - } - - public byte[] getSignature() - { - return c.getSignature().getBytes(); - } - - public String getSigAlgName() - { - return sigAlgName; - } - - public String getSigAlgOID() - { - return c.getSignatureAlgorithm().getAlgorithm().getId(); - } - - public byte[] getSigAlgParams() - { - if (sigAlgParams != null) - { - byte[] tmp = new byte[sigAlgParams.length]; - - System.arraycopy(sigAlgParams, 0, tmp, 0, tmp.length); - - return tmp; - } - - return null; - } - - /** - * Returns a string representation of this CRL. - * - * @return a string representation of this CRL. - */ - public String toString() - { - StringBuffer buf = new StringBuffer(); - String nl = System.getProperty("line.separator"); - - buf.append(" Version: ").append(this.getVersion()).append( - nl); - buf.append(" IssuerDN: ").append(this.getIssuerDN()) - .append(nl); - buf.append(" This update: ").append(this.getThisUpdate()) - .append(nl); - buf.append(" Next update: ").append(this.getNextUpdate()) - .append(nl); - buf.append(" Signature Algorithm: ").append(this.getSigAlgName()) - .append(nl); - - byte[] sig = this.getSignature(); - - buf.append(" Signature: ").append( - new String(Hex.encode(sig, 0, 20))).append(nl); - for (int i = 20; i < sig.length; i += 20) - { - if (i < sig.length - 20) - { - buf.append(" ").append( - new String(Hex.encode(sig, i, 20))).append(nl); - } - else - { - buf.append(" ").append( - new String(Hex.encode(sig, i, sig.length - i))).append(nl); - } - } - - Extensions extensions = c.getTBSCertList().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - if (e.hasMoreElements()) - { - buf.append(" Extensions: ").append(nl); - } - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (ext.getExtnValue() != null) - { - byte[] octs = ext.getExtnValue().getOctets(); - ASN1InputStream dIn = new ASN1InputStream(octs); - buf.append(" critical(").append( - ext.isCritical()).append(") "); - try - { - if (oid.equals(Extension.cRLNumber)) - { - buf.append( - new CRLNumber(ASN1Integer.getInstance( - dIn.readObject()).getPositiveValue())) - .append(nl); - } - else if (oid.equals(Extension.deltaCRLIndicator)) - { - buf.append( - "Base CRL: " - + new CRLNumber(ASN1Integer.getInstance( - dIn.readObject()).getPositiveValue())) - .append(nl); - } - else if (oid - .equals(Extension.issuingDistributionPoint)) - { - buf.append( - IssuingDistributionPoint.getInstance(dIn.readObject())).append(nl); - } - else if (oid - .equals(Extension.cRLDistributionPoints)) - { - buf.append( - CRLDistPoint.getInstance(dIn.readObject())).append(nl); - } - else if (oid.equals(Extension.freshestCRL)) - { - buf.append( - CRLDistPoint.getInstance(dIn.readObject())).append(nl); - } - else - { - buf.append(oid.getId()); - buf.append(" value = ").append( - ASN1Dump.dumpAsString(dIn.readObject())) - .append(nl); - } - } - catch (Exception ex) - { - buf.append(oid.getId()); - buf.append(" value = ").append("*****").append(nl); - } - } - else - { - buf.append(nl); - } - } - } - Set set = getRevokedCertificates(); - if (set != null) - { - Iterator it = set.iterator(); - while (it.hasNext()) - { - buf.append(it.next()); - buf.append(nl); - } - } - return buf.toString(); - } - - /** - * Checks whether the given certificate is on this CRL. - * - * @param cert the certificate to check for. - * @return true if the given certificate is on this CRL, - * false otherwise. - */ - public boolean isRevoked(Certificate cert) - { - if (!cert.getType().equals("X.509")) - { - throw new RuntimeException("X.509 CRL used with non X.509 Cert"); - } - - TBSCertList.CRLEntry[] certs = c.getRevokedCertificates(); - - X500Name caName = c.getIssuer(); - - if (certs != null) - { - BigInteger serial = ((X509Certificate)cert).getSerialNumber(); - - for (int i = 0; i < certs.length; i++) - { - if (isIndirect && certs[i].hasExtensions()) - { - Extension currentCaName = certs[i].getExtensions().getExtension(Extension.certificateIssuer); - - if (currentCaName != null) - { - caName = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); - } - } - - if (certs[i].getUserCertificate().getValue().equals(serial)) - { - X500Name issuer; - - try - { - issuer = org.spongycastle.asn1.x509.Certificate.getInstance(cert.getEncoded()).getIssuer(); - } - catch (CertificateEncodingException e) - { - throw new RuntimeException("Cannot process certificate"); - } - - if (!caName.equals(issuer)) - { - return false; - } - - return true; - } - } - } - - return false; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/X509CertificateObject.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/X509CertificateObject.java deleted file mode 100644 index aa83e65de..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/X509CertificateObject.java +++ /dev/null @@ -1,858 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.x509; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Principal; -import java.security.Provider; -import java.security.PublicKey; -import java.security.Security; -import java.security.Signature; -import java.security.SignatureException; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1OutputStream; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1String; -import org.spongycastle.asn1.DERBitString; -import org.spongycastle.asn1.DERIA5String; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.misc.MiscObjectIdentifiers; -import org.spongycastle.asn1.misc.NetscapeCertType; -import org.spongycastle.asn1.misc.NetscapeRevocationURL; -import org.spongycastle.asn1.misc.VerisignCzagExtension; -import org.spongycastle.asn1.util.ASN1Dump; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x500.style.RFC4519Style; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.BasicConstraints; -import org.spongycastle.asn1.x509.Extension; -import org.spongycastle.asn1.x509.Extensions; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.KeyUsage; -import org.spongycastle.jcajce.provider.asymmetric.util.PKCS12BagAttributeCarrierImpl; -import org.spongycastle.jce.X509Principal; -import org.spongycastle.jce.provider.RFC3280CertPathUtilities; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.jce.interfaces.PKCS12BagAttributeCarrier; -import org.spongycastle.util.Arrays; -import org.spongycastle.util.Integers; -import org.spongycastle.util.encoders.Hex; - -class X509CertificateObject - extends X509Certificate - implements PKCS12BagAttributeCarrier -{ - private org.spongycastle.asn1.x509.Certificate c; - private BasicConstraints basicConstraints; - private boolean[] keyUsage; - private boolean hashValueSet; - private int hashValue; - - private PKCS12BagAttributeCarrier attrCarrier = new PKCS12BagAttributeCarrierImpl(); - - public X509CertificateObject( - org.spongycastle.asn1.x509.Certificate c) - throws CertificateParsingException - { - this.c = c; - - try - { - byte[] bytes = this.getExtensionBytes("2.5.29.19"); - - if (bytes != null) - { - basicConstraints = BasicConstraints.getInstance(ASN1Primitive.fromByteArray(bytes)); - } - } - catch (Exception e) - { - throw new CertificateParsingException("cannot construct BasicConstraints: " + e); - } - - try - { - byte[] bytes = this.getExtensionBytes("2.5.29.15"); - if (bytes != null) - { - DERBitString bits = DERBitString.getInstance(ASN1Primitive.fromByteArray(bytes)); - - bytes = bits.getBytes(); - int length = (bytes.length * 8) - bits.getPadBits(); - - keyUsage = new boolean[(length < 9) ? 9 : length]; - - for (int i = 0; i != length; i++) - { - keyUsage[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0; - } - } - else - { - keyUsage = null; - } - } - catch (Exception e) - { - throw new CertificateParsingException("cannot construct KeyUsage: " + e); - } - } - - public void checkValidity() - throws CertificateExpiredException, CertificateNotYetValidException - { - this.checkValidity(new Date()); - } - - public void checkValidity( - Date date) - throws CertificateExpiredException, CertificateNotYetValidException - { - if (date.getTime() > this.getNotAfter().getTime()) // for other VM compatibility - { - throw new CertificateExpiredException("certificate expired on " + c.getEndDate().getTime()); - } - - if (date.getTime() < this.getNotBefore().getTime()) - { - throw new CertificateNotYetValidException("certificate not valid till " + c.getStartDate().getTime()); - } - } - - public int getVersion() - { - return c.getVersionNumber(); - } - - public BigInteger getSerialNumber() - { - return c.getSerialNumber().getValue(); - } - - public Principal getIssuerDN() - { - try - { - return new X509Principal(X500Name.getInstance(c.getIssuer().getEncoded())); - } - catch (IOException e) - { - return null; - } - } - - public Principal getSubjectDN() - { - return new X509Principal(X500Name.getInstance(c.getSubject().toASN1Primitive())); - } - - public Date getNotBefore() - { - return c.getStartDate().getDate(); - } - - public Date getNotAfter() - { - return c.getEndDate().getDate(); - } - - public byte[] getTBSCertificate() - throws CertificateEncodingException - { - try - { - return c.getTBSCertificate().getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CertificateEncodingException(e.toString()); - } - } - - public byte[] getSignature() - { - return c.getSignature().getBytes(); - } - - /** - * return a more "meaningful" representation for the signature algorithm used in - * the certficate. - */ - public String getSigAlgName() - { - Provider prov = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME); - - if (prov != null) - { - String algName = prov.getProperty("Alg.Alias.Signature." + this.getSigAlgOID()); - - if (algName != null) - { - return algName; - } - } - - Provider[] provs = Security.getProviders(); - - // - // search every provider looking for a real algorithm - // - for (int i = 0; i != provs.length; i++) - { - String algName = provs[i].getProperty("Alg.Alias.Signature." + this.getSigAlgOID()); - if (algName != null) - { - return algName; - } - } - - return this.getSigAlgOID(); - } - - /** - * return the object identifier for the signature. - */ - public String getSigAlgOID() - { - return c.getSignatureAlgorithm().getAlgorithm().getId(); - } - - /** - * return the signature parameters, or null if there aren't any. - */ - public byte[] getSigAlgParams() - { - if (c.getSignatureAlgorithm().getParameters() != null) - { - try - { - return c.getSignatureAlgorithm().getParameters().toASN1Primitive().getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - return null; - } - } - else - { - return null; - } - } - - public boolean[] getIssuerUniqueID() - { - DERBitString id = c.getTBSCertificate().getIssuerUniqueId(); - - if (id != null) - { - byte[] bytes = id.getBytes(); - boolean[] boolId = new boolean[bytes.length * 8 - id.getPadBits()]; - - for (int i = 0; i != boolId.length; i++) - { - boolId[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0; - } - - return boolId; - } - - return null; - } - - public boolean[] getSubjectUniqueID() - { - DERBitString id = c.getTBSCertificate().getSubjectUniqueId(); - - if (id != null) - { - byte[] bytes = id.getBytes(); - boolean[] boolId = new boolean[bytes.length * 8 - id.getPadBits()]; - - for (int i = 0; i != boolId.length; i++) - { - boolId[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0; - } - - return boolId; - } - - return null; - } - - public boolean[] getKeyUsage() - { - return keyUsage; - } - - public List getExtendedKeyUsage() - throws CertificateParsingException - { - byte[] bytes = this.getExtensionBytes("2.5.29.37"); - - if (bytes != null) - { - try - { - ASN1InputStream dIn = new ASN1InputStream(bytes); - ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); - List list = new ArrayList(); - - for (int i = 0; i != seq.size(); i++) - { - list.add(((ASN1ObjectIdentifier)seq.getObjectAt(i)).getId()); - } - - return Collections.unmodifiableList(list); - } - catch (Exception e) - { - throw new CertificateParsingException("error processing extended key usage extension"); - } - } - - return null; - } - - public int getBasicConstraints() - { - if (basicConstraints != null) - { - if (basicConstraints.isCA()) - { - if (basicConstraints.getPathLenConstraint() == null) - { - return Integer.MAX_VALUE; - } - else - { - return basicConstraints.getPathLenConstraint().intValue(); - } - } - else - { - return -1; - } - } - - return -1; - } - - public Collection getSubjectAlternativeNames() - throws CertificateParsingException - { - return getAlternativeNames(getExtensionBytes(Extension.subjectAlternativeName.getId())); - } - - public Collection getIssuerAlternativeNames() - throws CertificateParsingException - { - return getAlternativeNames(getExtensionBytes(Extension.issuerAlternativeName.getId())); - } - - public Set getCriticalExtensionOIDs() - { - if (this.getVersion() == 3) - { - Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (ext.isCritical()) - { - set.add(oid.getId()); - } - } - - return set; - } - } - - return null; - } - - private byte[] getExtensionBytes(String oid) - { - Extensions exts = c.getTBSCertificate().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - if (ext != null) - { - return ext.getExtnValue().getOctets(); - } - } - - return null; - } - - public byte[] getExtensionValue(String oid) - { - Extensions exts = c.getTBSCertificate().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - } - - return null; - } - - public Set getNonCriticalExtensionOIDs() - { - if (this.getVersion() == 3) - { - Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (!ext.isCritical()) - { - set.add(oid.getId()); - } - } - - return set; - } - } - - return null; - } - - public boolean hasUnsupportedCriticalExtension() - { - if (this.getVersion() == 3) - { - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - String oidId = oid.getId(); - - if (oidId.equals(RFC3280CertPathUtilities.KEY_USAGE) - || oidId.equals(RFC3280CertPathUtilities.CERTIFICATE_POLICIES) - || oidId.equals(RFC3280CertPathUtilities.POLICY_MAPPINGS) - || oidId.equals(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY) - || oidId.equals(RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS) - || oidId.equals(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT) - || oidId.equals(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR) - || oidId.equals(RFC3280CertPathUtilities.POLICY_CONSTRAINTS) - || oidId.equals(RFC3280CertPathUtilities.BASIC_CONSTRAINTS) - || oidId.equals(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME) - || oidId.equals(RFC3280CertPathUtilities.NAME_CONSTRAINTS)) - { - continue; - } - - Extension ext = extensions.getExtension(oid); - - if (ext.isCritical()) - { - return true; - } - } - } - } - - return false; - } - - public PublicKey getPublicKey() - { - try - { - return BouncyCastleProvider.getPublicKey(c.getSubjectPublicKeyInfo()); - } - catch (IOException e) - { - return null; // should never happen... - } - } - - public byte[] getEncoded() - throws CertificateEncodingException - { - try - { - return c.getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CertificateEncodingException(e.toString()); - } - } - - public boolean equals( - Object o) - { - if (o == this) - { - return true; - } - - if (!(o instanceof Certificate)) - { - return false; - } - - Certificate other = (Certificate)o; - - try - { - byte[] b1 = this.getEncoded(); - byte[] b2 = other.getEncoded(); - - return Arrays.areEqual(b1, b2); - } - catch (CertificateEncodingException e) - { - return false; - } - } - - public synchronized int hashCode() - { - if (!hashValueSet) - { - hashValue = calculateHashCode(); - hashValueSet = true; - } - - return hashValue; - } - - private int calculateHashCode() - { - try - { - int hashCode = 0; - byte[] certData = this.getEncoded(); - for (int i = 1; i < certData.length; i++) - { - hashCode += certData[i] * i; - } - return hashCode; - } - catch (CertificateEncodingException e) - { - return 0; - } - } - - public void setBagAttribute( - ASN1ObjectIdentifier oid, - ASN1Encodable attribute) - { - attrCarrier.setBagAttribute(oid, attribute); - } - - public ASN1Encodable getBagAttribute( - ASN1ObjectIdentifier oid) - { - return attrCarrier.getBagAttribute(oid); - } - - public Enumeration getBagAttributeKeys() - { - return attrCarrier.getBagAttributeKeys(); - } - - public String toString() - { - StringBuffer buf = new StringBuffer(); - String nl = System.getProperty("line.separator"); - - buf.append(" [0] Version: ").append(this.getVersion()).append(nl); - buf.append(" SerialNumber: ").append(this.getSerialNumber()).append(nl); - buf.append(" IssuerDN: ").append(this.getIssuerDN()).append(nl); - buf.append(" Start Date: ").append(this.getNotBefore()).append(nl); - buf.append(" Final Date: ").append(this.getNotAfter()).append(nl); - buf.append(" SubjectDN: ").append(this.getSubjectDN()).append(nl); - buf.append(" Public Key: ").append(this.getPublicKey()).append(nl); - buf.append(" Signature Algorithm: ").append(this.getSigAlgName()).append(nl); - - byte[] sig = this.getSignature(); - - buf.append(" Signature: ").append(new String(Hex.encode(sig, 0, 20))).append(nl); - for (int i = 20; i < sig.length; i += 20) - { - if (i < sig.length - 20) - { - buf.append(" ").append(new String(Hex.encode(sig, i, 20))).append(nl); - } - else - { - buf.append(" ").append(new String(Hex.encode(sig, i, sig.length - i))).append(nl); - } - } - - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - if (e.hasMoreElements()) - { - buf.append(" Extensions: \n"); - } - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (ext.getExtnValue() != null) - { - byte[] octs = ext.getExtnValue().getOctets(); - ASN1InputStream dIn = new ASN1InputStream(octs); - buf.append(" critical(").append(ext.isCritical()).append(") "); - try - { - if (oid.equals(Extension.basicConstraints)) - { - buf.append(BasicConstraints.getInstance(dIn.readObject())).append(nl); - } - else if (oid.equals(Extension.keyUsage)) - { - buf.append(KeyUsage.getInstance(dIn.readObject())).append(nl); - } - else if (oid.equals(MiscObjectIdentifiers.netscapeCertType)) - { - buf.append(new NetscapeCertType((DERBitString)dIn.readObject())).append(nl); - } - else if (oid.equals(MiscObjectIdentifiers.netscapeRevocationURL)) - { - buf.append(new NetscapeRevocationURL((DERIA5String)dIn.readObject())).append(nl); - } - else if (oid.equals(MiscObjectIdentifiers.verisignCzagExtension)) - { - buf.append(new VerisignCzagExtension((DERIA5String)dIn.readObject())).append(nl); - } - else - { - buf.append(oid.getId()); - buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl); - //buf.append(" value = ").append("*****").append(nl); - } - } - catch (Exception ex) - { - buf.append(oid.getId()); - // buf.append(" value = ").append(new String(Hex.encode(ext.getExtnValue().getOctets()))).append(nl); - buf.append(" value = ").append("*****").append(nl); - } - } - else - { - buf.append(nl); - } - } - } - - return buf.toString(); - } - - public final void verify( - PublicKey key) - throws CertificateException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - Signature signature; - String sigName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm()); - - try - { - signature = Signature.getInstance(sigName, BouncyCastleProvider.PROVIDER_NAME); - } - catch (Exception e) - { - signature = Signature.getInstance(sigName); - } - - checkSignature(key, signature); - } - - public final void verify( - PublicKey key, - String sigProvider) - throws CertificateException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - String sigName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm()); - Signature signature = Signature.getInstance(sigName, sigProvider); - - checkSignature(key, signature); - } - - private void checkSignature( - PublicKey key, - Signature signature) - throws CertificateException, NoSuchAlgorithmException, - SignatureException, InvalidKeyException - { - if (!isAlgIdEqual(c.getSignatureAlgorithm(), c.getTBSCertificate().getSignature())) - { - throw new CertificateException("signature algorithm in TBS cert not same as outer cert"); - } - - ASN1Encodable params = c.getSignatureAlgorithm().getParameters(); - - // TODO This should go after the initVerify? - X509SignatureUtil.setSignatureParameters(signature, params); - - signature.initVerify(key); - - signature.update(this.getTBSCertificate()); - - if (!signature.verify(this.getSignature())) - { - throw new SignatureException("certificate does not verify with supplied key"); - } - } - - private boolean isAlgIdEqual(AlgorithmIdentifier id1, AlgorithmIdentifier id2) - { - if (!id1.getAlgorithm().equals(id2.getAlgorithm())) - { - return false; - } - - if (id1.getParameters() == null) - { - if (id2.getParameters() != null && !id2.getParameters().equals(DERNull.INSTANCE)) - { - return false; - } - - return true; - } - - if (id2.getParameters() == null) - { - if (id1.getParameters() != null && !id1.getParameters().equals(DERNull.INSTANCE)) - { - return false; - } - - return true; - } - - return id1.getParameters().equals(id2.getParameters()); - } - - private static Collection getAlternativeNames(byte[] extVal) - throws CertificateParsingException - { - if (extVal == null) - { - return null; - } - try - { - Collection temp = new ArrayList(); - Enumeration it = ASN1Sequence.getInstance(extVal).getObjects(); - while (it.hasMoreElements()) - { - GeneralName genName = GeneralName.getInstance(it.nextElement()); - List list = new ArrayList(); - list.add(Integers.valueOf(genName.getTagNo())); - switch (genName.getTagNo()) - { - case GeneralName.ediPartyName: - case GeneralName.x400Address: - case GeneralName.otherName: - list.add(genName.getEncoded()); - break; - case GeneralName.directoryName: - list.add(X500Name.getInstance(RFC4519Style.INSTANCE, genName.getName()).toString()); - break; - case GeneralName.dNSName: - case GeneralName.rfc822Name: - case GeneralName.uniformResourceIdentifier: - list.add(((ASN1String)genName.getName()).getString()); - break; - case GeneralName.registeredID: - list.add(ASN1ObjectIdentifier.getInstance(genName.getName()).getId()); - break; - case GeneralName.iPAddress: - byte[] addrBytes = DEROctetString.getInstance(genName.getName()).getOctets(); - list.add(addrBytes); - break; - default: - throw new IOException("Bad tag number: " + genName.getTagNo()); - } - - temp.add(list); - } - if (temp.size() == 0) - { - return null; - } - return Collections.unmodifiableCollection(temp); - } - catch (Exception e) - { - throw new CertificateParsingException(e.getMessage()); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java deleted file mode 100644 index e74ced7f5..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/X509SignatureUtil.java +++ /dev/null @@ -1,125 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.x509; - -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.Signature; -import java.security.SignatureException; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Null; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.spongycastle.asn1.nist.NISTObjectIdentifiers; -import org.spongycastle.asn1.oiw.OIWObjectIdentifiers; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.pkcs.RSASSAPSSparams; -import org.spongycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; - -class X509SignatureUtil -{ - private static final ASN1Null derNull = new DERNull(); - - static void setSignatureParameters( - Signature signature, - ASN1Encodable params) - throws NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - if (params != null && !derNull.equals(params)) - { - /* - AlgorithmParameters sigParams = AlgorithmParameters.getInstance(signature.getAlgorithm(), signature.getProvider()); - - try - { - sigParams.init(params.getDERObject().getDEREncoded()); - } - catch (IOException e) - { - throw new SignatureException("IOException decoding parameters: " + e.getMessage()); - } - - try - { - signature.setParameters(sigParams.getParameterSpec(PSSParameterSpec.class)); - } - catch (GeneralSecurityException e) - { - throw new SignatureException("Exception extracting parameters: " + e.getMessage()); - } - */ - } - } - - static String getSignatureName( - AlgorithmIdentifier sigAlgId) - { - ASN1Encodable params = sigAlgId.getParameters(); - - if (params != null && !derNull.equals(params)) - { - if (sigAlgId.getObjectId().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) - { - RSASSAPSSparams rsaParams = RSASSAPSSparams.getInstance(params); - - return getDigestAlgName(rsaParams.getHashAlgorithm().getObjectId()) + "withRSAandMGF1"; - } - } - - return sigAlgId.getObjectId().getId(); - } - - /** - * Return the digest algorithm using one of the standard JCA string - * representations rather the the algorithm identifier (if possible). - */ - private static String getDigestAlgName( - ASN1ObjectIdentifier digestAlgOID) - { - if (PKCSObjectIdentifiers.md5.equals(digestAlgOID)) - { - return "MD5"; - } - else if (OIWObjectIdentifiers.idSHA1.equals(digestAlgOID)) - { - return "SHA1"; - } - else if (NISTObjectIdentifiers.id_sha224.equals(digestAlgOID)) - { - return "SHA224"; - } - else if (NISTObjectIdentifiers.id_sha256.equals(digestAlgOID)) - { - return "SHA256"; - } - else if (NISTObjectIdentifiers.id_sha384.equals(digestAlgOID)) - { - return "SHA384"; - } - else if (NISTObjectIdentifiers.id_sha512.equals(digestAlgOID)) - { - return "SHA512"; - } - else if (TeleTrusTObjectIdentifiers.ripemd128.equals(digestAlgOID)) - { - return "RIPEMD128"; - } - else if (TeleTrusTObjectIdentifiers.ripemd160.equals(digestAlgOID)) - { - return "RIPEMD160"; - } - else if (TeleTrusTObjectIdentifiers.ripemd256.equals(digestAlgOID)) - { - return "RIPEMD256"; - } - else if (CryptoProObjectIdentifiers.gostR3411.equals(digestAlgOID)) - { - return "GOST3411"; - } - else - { - return digestAlgOID.getId(); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java deleted file mode 100644 index 9875bd140..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java +++ /dev/null @@ -1,1636 +0,0 @@ -package org.spongycastle.jcajce.provider.keystore.pkcs12; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.Key; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.KeyStoreSpi; -import java.security.NoSuchAlgorithmException; -import java.security.Principal; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.UnrecoverableKeyException; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.Date; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Vector; - -import javax.crypto.Cipher; -import javax.crypto.Mac; -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.PBEParameterSpec; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1Set; -import org.spongycastle.asn1.BEROctetString; -import org.spongycastle.asn1.BEROutputStream; -import org.spongycastle.asn1.DERBMPString; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.DEROutputStream; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.DERSet; -import org.spongycastle.asn1.pkcs.AuthenticatedSafe; -import org.spongycastle.asn1.pkcs.CertBag; -import org.spongycastle.asn1.pkcs.ContentInfo; -import org.spongycastle.asn1.pkcs.EncryptedData; -import org.spongycastle.asn1.pkcs.MacData; -import org.spongycastle.asn1.pkcs.PBES2Parameters; -import org.spongycastle.asn1.pkcs.PBKDF2Params; -import org.spongycastle.asn1.pkcs.PKCS12PBEParams; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.pkcs.Pfx; -import org.spongycastle.asn1.pkcs.SafeBag; -import org.spongycastle.asn1.util.ASN1Dump; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.AuthorityKeyIdentifier; -import org.spongycastle.asn1.x509.DigestInfo; -import org.spongycastle.asn1.x509.Extension; -import org.spongycastle.asn1.x509.SubjectKeyIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x509.X509ObjectIdentifiers; -import org.spongycastle.crypto.Digest; -import org.spongycastle.crypto.digests.SHA1Digest; -import org.spongycastle.jcajce.provider.symmetric.util.BCPBEKey; -import org.spongycastle.jcajce.provider.util.SecretKeyUtil; -import org.spongycastle.jce.interfaces.BCKeyStore; -import org.spongycastle.jce.interfaces.PKCS12BagAttributeCarrier; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.util.Arrays; -import org.spongycastle.util.Strings; -import org.spongycastle.util.encoders.Hex; - -public class PKCS12KeyStoreSpi - extends KeyStoreSpi - implements PKCSObjectIdentifiers, X509ObjectIdentifiers, BCKeyStore -{ - private static final int SALT_SIZE = 20; - private static final int MIN_ITERATIONS = 1024; - - private static final Provider bcProvider = new BouncyCastleProvider(); - - private IgnoresCaseHashtable keys = new IgnoresCaseHashtable(); - private Hashtable localIds = new Hashtable(); - private IgnoresCaseHashtable certs = new IgnoresCaseHashtable(); - private Hashtable chainCerts = new Hashtable(); - private Hashtable keyCerts = new Hashtable(); - - // - // generic object types - // - static final int NULL = 0; - static final int CERTIFICATE = 1; - static final int KEY = 2; - static final int SECRET = 3; - static final int SEALED = 4; - - // - // key types - // - static final int KEY_PRIVATE = 0; - static final int KEY_PUBLIC = 1; - static final int KEY_SECRET = 2; - - protected SecureRandom random = new SecureRandom(); - - // use of final causes problems with JDK 1.2 compiler - private CertificateFactory certFact; - private ASN1ObjectIdentifier keyAlgorithm; - private ASN1ObjectIdentifier certAlgorithm; - - private class CertId - { - byte[] id; - - CertId( - PublicKey key) - { - this.id = createSubjectKeyId(key).getKeyIdentifier(); - } - - CertId( - byte[] id) - { - this.id = id; - } - - public int hashCode() - { - return Arrays.hashCode(id); - } - - public boolean equals( - Object o) - { - if (o == this) - { - return true; - } - - if (!(o instanceof CertId)) - { - return false; - } - - CertId cId = (CertId)o; - - return Arrays.areEqual(id, cId.id); - } - } - - public PKCS12KeyStoreSpi( - Provider provider, - ASN1ObjectIdentifier keyAlgorithm, - ASN1ObjectIdentifier certAlgorithm) - { - this.keyAlgorithm = keyAlgorithm; - this.certAlgorithm = certAlgorithm; - - try - { - if (provider != null) - { - certFact = CertificateFactory.getInstance("X.509", provider.getName()); - } - else - { - certFact = CertificateFactory.getInstance("X.509"); - } - } - catch (Exception e) - { - throw new IllegalArgumentException("can't create cert factory - " + e.toString()); - } - } - - private SubjectKeyIdentifier createSubjectKeyId( - PublicKey pubKey) - { - try - { - SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); - - return new SubjectKeyIdentifier(getDigest(info)); - } - catch (Exception e) - { - throw new RuntimeException("error creating key"); - } - } - - private static byte[] getDigest(SubjectPublicKeyInfo spki) - { - Digest digest = new SHA1Digest(); - byte[] resBuf = new byte[digest.getDigestSize()]; - - byte[] bytes = spki.getPublicKeyData().getBytes(); - digest.update(bytes, 0, bytes.length); - digest.doFinal(resBuf, 0); - return resBuf; - } - - public void setRandom( - SecureRandom rand) - { - this.random = rand; - } - - public Enumeration engineAliases() - { - Hashtable tab = new Hashtable(); - - Enumeration e = certs.keys(); - while (e.hasMoreElements()) - { - tab.put(e.nextElement(), "cert"); - } - - e = keys.keys(); - while (e.hasMoreElements()) - { - String a = (String)e.nextElement(); - if (tab.get(a) == null) - { - tab.put(a, "key"); - } - } - - return tab.keys(); - } - - public boolean engineContainsAlias( - String alias) - { - return (certs.get(alias) != null || keys.get(alias) != null); - } - - /** - * this is not quite complete - we should follow up on the chain, a bit - * tricky if a certificate appears in more than one chain... - */ - public void engineDeleteEntry( - String alias) - throws KeyStoreException - { - Key k = (Key)keys.remove(alias); - - Certificate c = (Certificate)certs.remove(alias); - - if (c != null) - { - chainCerts.remove(new CertId(c.getPublicKey())); - } - - if (k != null) - { - String id = (String)localIds.remove(alias); - if (id != null) - { - c = (Certificate)keyCerts.remove(id); - } - if (c != null) - { - chainCerts.remove(new CertId(c.getPublicKey())); - } - } - } - - /** - * simply return the cert for the private key - */ - public Certificate engineGetCertificate( - String alias) - { - if (alias == null) - { - throw new IllegalArgumentException("null alias passed to getCertificate."); - } - - Certificate c = (Certificate)certs.get(alias); - - // - // look up the key table - and try the local key id - // - if (c == null) - { - String id = (String)localIds.get(alias); - if (id != null) - { - c = (Certificate)keyCerts.get(id); - } - else - { - c = (Certificate)keyCerts.get(alias); - } - } - - return c; - } - - public String engineGetCertificateAlias( - Certificate cert) - { - Enumeration c = certs.elements(); - Enumeration k = certs.keys(); - - while (c.hasMoreElements()) - { - Certificate tc = (Certificate)c.nextElement(); - String ta = (String)k.nextElement(); - - if (tc.equals(cert)) - { - return ta; - } - } - - c = keyCerts.elements(); - k = keyCerts.keys(); - - while (c.hasMoreElements()) - { - Certificate tc = (Certificate)c.nextElement(); - String ta = (String)k.nextElement(); - - if (tc.equals(cert)) - { - return ta; - } - } - - return null; - } - - public Certificate[] engineGetCertificateChain( - String alias) - { - if (alias == null) - { - throw new IllegalArgumentException("null alias passed to getCertificateChain."); - } - - if (!engineIsKeyEntry(alias)) - { - return null; - } - - Certificate c = engineGetCertificate(alias); - - if (c != null) - { - Vector cs = new Vector(); - - while (c != null) - { - X509Certificate x509c = (X509Certificate)c; - Certificate nextC = null; - - byte[] bytes = x509c.getExtensionValue(Extension.authorityKeyIdentifier.getId()); - if (bytes != null) - { - try - { - ASN1InputStream aIn = new ASN1InputStream(bytes); - - byte[] authBytes = ((ASN1OctetString)aIn.readObject()).getOctets(); - aIn = new ASN1InputStream(authBytes); - - AuthorityKeyIdentifier id = AuthorityKeyIdentifier.getInstance(aIn.readObject()); - if (id.getKeyIdentifier() != null) - { - nextC = (Certificate)chainCerts.get(new CertId(id.getKeyIdentifier())); - } - - } - catch (IOException e) - { - throw new RuntimeException(e.toString()); - } - } - - if (nextC == null) - { - // - // no authority key id, try the Issuer DN - // - Principal i = x509c.getIssuerDN(); - Principal s = x509c.getSubjectDN(); - - if (!i.equals(s)) - { - Enumeration e = chainCerts.keys(); - - while (e.hasMoreElements()) - { - X509Certificate crt = (X509Certificate)chainCerts.get(e.nextElement()); - Principal sub = crt.getSubjectDN(); - if (sub.equals(i)) - { - try - { - x509c.verify(crt.getPublicKey()); - nextC = crt; - break; - } - catch (Exception ex) - { - // continue - } - } - } - } - } - - cs.addElement(c); - if (nextC != c) // self signed - end of the chain - { - c = nextC; - } - else - { - c = null; - } - } - - Certificate[] certChain = new Certificate[cs.size()]; - - for (int i = 0; i != certChain.length; i++) - { - certChain[i] = (Certificate)cs.elementAt(i); - } - - return certChain; - } - - return null; - } - - public Date engineGetCreationDate(String alias) - { - if (alias == null) - { - throw new NullPointerException("alias == null"); - } - if (keys.get(alias) == null && certs.get(alias) == null) - { - return null; - } - return new Date(); - } - - public Key engineGetKey( - String alias, - char[] password) - throws NoSuchAlgorithmException, UnrecoverableKeyException - { - if (alias == null) - { - throw new IllegalArgumentException("null alias passed to getKey."); - } - - return (Key)keys.get(alias); - } - - public boolean engineIsCertificateEntry( - String alias) - { - return (certs.get(alias) != null && keys.get(alias) == null); - } - - public boolean engineIsKeyEntry( - String alias) - { - return (keys.get(alias) != null); - } - - public void engineSetCertificateEntry( - String alias, - Certificate cert) - throws KeyStoreException - { - if (keys.get(alias) != null) - { - throw new KeyStoreException("There is a key entry with the name " + alias + "."); - } - - certs.put(alias, cert); - chainCerts.put(new CertId(cert.getPublicKey()), cert); - } - - public void engineSetKeyEntry( - String alias, - byte[] key, - Certificate[] chain) - throws KeyStoreException - { - throw new RuntimeException("operation not supported"); - } - - public void engineSetKeyEntry( - String alias, - Key key, - char[] password, - Certificate[] chain) - throws KeyStoreException - { - if (!(key instanceof PrivateKey)) - { - throw new KeyStoreException("PKCS12 does not support non-PrivateKeys"); - } - - if ((key instanceof PrivateKey) && (chain == null)) - { - throw new KeyStoreException("no certificate chain for private key"); - } - - if (keys.get(alias) != null) - { - engineDeleteEntry(alias); - } - - keys.put(alias, key); - if (chain != null) - { - certs.put(alias, chain[0]); - - for (int i = 0; i != chain.length; i++) - { - chainCerts.put(new CertId(chain[i].getPublicKey()), chain[i]); - } - } - } - - public int engineSize() - { - Hashtable tab = new Hashtable(); - - Enumeration e = certs.keys(); - while (e.hasMoreElements()) - { - tab.put(e.nextElement(), "cert"); - } - - e = keys.keys(); - while (e.hasMoreElements()) - { - String a = (String)e.nextElement(); - if (tab.get(a) == null) - { - tab.put(a, "key"); - } - } - - return tab.size(); - } - - protected PrivateKey unwrapKey( - AlgorithmIdentifier algId, - byte[] data, - char[] password, - boolean wrongPKCS12Zero) - throws IOException - { - ASN1ObjectIdentifier algorithm = algId.getAlgorithm(); - try - { - if (algorithm.on(PKCSObjectIdentifiers.pkcs_12PbeIds)) - { - PKCS12PBEParams pbeParams = PKCS12PBEParams.getInstance(algId.getParameters()); - - PBEKeySpec pbeSpec = new PBEKeySpec(password); - PrivateKey out; - - SecretKeyFactory keyFact = SecretKeyFactory.getInstance( - algorithm.getId(), bcProvider); - PBEParameterSpec defParams = new PBEParameterSpec( - pbeParams.getIV(), - pbeParams.getIterations().intValue()); - - SecretKey k = keyFact.generateSecret(pbeSpec); - - ((BCPBEKey)k).setTryWrongPKCS12Zero(wrongPKCS12Zero); - - Cipher cipher = Cipher.getInstance(algorithm.getId(), bcProvider); - - cipher.init(Cipher.UNWRAP_MODE, k, defParams); - - // we pass "" as the key algorithm type as it is unknown at this point - return (PrivateKey)cipher.unwrap(data, "", Cipher.PRIVATE_KEY); - } - else if (algorithm.equals(PKCSObjectIdentifiers.id_PBES2)) - { - PBES2Parameters alg = PBES2Parameters.getInstance(algId.getParameters()); - PBKDF2Params func = PBKDF2Params.getInstance(alg.getKeyDerivationFunc().getParameters()); - - SecretKeyFactory keyFact = SecretKeyFactory.getInstance(alg.getKeyDerivationFunc().getAlgorithm().getId(), bcProvider); - - SecretKey k = keyFact.generateSecret(new PBEKeySpec(password, func.getSalt(), func.getIterationCount().intValue(), SecretKeyUtil.getKeySize(alg.getEncryptionScheme().getAlgorithm()))); - - Cipher cipher = Cipher.getInstance(alg.getEncryptionScheme().getAlgorithm().getId(), bcProvider); - - cipher.init(Cipher.UNWRAP_MODE, k, new IvParameterSpec(ASN1OctetString.getInstance(alg.getEncryptionScheme().getParameters()).getOctets())); - - // we pass "" as the key algorithm type as it is unknown at this point - return (PrivateKey)cipher.unwrap(data, "", Cipher.PRIVATE_KEY); - } - } - catch (Exception e) - { - throw new IOException("exception unwrapping private key - " + e.toString()); - } - - throw new IOException("exception unwrapping private key - cannot recognise: " + algorithm); - } - - protected byte[] wrapKey( - String algorithm, - Key key, - PKCS12PBEParams pbeParams, - char[] password) - throws IOException - { - PBEKeySpec pbeSpec = new PBEKeySpec(password); - byte[] out; - - try - { - SecretKeyFactory keyFact = SecretKeyFactory.getInstance( - algorithm, bcProvider); - PBEParameterSpec defParams = new PBEParameterSpec( - pbeParams.getIV(), - pbeParams.getIterations().intValue()); - - Cipher cipher = Cipher.getInstance(algorithm, bcProvider); - - cipher.init(Cipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), defParams); - - out = cipher.wrap(key); - } - catch (Exception e) - { - throw new IOException("exception encrypting data - " + e.toString()); - } - - return out; - } - - protected byte[] cryptData( - boolean forEncryption, - AlgorithmIdentifier algId, - char[] password, - boolean wrongPKCS12Zero, - byte[] data) - throws IOException - { - String algorithm = algId.getAlgorithm().getId(); - PKCS12PBEParams pbeParams = PKCS12PBEParams.getInstance(algId.getParameters()); - PBEKeySpec pbeSpec = new PBEKeySpec(password); - - try - { - SecretKeyFactory keyFact = SecretKeyFactory.getInstance(algorithm, bcProvider); - PBEParameterSpec defParams = new PBEParameterSpec( - pbeParams.getIV(), - pbeParams.getIterations().intValue()); - BCPBEKey key = (BCPBEKey)keyFact.generateSecret(pbeSpec); - - key.setTryWrongPKCS12Zero(wrongPKCS12Zero); - - Cipher cipher = Cipher.getInstance(algorithm, bcProvider); - int mode = forEncryption ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE; - cipher.init(mode, key, defParams); - return cipher.doFinal(data); - } - catch (Exception e) - { - throw new IOException("exception decrypting data - " + e.toString()); - } - } - - public void engineLoad( - InputStream stream, - char[] password) - throws IOException - { - if (stream == null) // just initialising - { - return; - } - - if (password == null) - { - throw new NullPointerException("No password supplied for PKCS#12 KeyStore."); - } - - BufferedInputStream bufIn = new BufferedInputStream(stream); - - bufIn.mark(10); - - int head = bufIn.read(); - - if (head != 0x30) - { - throw new IOException("stream does not represent a PKCS12 key store"); - } - - bufIn.reset(); - - ASN1InputStream bIn = new ASN1InputStream(bufIn); - ASN1Sequence obj = (ASN1Sequence)bIn.readObject(); - Pfx bag = Pfx.getInstance(obj); - ContentInfo info = bag.getAuthSafe(); - Vector chain = new Vector(); - boolean unmarkedKey = false; - boolean wrongPKCS12Zero = false; - - if (bag.getMacData() != null) // check the mac code - { - MacData mData = bag.getMacData(); - DigestInfo dInfo = mData.getMac(); - AlgorithmIdentifier algId = dInfo.getAlgorithmId(); - byte[] salt = mData.getSalt(); - int itCount = mData.getIterationCount().intValue(); - - byte[] data = ((ASN1OctetString)info.getContent()).getOctets(); - - try - { - byte[] res = calculatePbeMac(algId.getAlgorithm(), salt, itCount, password, false, data); - byte[] dig = dInfo.getDigest(); - - if (!Arrays.constantTimeAreEqual(res, dig)) - { - if (password.length > 0) - { - throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file."); - } - - // Try with incorrect zero length password - res = calculatePbeMac(algId.getAlgorithm(), salt, itCount, password, true, data); - - if (!Arrays.constantTimeAreEqual(res, dig)) - { - throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file."); - } - - wrongPKCS12Zero = true; - } - } - catch (IOException e) - { - throw e; - } - catch (Exception e) - { - throw new IOException("error constructing MAC: " + e.toString()); - } - } - - keys = new IgnoresCaseHashtable(); - localIds = new Hashtable(); - - if (info.getContentType().equals(data)) - { - bIn = new ASN1InputStream(((ASN1OctetString)info.getContent()).getOctets()); - - AuthenticatedSafe authSafe = AuthenticatedSafe.getInstance(bIn.readObject()); - ContentInfo[] c = authSafe.getContentInfo(); - - for (int i = 0; i != c.length; i++) - { - if (c[i].getContentType().equals(data)) - { - ASN1InputStream dIn = new ASN1InputStream(((ASN1OctetString)c[i].getContent()).getOctets()); - ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); - - for (int j = 0; j != seq.size(); j++) - { - SafeBag b = SafeBag.getInstance(seq.getObjectAt(j)); - if (b.getBagId().equals(pkcs8ShroudedKeyBag)) - { - org.spongycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = org.spongycastle.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(b.getBagValue()); - PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero); - - // - // set the attributes on the key - // - PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)privKey; - String alias = null; - ASN1OctetString localId = null; - - if (b.getBagAttributes() != null) - { - Enumeration e = b.getBagAttributes().getObjects(); - while (e.hasMoreElements()) - { - ASN1Sequence sq = (ASN1Sequence)e.nextElement(); - ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier)sq.getObjectAt(0); - ASN1Set attrSet = (ASN1Set)sq.getObjectAt(1); - ASN1Primitive attr = null; - - if (attrSet.size() > 0) - { - attr = (ASN1Primitive)attrSet.getObjectAt(0); - - ASN1Encodable existing = bagAttr.getBagAttribute(aOid); - if (existing != null) - { - // OK, but the value has to be the same - if (!existing.toASN1Primitive().equals(attr)) - { - throw new IOException( - "attempt to add existing attribute with different value"); - } - } - else - { - bagAttr.setBagAttribute(aOid, attr); - } - } - - if (aOid.equals(pkcs_9_at_friendlyName)) - { - alias = ((DERBMPString)attr).getString(); - keys.put(alias, privKey); - } - else if (aOid.equals(pkcs_9_at_localKeyId)) - { - localId = (ASN1OctetString)attr; - } - } - } - - if (localId != null) - { - String name = new String(Hex.encode(localId.getOctets())); - - if (alias == null) - { - keys.put(name, privKey); - } - else - { - localIds.put(alias, name); - } - } - else - { - unmarkedKey = true; - keys.put("unmarked", privKey); - } - } - else if (b.getBagId().equals(certBag)) - { - chain.addElement(b); - } - else - { - System.out.println("extra in data " + b.getBagId()); - System.out.println(ASN1Dump.dumpAsString(b)); - } - } - } - else if (c[i].getContentType().equals(encryptedData)) - { - EncryptedData d = EncryptedData.getInstance(c[i].getContent()); - byte[] octets = cryptData(false, d.getEncryptionAlgorithm(), - password, wrongPKCS12Zero, d.getContent().getOctets()); - ASN1Sequence seq = (ASN1Sequence)ASN1Primitive.fromByteArray(octets); - - for (int j = 0; j != seq.size(); j++) - { - SafeBag b = SafeBag.getInstance(seq.getObjectAt(j)); - - if (b.getBagId().equals(certBag)) - { - chain.addElement(b); - } - else if (b.getBagId().equals(pkcs8ShroudedKeyBag)) - { - org.spongycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = org.spongycastle.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(b.getBagValue()); - PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero); - - // - // set the attributes on the key - // - PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)privKey; - String alias = null; - ASN1OctetString localId = null; - - Enumeration e = b.getBagAttributes().getObjects(); - while (e.hasMoreElements()) - { - ASN1Sequence sq = (ASN1Sequence)e.nextElement(); - ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier)sq.getObjectAt(0); - ASN1Set attrSet = (ASN1Set)sq.getObjectAt(1); - ASN1Primitive attr = null; - - if (attrSet.size() > 0) - { - attr = (ASN1Primitive)attrSet.getObjectAt(0); - - ASN1Encodable existing = bagAttr.getBagAttribute(aOid); - if (existing != null) - { - // OK, but the value has to be the same - if (!existing.toASN1Primitive().equals(attr)) - { - throw new IOException( - "attempt to add existing attribute with different value"); - } - } - else - { - bagAttr.setBagAttribute(aOid, attr); - } - } - - if (aOid.equals(pkcs_9_at_friendlyName)) - { - alias = ((DERBMPString)attr).getString(); - keys.put(alias, privKey); - } - else if (aOid.equals(pkcs_9_at_localKeyId)) - { - localId = (ASN1OctetString)attr; - } - } - - String name = new String(Hex.encode(localId.getOctets())); - - if (alias == null) - { - keys.put(name, privKey); - } - else - { - localIds.put(alias, name); - } - } - else if (b.getBagId().equals(keyBag)) - { - org.spongycastle.asn1.pkcs.PrivateKeyInfo kInfo = org.spongycastle.asn1.pkcs.PrivateKeyInfo.getInstance(b.getBagValue()); - PrivateKey privKey = BouncyCastleProvider.getPrivateKey(kInfo); - - // - // set the attributes on the key - // - PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)privKey; - String alias = null; - ASN1OctetString localId = null; - - Enumeration e = b.getBagAttributes().getObjects(); - while (e.hasMoreElements()) - { - ASN1Sequence sq = (ASN1Sequence)e.nextElement(); - ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier)sq.getObjectAt(0); - ASN1Set attrSet = (ASN1Set)sq.getObjectAt(1); - ASN1Primitive attr = null; - - if (attrSet.size() > 0) - { - attr = (ASN1Primitive)attrSet.getObjectAt(0); - - ASN1Encodable existing = bagAttr.getBagAttribute(aOid); - if (existing != null) - { - // OK, but the value has to be the same - if (!existing.toASN1Primitive().equals(attr)) - { - throw new IOException( - "attempt to add existing attribute with different value"); - } - } - else - { - bagAttr.setBagAttribute(aOid, attr); - } - } - - if (aOid.equals(pkcs_9_at_friendlyName)) - { - alias = ((DERBMPString)attr).getString(); - keys.put(alias, privKey); - } - else if (aOid.equals(pkcs_9_at_localKeyId)) - { - localId = (ASN1OctetString)attr; - } - } - - String name = new String(Hex.encode(localId.getOctets())); - - if (alias == null) - { - keys.put(name, privKey); - } - else - { - localIds.put(alias, name); - } - } - else - { - System.out.println("extra in encryptedData " + b.getBagId()); - System.out.println(ASN1Dump.dumpAsString(b)); - } - } - } - else - { - System.out.println("extra " + c[i].getContentType().getId()); - System.out.println("extra " + ASN1Dump.dumpAsString(c[i].getContent())); - } - } - } - - certs = new IgnoresCaseHashtable(); - chainCerts = new Hashtable(); - keyCerts = new Hashtable(); - - for (int i = 0; i != chain.size(); i++) - { - SafeBag b = (SafeBag)chain.elementAt(i); - CertBag cb = CertBag.getInstance(b.getBagValue()); - - if (!cb.getCertId().equals(x509Certificate)) - { - throw new RuntimeException("Unsupported certificate type: " + cb.getCertId()); - } - - Certificate cert; - - try - { - ByteArrayInputStream cIn = new ByteArrayInputStream( - ((ASN1OctetString)cb.getCertValue()).getOctets()); - cert = certFact.generateCertificate(cIn); - } - catch (Exception e) - { - throw new RuntimeException(e.toString()); - } - - // - // set the attributes - // - ASN1OctetString localId = null; - String alias = null; - - if (b.getBagAttributes() != null) - { - Enumeration e = b.getBagAttributes().getObjects(); - while (e.hasMoreElements()) - { - ASN1Sequence sq = (ASN1Sequence)e.nextElement(); - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)sq.getObjectAt(0); - ASN1Primitive attr = (ASN1Primitive)((ASN1Set)sq.getObjectAt(1)).getObjectAt(0); - PKCS12BagAttributeCarrier bagAttr = null; - - if (cert instanceof PKCS12BagAttributeCarrier) - { - bagAttr = (PKCS12BagAttributeCarrier)cert; - - ASN1Encodable existing = bagAttr.getBagAttribute(oid); - if (existing != null) - { - // OK, but the value has to be the same - if (!existing.toASN1Primitive().equals(attr)) - { - throw new IOException( - "attempt to add existing attribute with different value"); - } - } - else - { - bagAttr.setBagAttribute(oid, attr); - } - } - - if (oid.equals(pkcs_9_at_friendlyName)) - { - alias = ((DERBMPString)attr).getString(); - } - else if (oid.equals(pkcs_9_at_localKeyId)) - { - localId = (ASN1OctetString)attr; - } - } - } - - chainCerts.put(new CertId(cert.getPublicKey()), cert); - - if (unmarkedKey) - { - if (keyCerts.isEmpty()) - { - String name = new String(Hex.encode(createSubjectKeyId(cert.getPublicKey()).getKeyIdentifier())); - - keyCerts.put(name, cert); - keys.put(name, keys.remove("unmarked")); - } - } - else - { - // - // the local key id needs to override the friendly name - // - if (localId != null) - { - String name = new String(Hex.encode(localId.getOctets())); - - keyCerts.put(name, cert); - } - if (alias != null) - { - certs.put(alias, cert); - } - } - } - } - - public void engineStore(OutputStream stream, char[] password) - throws IOException - { - doStore(stream, password, false); - } - - private void doStore(OutputStream stream, char[] password, boolean useDEREncoding) - throws IOException - { - if (password == null) - { - throw new NullPointerException("No password supplied for PKCS#12 KeyStore."); - } - - // - // handle the key - // - ASN1EncodableVector keyS = new ASN1EncodableVector(); - - - Enumeration ks = keys.keys(); - - while (ks.hasMoreElements()) - { - byte[] kSalt = new byte[SALT_SIZE]; - - random.nextBytes(kSalt); - - String name = (String)ks.nextElement(); - PrivateKey privKey = (PrivateKey)keys.get(name); - PKCS12PBEParams kParams = new PKCS12PBEParams(kSalt, MIN_ITERATIONS); - byte[] kBytes = wrapKey(keyAlgorithm.getId(), privKey, kParams, password); - AlgorithmIdentifier kAlgId = new AlgorithmIdentifier(keyAlgorithm, kParams.toASN1Primitive()); - org.spongycastle.asn1.pkcs.EncryptedPrivateKeyInfo kInfo = new org.spongycastle.asn1.pkcs.EncryptedPrivateKeyInfo(kAlgId, kBytes); - boolean attrSet = false; - ASN1EncodableVector kName = new ASN1EncodableVector(); - - if (privKey instanceof PKCS12BagAttributeCarrier) - { - PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier)privKey; - // - // make sure we are using the local alias on store - // - DERBMPString nm = (DERBMPString)bagAttrs.getBagAttribute(pkcs_9_at_friendlyName); - if (nm == null || !nm.getString().equals(name)) - { - bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name)); - } - - // - // make sure we have a local key-id - // - if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) - { - Certificate ct = engineGetCertificate(name); - - bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(ct.getPublicKey())); - } - - Enumeration e = bagAttrs.getBagAttributeKeys(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - ASN1EncodableVector kSeq = new ASN1EncodableVector(); - - kSeq.add(oid); - kSeq.add(new DERSet(bagAttrs.getBagAttribute(oid))); - - attrSet = true; - - kName.add(new DERSequence(kSeq)); - } - } - - if (!attrSet) - { - // - // set a default friendly name (from the key id) and local id - // - ASN1EncodableVector kSeq = new ASN1EncodableVector(); - Certificate ct = engineGetCertificate(name); - - kSeq.add(pkcs_9_at_localKeyId); - kSeq.add(new DERSet(createSubjectKeyId(ct.getPublicKey()))); - - kName.add(new DERSequence(kSeq)); - - kSeq = new ASN1EncodableVector(); - - kSeq.add(pkcs_9_at_friendlyName); - kSeq.add(new DERSet(new DERBMPString(name))); - - kName.add(new DERSequence(kSeq)); - } - - SafeBag kBag = new SafeBag(pkcs8ShroudedKeyBag, kInfo.toASN1Primitive(), new DERSet(kName)); - keyS.add(kBag); - } - - byte[] keySEncoded = new DERSequence(keyS).getEncoded(ASN1Encoding.DER); - BEROctetString keyString = new BEROctetString(keySEncoded); - - // - // certificate processing - // - byte[] cSalt = new byte[SALT_SIZE]; - - random.nextBytes(cSalt); - - ASN1EncodableVector certSeq = new ASN1EncodableVector(); - PKCS12PBEParams cParams = new PKCS12PBEParams(cSalt, MIN_ITERATIONS); - AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.toASN1Primitive()); - Hashtable doneCerts = new Hashtable(); - - Enumeration cs = keys.keys(); - while (cs.hasMoreElements()) - { - try - { - String name = (String)cs.nextElement(); - Certificate cert = engineGetCertificate(name); - boolean cAttrSet = false; - CertBag cBag = new CertBag( - x509Certificate, - new DEROctetString(cert.getEncoded())); - ASN1EncodableVector fName = new ASN1EncodableVector(); - - if (cert instanceof PKCS12BagAttributeCarrier) - { - PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier)cert; - // - // make sure we are using the local alias on store - // - DERBMPString nm = (DERBMPString)bagAttrs.getBagAttribute(pkcs_9_at_friendlyName); - if (nm == null || !nm.getString().equals(name)) - { - bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name)); - } - - // - // make sure we have a local key-id - // - if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) - { - bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(cert.getPublicKey())); - } - - Enumeration e = bagAttrs.getBagAttributeKeys(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - ASN1EncodableVector fSeq = new ASN1EncodableVector(); - - fSeq.add(oid); - fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid))); - fName.add(new DERSequence(fSeq)); - - cAttrSet = true; - } - } - - if (!cAttrSet) - { - ASN1EncodableVector fSeq = new ASN1EncodableVector(); - - fSeq.add(pkcs_9_at_localKeyId); - fSeq.add(new DERSet(createSubjectKeyId(cert.getPublicKey()))); - fName.add(new DERSequence(fSeq)); - - fSeq = new ASN1EncodableVector(); - - fSeq.add(pkcs_9_at_friendlyName); - fSeq.add(new DERSet(new DERBMPString(name))); - - fName.add(new DERSequence(fSeq)); - } - - SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName)); - - certSeq.add(sBag); - - doneCerts.put(cert, cert); - } - catch (CertificateEncodingException e) - { - throw new IOException("Error encoding certificate: " + e.toString()); - } - } - - cs = certs.keys(); - while (cs.hasMoreElements()) - { - try - { - String certId = (String)cs.nextElement(); - Certificate cert = (Certificate)certs.get(certId); - boolean cAttrSet = false; - - if (keys.get(certId) != null) - { - continue; - } - - CertBag cBag = new CertBag( - x509Certificate, - new DEROctetString(cert.getEncoded())); - ASN1EncodableVector fName = new ASN1EncodableVector(); - - if (cert instanceof PKCS12BagAttributeCarrier) - { - PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier)cert; - // - // make sure we are using the local alias on store - // - DERBMPString nm = (DERBMPString)bagAttrs.getBagAttribute(pkcs_9_at_friendlyName); - if (nm == null || !nm.getString().equals(certId)) - { - bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(certId)); - } - - Enumeration e = bagAttrs.getBagAttributeKeys(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - - // a certificate not immediately linked to a key doesn't require - // a localKeyID and will confuse some PKCS12 implementations. - // - // If we find one, we'll prune it out. - if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) - { - continue; - } - - ASN1EncodableVector fSeq = new ASN1EncodableVector(); - - fSeq.add(oid); - fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid))); - fName.add(new DERSequence(fSeq)); - - cAttrSet = true; - } - } - - if (!cAttrSet) - { - ASN1EncodableVector fSeq = new ASN1EncodableVector(); - - fSeq.add(pkcs_9_at_friendlyName); - fSeq.add(new DERSet(new DERBMPString(certId))); - - fName.add(new DERSequence(fSeq)); - } - - SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName)); - - certSeq.add(sBag); - - doneCerts.put(cert, cert); - } - catch (CertificateEncodingException e) - { - throw new IOException("Error encoding certificate: " + e.toString()); - } - } - - cs = chainCerts.keys(); - while (cs.hasMoreElements()) - { - try - { - CertId certId = (CertId)cs.nextElement(); - Certificate cert = (Certificate)chainCerts.get(certId); - - if (doneCerts.get(cert) != null) - { - continue; - } - - CertBag cBag = new CertBag( - x509Certificate, - new DEROctetString(cert.getEncoded())); - ASN1EncodableVector fName = new ASN1EncodableVector(); - - if (cert instanceof PKCS12BagAttributeCarrier) - { - PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier)cert; - Enumeration e = bagAttrs.getBagAttributeKeys(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - - // a certificate not immediately linked to a key doesn't require - // a localKeyID and will confuse some PKCS12 implementations. - // - // If we find one, we'll prune it out. - if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) - { - continue; - } - - ASN1EncodableVector fSeq = new ASN1EncodableVector(); - - fSeq.add(oid); - fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid))); - fName.add(new DERSequence(fSeq)); - } - } - - SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName)); - - certSeq.add(sBag); - } - catch (CertificateEncodingException e) - { - throw new IOException("Error encoding certificate: " + e.toString()); - } - } - - byte[] certSeqEncoded = new DERSequence(certSeq).getEncoded(ASN1Encoding.DER); - byte[] certBytes = cryptData(true, cAlgId, password, false, certSeqEncoded); - EncryptedData cInfo = new EncryptedData(data, cAlgId, new BEROctetString(certBytes)); - - ContentInfo[] info = new ContentInfo[] - { - new ContentInfo(data, keyString), - new ContentInfo(encryptedData, cInfo.toASN1Primitive()) - }; - - AuthenticatedSafe auth = new AuthenticatedSafe(info); - - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - DEROutputStream asn1Out; - if (useDEREncoding) - { - asn1Out = new DEROutputStream(bOut); - } - else - { - asn1Out = new BEROutputStream(bOut); - } - - asn1Out.writeObject(auth); - - byte[] pkg = bOut.toByteArray(); - - ContentInfo mainInfo = new ContentInfo(data, new BEROctetString(pkg)); - - // - // create the mac - // - byte[] mSalt = new byte[20]; - int itCount = MIN_ITERATIONS; - - random.nextBytes(mSalt); - - byte[] data = ((ASN1OctetString)mainInfo.getContent()).getOctets(); - - MacData mData; - - try - { - byte[] res = calculatePbeMac(id_SHA1, mSalt, itCount, password, false, data); - - AlgorithmIdentifier algId = new AlgorithmIdentifier(id_SHA1, DERNull.INSTANCE); - DigestInfo dInfo = new DigestInfo(algId, res); - - mData = new MacData(dInfo, mSalt, itCount); - } - catch (Exception e) - { - throw new IOException("error constructing MAC: " + e.toString()); - } - - // - // output the Pfx - // - Pfx pfx = new Pfx(mainInfo, mData); - - if (useDEREncoding) - { - asn1Out = new DEROutputStream(stream); - } - else - { - asn1Out = new BEROutputStream(stream); - } - - asn1Out.writeObject(pfx); - } - - private static byte[] calculatePbeMac( - ASN1ObjectIdentifier oid, - byte[] salt, - int itCount, - char[] password, - boolean wrongPkcs12Zero, - byte[] data) - throws Exception - { - SecretKeyFactory keyFact = SecretKeyFactory.getInstance(oid.getId(), bcProvider); - PBEParameterSpec defParams = new PBEParameterSpec(salt, itCount); - PBEKeySpec pbeSpec = new PBEKeySpec(password); - BCPBEKey key = (BCPBEKey)keyFact.generateSecret(pbeSpec); - key.setTryWrongPKCS12Zero(wrongPkcs12Zero); - - Mac mac = Mac.getInstance(oid.getId(), bcProvider); - mac.init(key, defParams); - mac.update(data); - return mac.doFinal(); - } - - public static class BCPKCS12KeyStore - extends PKCS12KeyStoreSpi - { - public BCPKCS12KeyStore() - { - super(bcProvider, pbeWithSHAAnd3_KeyTripleDES_CBC, pbeWithSHAAnd40BitRC2_CBC); - } - } - - public static class BCPKCS12KeyStore3DES - extends PKCS12KeyStoreSpi - { - public BCPKCS12KeyStore3DES() - { - super(bcProvider, pbeWithSHAAnd3_KeyTripleDES_CBC, pbeWithSHAAnd3_KeyTripleDES_CBC); - } - } - - public static class DefPKCS12KeyStore - extends PKCS12KeyStoreSpi - { - public DefPKCS12KeyStore() - { - super(null, pbeWithSHAAnd3_KeyTripleDES_CBC, pbeWithSHAAnd40BitRC2_CBC); - } - } - - public static class DefPKCS12KeyStore3DES - extends PKCS12KeyStoreSpi - { - public DefPKCS12KeyStore3DES() - { - super(null, pbeWithSHAAnd3_KeyTripleDES_CBC, pbeWithSHAAnd3_KeyTripleDES_CBC); - } - } - - private static class IgnoresCaseHashtable - { - private Hashtable orig = new Hashtable(); - private Hashtable keys = new Hashtable(); - - public void put(String key, Object value) - { - String lower = (key == null) ? null : Strings.toLowerCase(key); - String k = (String)keys.get(lower); - if (k != null) - { - orig.remove(k); - } - - keys.put(lower, key); - orig.put(key, value); - } - - public Enumeration keys() - { - return orig.keys(); - } - - public Object remove(String alias) - { - String k = (String)keys.remove(alias == null ? null : Strings.toLowerCase(alias)); - if (k == null) - { - return null; - } - - return orig.remove(k); - } - - public Object get(String alias) - { - String k = (String)keys.get(alias == null ? null : Strings.toLowerCase(alias)); - if (k == null) - { - return null; - } - - return orig.get(k); - } - - public Enumeration elements() - { - return orig.elements(); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/symmetric/util/BaseBlockCipher.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/symmetric/util/BaseBlockCipher.java deleted file mode 100644 index d188bf696..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/symmetric/util/BaseBlockCipher.java +++ /dev/null @@ -1,1031 +0,0 @@ -package org.spongycastle.jcajce.provider.symmetric.util; - -import java.lang.reflect.Method; -import java.security.AlgorithmParameters; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.InvalidParameterException; -import java.security.Key; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.security.spec.AlgorithmParameterSpec; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; -import javax.crypto.ShortBufferException; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.PBEParameterSpec; -import javax.crypto.spec.RC2ParameterSpec; -import javax.crypto.spec.RC5ParameterSpec; - -import org.spongycastle.asn1.cms.GCMParameters; -import org.spongycastle.crypto.BlockCipher; -import org.spongycastle.crypto.BufferedBlockCipher; -import org.spongycastle.crypto.CipherParameters; -import org.spongycastle.crypto.DataLengthException; -import org.spongycastle.crypto.InvalidCipherTextException; -import org.spongycastle.crypto.OutputLengthException; -import org.spongycastle.crypto.modes.AEADBlockCipher; -import org.spongycastle.crypto.modes.CBCBlockCipher; -import org.spongycastle.crypto.modes.CCMBlockCipher; -import org.spongycastle.crypto.modes.CFBBlockCipher; -import org.spongycastle.crypto.modes.CTSBlockCipher; -import org.spongycastle.crypto.modes.EAXBlockCipher; -import org.spongycastle.crypto.modes.GCFBBlockCipher; -import org.spongycastle.crypto.modes.GCMBlockCipher; -import org.spongycastle.crypto.modes.GOFBBlockCipher; -import org.spongycastle.crypto.modes.OCBBlockCipher; -import org.spongycastle.crypto.modes.OFBBlockCipher; -import org.spongycastle.crypto.modes.OpenPGPCFBBlockCipher; -import org.spongycastle.crypto.modes.PGPCFBBlockCipher; -import org.spongycastle.crypto.modes.SICBlockCipher; -import org.spongycastle.crypto.paddings.BlockCipherPadding; -import org.spongycastle.crypto.paddings.ISO10126d2Padding; -import org.spongycastle.crypto.paddings.ISO7816d4Padding; -import org.spongycastle.crypto.paddings.PaddedBufferedBlockCipher; -import org.spongycastle.crypto.paddings.TBCPadding; -import org.spongycastle.crypto.paddings.X923Padding; -import org.spongycastle.crypto.paddings.ZeroBytePadding; -import org.spongycastle.crypto.params.AEADParameters; -import org.spongycastle.crypto.params.KeyParameter; -import org.spongycastle.crypto.params.ParametersWithIV; -import org.spongycastle.crypto.params.ParametersWithRandom; -import org.spongycastle.crypto.params.ParametersWithSBox; -import org.spongycastle.crypto.params.RC2Parameters; -import org.spongycastle.crypto.params.RC5Parameters; -import org.spongycastle.jcajce.spec.GOST28147ParameterSpec; -import org.spongycastle.jcajce.spec.RepeatedSecretKeySpec; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.util.Strings; - -public class BaseBlockCipher - extends BaseWrapCipher - implements PBE -{ - private static final Class gcmSpecClass = lookup("javax.crypto.spec.GCMParameterSpec"); - - // - // specs we can handle. - // - private Class[] availableSpecs = - { - RC2ParameterSpec.class, - RC5ParameterSpec.class, - IvParameterSpec.class, - PBEParameterSpec.class, - GOST28147ParameterSpec.class, - gcmSpecClass - }; - - private BlockCipher baseEngine; - private BlockCipherProvider engineProvider; - private GenericBlockCipher cipher; - private ParametersWithIV ivParam; - private AEADParameters aeadParams; - - private int ivLength = 0; - - private boolean padded; - - private PBEParameterSpec pbeSpec = null; - private String pbeAlgorithm = null; - - private String modeName = null; - - private static Class lookup(String className) - { - try - { - Class def = BaseBlockCipher.class.getClassLoader().loadClass(className); - - return def; - } - catch (Exception e) - { - return null; - } - } - - protected BaseBlockCipher( - BlockCipher engine) - { - baseEngine = engine; - - cipher = new BufferedGenericBlockCipher(engine); - } - - protected BaseBlockCipher( - BlockCipherProvider provider) - { - baseEngine = provider.get(); - engineProvider = provider; - - cipher = new BufferedGenericBlockCipher(provider.get()); - } - - protected BaseBlockCipher( - AEADBlockCipher engine) - { - baseEngine = engine.getUnderlyingCipher(); - ivLength = baseEngine.getBlockSize(); - cipher = new AEADGenericBlockCipher(engine); - } - - protected BaseBlockCipher( - org.spongycastle.crypto.BlockCipher engine, - int ivLength) - { - baseEngine = engine; - - this.cipher = new BufferedGenericBlockCipher(engine); - this.ivLength = ivLength / 8; - } - - protected BaseBlockCipher( - BufferedBlockCipher engine, - int ivLength) - { - baseEngine = engine.getUnderlyingCipher(); - - this.cipher = new BufferedGenericBlockCipher(engine); - this.ivLength = ivLength / 8; - } - - protected int engineGetBlockSize() - { - return baseEngine.getBlockSize(); - } - - protected byte[] engineGetIV() - { - return (ivParam != null) ? ivParam.getIV() : null; - } - - protected int engineGetKeySize( - Key key) - { - return key.getEncoded().length * 8; - } - - protected int engineGetOutputSize( - int inputLen) - { - return cipher.getOutputSize(inputLen); - } - - protected AlgorithmParameters engineGetParameters() - { - if (engineParams == null) - { - if (pbeSpec != null) - { - try - { - engineParams = AlgorithmParameters.getInstance(pbeAlgorithm, BouncyCastleProvider.PROVIDER_NAME); - engineParams.init(pbeSpec); - } - catch (Exception e) - { - return null; - } - } - else if (ivParam != null) - { - String name = cipher.getUnderlyingCipher().getAlgorithmName(); - - if (name.indexOf('/') >= 0) - { - name = name.substring(0, name.indexOf('/')); - } - - try - { - engineParams = AlgorithmParameters.getInstance(name, BouncyCastleProvider.PROVIDER_NAME); - engineParams.init(ivParam.getIV()); - } - catch (Exception e) - { - throw new RuntimeException(e.toString()); - } - } - else if (aeadParams != null) - { - try - { - engineParams = AlgorithmParameters.getInstance("GCM", BouncyCastleProvider.PROVIDER_NAME); - engineParams.init(new GCMParameters(aeadParams.getNonce(), aeadParams.getMacSize()).getEncoded()); - } - catch (Exception e) - { - throw new RuntimeException(e.toString()); - } - } - } - - return engineParams; - } - - protected void engineSetMode( - String mode) - throws NoSuchAlgorithmException - { - modeName = Strings.toUpperCase(mode); - - if (modeName.equals("ECB")) - { - ivLength = 0; - cipher = new BufferedGenericBlockCipher(baseEngine); - } - else if (modeName.equals("CBC")) - { - ivLength = baseEngine.getBlockSize(); - cipher = new BufferedGenericBlockCipher( - new CBCBlockCipher(baseEngine)); - } - else if (modeName.startsWith("OFB")) - { - ivLength = baseEngine.getBlockSize(); - if (modeName.length() != 3) - { - int wordSize = Integer.parseInt(modeName.substring(3)); - - cipher = new BufferedGenericBlockCipher( - new OFBBlockCipher(baseEngine, wordSize)); - } - else - { - cipher = new BufferedGenericBlockCipher( - new OFBBlockCipher(baseEngine, 8 * baseEngine.getBlockSize())); - } - } - else if (modeName.startsWith("CFB")) - { - ivLength = baseEngine.getBlockSize(); - if (modeName.length() != 3) - { - int wordSize = Integer.parseInt(modeName.substring(3)); - - cipher = new BufferedGenericBlockCipher( - new CFBBlockCipher(baseEngine, wordSize)); - } - else - { - cipher = new BufferedGenericBlockCipher( - new CFBBlockCipher(baseEngine, 8 * baseEngine.getBlockSize())); - } - } - else if (modeName.startsWith("PGP")) - { - boolean inlineIV = modeName.equalsIgnoreCase("PGPCFBwithIV"); - - ivLength = baseEngine.getBlockSize(); - cipher = new BufferedGenericBlockCipher( - new PGPCFBBlockCipher(baseEngine, inlineIV)); - } - else if (modeName.equalsIgnoreCase("OpenPGPCFB")) - { - ivLength = 0; - cipher = new BufferedGenericBlockCipher( - new OpenPGPCFBBlockCipher(baseEngine)); - } - else if (modeName.startsWith("SIC")) - { - ivLength = baseEngine.getBlockSize(); - if (ivLength < 16) - { - throw new IllegalArgumentException("Warning: SIC-Mode can become a twotime-pad if the blocksize of the cipher is too small. Use a cipher with a block size of at least 128 bits (e.g. AES)"); - } - cipher = new BufferedGenericBlockCipher(new BufferedBlockCipher( - new SICBlockCipher(baseEngine))); - } - else if (modeName.startsWith("CTR")) - { - ivLength = baseEngine.getBlockSize(); - cipher = new BufferedGenericBlockCipher(new BufferedBlockCipher( - new SICBlockCipher(baseEngine))); - } - else if (modeName.startsWith("GOFB")) - { - ivLength = baseEngine.getBlockSize(); - cipher = new BufferedGenericBlockCipher(new BufferedBlockCipher( - new GOFBBlockCipher(baseEngine))); - } - else if (modeName.startsWith("GCFB")) - { - ivLength = baseEngine.getBlockSize(); - cipher = new BufferedGenericBlockCipher(new BufferedBlockCipher( - new GCFBBlockCipher(baseEngine))); - } - else if (modeName.startsWith("CTS")) - { - ivLength = baseEngine.getBlockSize(); - cipher = new BufferedGenericBlockCipher(new CTSBlockCipher(new CBCBlockCipher(baseEngine))); - } - else if (modeName.startsWith("CCM")) - { - ivLength = 13; // CCM nonce 7..13 bytes - cipher = new AEADGenericBlockCipher(new CCMBlockCipher(baseEngine)); - } - else if (modeName.startsWith("OCB")) - { - if (engineProvider != null) - { - /* - * RFC 7253 4.2. Nonce is a string of no more than 120 bits - */ - ivLength = 15; - cipher = new AEADGenericBlockCipher(new OCBBlockCipher(baseEngine, engineProvider.get())); - } - else - { - throw new NoSuchAlgorithmException("can't support mode " + mode); - } - } - else if (modeName.startsWith("EAX")) - { - ivLength = baseEngine.getBlockSize(); - cipher = new AEADGenericBlockCipher(new EAXBlockCipher(baseEngine)); - } - else if (modeName.startsWith("GCM")) - { - ivLength = baseEngine.getBlockSize(); - cipher = new AEADGenericBlockCipher(new GCMBlockCipher(baseEngine)); - } - else - { - throw new NoSuchAlgorithmException("can't support mode " + mode); - } - } - - protected void engineSetPadding( - String padding) - throws NoSuchPaddingException - { - String paddingName = Strings.toUpperCase(padding); - - if (paddingName.equals("NOPADDING")) - { - if (cipher.wrapOnNoPadding()) - { - cipher = new BufferedGenericBlockCipher(new BufferedBlockCipher(cipher.getUnderlyingCipher())); - } - } - else if (paddingName.equals("WITHCTS")) - { - cipher = new BufferedGenericBlockCipher(new CTSBlockCipher(cipher.getUnderlyingCipher())); - } - else - { - padded = true; - - if (isAEADModeName(modeName)) - { - throw new NoSuchPaddingException("Only NoPadding can be used with AEAD modes."); - } - else if (paddingName.equals("PKCS5PADDING") || paddingName.equals("PKCS7PADDING")) - { - cipher = new BufferedGenericBlockCipher(cipher.getUnderlyingCipher()); - } - else if (paddingName.equals("ZEROBYTEPADDING")) - { - cipher = new BufferedGenericBlockCipher(cipher.getUnderlyingCipher(), new ZeroBytePadding()); - } - else if (paddingName.equals("ISO10126PADDING") || paddingName.equals("ISO10126-2PADDING")) - { - cipher = new BufferedGenericBlockCipher(cipher.getUnderlyingCipher(), new ISO10126d2Padding()); - } - else if (paddingName.equals("X9.23PADDING") || paddingName.equals("X923PADDING")) - { - cipher = new BufferedGenericBlockCipher(cipher.getUnderlyingCipher(), new X923Padding()); - } - else if (paddingName.equals("ISO7816-4PADDING") || paddingName.equals("ISO9797-1PADDING")) - { - cipher = new BufferedGenericBlockCipher(cipher.getUnderlyingCipher(), new ISO7816d4Padding()); - } - else if (paddingName.equals("TBCPADDING")) - { - cipher = new BufferedGenericBlockCipher(cipher.getUnderlyingCipher(), new TBCPadding()); - } - else - { - throw new NoSuchPaddingException("Padding " + padding + " unknown."); - } - } - } - - protected void engineInit( - int opmode, - Key key, - AlgorithmParameterSpec params, - SecureRandom random) - throws InvalidKeyException, InvalidAlgorithmParameterException - { - CipherParameters param; - - this.pbeSpec = null; - this.pbeAlgorithm = null; - this.engineParams = null; - this.aeadParams = null; - - // - // basic key check - // - if (!(key instanceof SecretKey)) - { - throw new InvalidKeyException("Key for algorithm " + key.getAlgorithm() + " not suitable for symmetric enryption."); - } - - // - // for RC5-64 we must have some default parameters - // - if (params == null && baseEngine.getAlgorithmName().startsWith("RC5-64")) - { - throw new InvalidAlgorithmParameterException("RC5 requires an RC5ParametersSpec to be passed in."); - } - - // - // a note on iv's - if ivLength is zero the IV gets ignored (we don't use it). - // - if (key instanceof BCPBEKey) - { - BCPBEKey k = (BCPBEKey)key; - - if (k.getOID() != null) - { - pbeAlgorithm = k.getOID().getId(); - } - else - { - pbeAlgorithm = k.getAlgorithm(); - } - - if (k.getParam() != null) - { - param = k.getParam(); - if (params instanceof IvParameterSpec) - { - IvParameterSpec iv = (IvParameterSpec)params; - - param = new ParametersWithIV(param, iv.getIV()); - } - else if (params instanceof GOST28147ParameterSpec) - { - // need to pick up IV and SBox. - GOST28147ParameterSpec gost28147Param = (GOST28147ParameterSpec)params; - - param = new ParametersWithSBox(param, gost28147Param.getSbox()); - - if (gost28147Param.getIV() != null && ivLength != 0) - { - param = new ParametersWithIV(param, gost28147Param.getIV()); - } - } - } - else if (params instanceof PBEParameterSpec) - { - pbeSpec = (PBEParameterSpec)params; - param = PBE.Util.makePBEParameters(k, params, cipher.getUnderlyingCipher().getAlgorithmName()); - } - else - { - throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set."); - } - - if (param instanceof ParametersWithIV) - { - ivParam = (ParametersWithIV)param; - } - } - else if (params == null) - { - param = new KeyParameter(key.getEncoded()); - } - else if (params instanceof IvParameterSpec) - { - if (ivLength != 0) - { - IvParameterSpec p = (IvParameterSpec)params; - - if (p.getIV().length != ivLength && !isAEADModeName(modeName)) - { - throw new InvalidAlgorithmParameterException("IV must be " + ivLength + " bytes long."); - } - - if (key instanceof RepeatedSecretKeySpec) - { - param = new ParametersWithIV(null, p.getIV()); - ivParam = (ParametersWithIV)param; - } - else - { - param = new ParametersWithIV(new KeyParameter(key.getEncoded()), p.getIV()); - ivParam = (ParametersWithIV)param; - } - } - else - { - if (modeName != null && modeName.equals("ECB")) - { - throw new InvalidAlgorithmParameterException("ECB mode does not use an IV"); - } - - param = new KeyParameter(key.getEncoded()); - } - } - else if (params instanceof GOST28147ParameterSpec) - { - GOST28147ParameterSpec gost28147Param = (GOST28147ParameterSpec)params; - - param = new ParametersWithSBox( - new KeyParameter(key.getEncoded()), ((GOST28147ParameterSpec)params).getSbox()); - - if (gost28147Param.getIV() != null && ivLength != 0) - { - param = new ParametersWithIV(param, gost28147Param.getIV()); - ivParam = (ParametersWithIV)param; - } - } - else if (params instanceof RC2ParameterSpec) - { - RC2ParameterSpec rc2Param = (RC2ParameterSpec)params; - - param = new RC2Parameters(key.getEncoded(), ((RC2ParameterSpec)params).getEffectiveKeyBits()); - - if (rc2Param.getIV() != null && ivLength != 0) - { - param = new ParametersWithIV(param, rc2Param.getIV()); - ivParam = (ParametersWithIV)param; - } - } - else if (params instanceof RC5ParameterSpec) - { - RC5ParameterSpec rc5Param = (RC5ParameterSpec)params; - - param = new RC5Parameters(key.getEncoded(), ((RC5ParameterSpec)params).getRounds()); - if (baseEngine.getAlgorithmName().startsWith("RC5")) - { - if (baseEngine.getAlgorithmName().equals("RC5-32")) - { - if (rc5Param.getWordSize() != 32) - { - throw new InvalidAlgorithmParameterException("RC5 already set up for a word size of 32 not " + rc5Param.getWordSize() + "."); - } - } - else if (baseEngine.getAlgorithmName().equals("RC5-64")) - { - if (rc5Param.getWordSize() != 64) - { - throw new InvalidAlgorithmParameterException("RC5 already set up for a word size of 64 not " + rc5Param.getWordSize() + "."); - } - } - } - else - { - throw new InvalidAlgorithmParameterException("RC5 parameters passed to a cipher that is not RC5."); - } - if ((rc5Param.getIV() != null) && (ivLength != 0)) - { - param = new ParametersWithIV(param, rc5Param.getIV()); - ivParam = (ParametersWithIV)param; - } - } - else if (gcmSpecClass != null && gcmSpecClass.isInstance(params)) - { - if (!isAEADModeName(modeName) && !(cipher instanceof AEADGenericBlockCipher)) - { - throw new InvalidAlgorithmParameterException("GCMParameterSpec can only be used with AEAD modes."); - } - - try - { - Method tLen = gcmSpecClass.getDeclaredMethod("getTLen", new Class[0]); - Method iv= gcmSpecClass.getDeclaredMethod("getIV", new Class[0]); - - if (key instanceof RepeatedSecretKeySpec) - { - param = aeadParams = new AEADParameters(null, ((Integer)tLen.invoke(params, new Object[0])).intValue(), (byte[])iv.invoke(params, new Object[0])); - } - else - { - param = aeadParams = new AEADParameters(new KeyParameter(key.getEncoded()), ((Integer)tLen.invoke(params, new Object[0])).intValue(), (byte[])iv.invoke(params, new Object[0])); - } - } - catch (Exception e) - { - throw new InvalidAlgorithmParameterException("Cannot process GCMParameterSpec."); - } - } - else - { - throw new InvalidAlgorithmParameterException("unknown parameter type."); - } - - if ((ivLength != 0) && !(param instanceof ParametersWithIV) && !(param instanceof AEADParameters)) - { - SecureRandom ivRandom = random; - - if (ivRandom == null) - { - ivRandom = new SecureRandom(); - } - - if ((opmode == Cipher.ENCRYPT_MODE) || (opmode == Cipher.WRAP_MODE)) - { - byte[] iv = new byte[ivLength]; - - ivRandom.nextBytes(iv); - param = new ParametersWithIV(param, iv); - ivParam = (ParametersWithIV)param; - } - else if (cipher.getUnderlyingCipher().getAlgorithmName().indexOf("PGPCFB") < 0) - { - throw new InvalidAlgorithmParameterException("no IV set when one expected"); - } - } - - if (random != null && padded) - { - param = new ParametersWithRandom(param, random); - } - - try - { - switch (opmode) - { - case Cipher.ENCRYPT_MODE: - case Cipher.WRAP_MODE: - cipher.init(true, param); - break; - case Cipher.DECRYPT_MODE: - case Cipher.UNWRAP_MODE: - cipher.init(false, param); - break; - default: - throw new InvalidParameterException("unknown opmode " + opmode + " passed"); - } - } - catch (Exception e) - { - throw new InvalidKeyException(e.getMessage()); - } - } - - protected void engineInit( - int opmode, - Key key, - AlgorithmParameters params, - SecureRandom random) - throws InvalidKeyException, InvalidAlgorithmParameterException - { - AlgorithmParameterSpec paramSpec = null; - - if (params != null) - { - for (int i = 0; i != availableSpecs.length; i++) - { - if (availableSpecs[i] == null) - { - continue; - } - - try - { - paramSpec = params.getParameterSpec(availableSpecs[i]); - break; - } - catch (Exception e) - { - // try again if possible - } - } - - if (paramSpec == null) - { - throw new InvalidAlgorithmParameterException("can't handle parameter " + params.toString()); - } - } - - engineInit(opmode, key, paramSpec, random); - - engineParams = params; - } - - protected void engineInit( - int opmode, - Key key, - SecureRandom random) - throws InvalidKeyException - { - try - { - engineInit(opmode, key, (AlgorithmParameterSpec)null, random); - } - catch (InvalidAlgorithmParameterException e) - { - throw new InvalidKeyException(e.getMessage()); - } - } - - protected void engineUpdateAAD(byte[] input, int offset, int length) - { - cipher.updateAAD(input, offset, length); - } - - protected byte[] engineUpdate( - byte[] input, - int inputOffset, - int inputLen) - { - int length = cipher.getUpdateOutputSize(inputLen); - - if (length > 0) - { - byte[] out = new byte[length]; - - int len = cipher.processBytes(input, inputOffset, inputLen, out, 0); - - if (len == 0) - { - return null; - } - else if (len != out.length) - { - byte[] tmp = new byte[len]; - - System.arraycopy(out, 0, tmp, 0, len); - - return tmp; - } - - return out; - } - - cipher.processBytes(input, inputOffset, inputLen, null, 0); - - return null; - } - - protected int engineUpdate( - byte[] input, - int inputOffset, - int inputLen, - byte[] output, - int outputOffset) - throws ShortBufferException - { - try - { - return cipher.processBytes(input, inputOffset, inputLen, output, outputOffset); - } - catch (DataLengthException e) - { - throw new ShortBufferException(e.getMessage()); - } - } - - protected byte[] engineDoFinal( - byte[] input, - int inputOffset, - int inputLen) - throws IllegalBlockSizeException, BadPaddingException - { - int len = 0; - byte[] tmp = new byte[engineGetOutputSize(inputLen)]; - - if (inputLen != 0) - { - len = cipher.processBytes(input, inputOffset, inputLen, tmp, 0); - } - - try - { - len += cipher.doFinal(tmp, len); - } - catch (DataLengthException e) - { - throw new IllegalBlockSizeException(e.getMessage()); - } - catch (InvalidCipherTextException e) - { - throw new BadPaddingException(e.getMessage()); - } - - if (len == tmp.length) - { - return tmp; - } - - byte[] out = new byte[len]; - - System.arraycopy(tmp, 0, out, 0, len); - - return out; - } - - protected int engineDoFinal( - byte[] input, - int inputOffset, - int inputLen, - byte[] output, - int outputOffset) - throws IllegalBlockSizeException, BadPaddingException, ShortBufferException - { - try - { - int len = 0; - - if (inputLen != 0) - { - len = cipher.processBytes(input, inputOffset, inputLen, output, outputOffset); - } - - return (len + cipher.doFinal(output, outputOffset + len)); - } - catch (OutputLengthException e) - { - throw new ShortBufferException(e.getMessage()); - } - catch (DataLengthException e) - { - throw new IllegalBlockSizeException(e.getMessage()); - } - catch (InvalidCipherTextException e) - { - throw new BadPaddingException(e.getMessage()); - } - } - - private boolean isAEADModeName( - String modeName) - { - return "CCM".equals(modeName) || "EAX".equals(modeName) || "GCM".equals(modeName) || "OCB".equals(modeName); - } - - /* - * The ciphers that inherit from us. - */ - - static private interface GenericBlockCipher - { - public void init(boolean forEncryption, CipherParameters params) - throws IllegalArgumentException; - - public boolean wrapOnNoPadding(); - - public String getAlgorithmName(); - - public org.spongycastle.crypto.BlockCipher getUnderlyingCipher(); - - public int getOutputSize(int len); - - public int getUpdateOutputSize(int len); - - public void updateAAD(byte[] input, int offset, int length); - - public int processByte(byte in, byte[] out, int outOff) - throws DataLengthException; - - public int processBytes(byte[] in, int inOff, int len, byte[] out, int outOff) - throws DataLengthException; - - public int doFinal(byte[] out, int outOff) - throws IllegalStateException, InvalidCipherTextException; - } - - private static class BufferedGenericBlockCipher - implements GenericBlockCipher - { - private BufferedBlockCipher cipher; - - BufferedGenericBlockCipher(BufferedBlockCipher cipher) - { - this.cipher = cipher; - } - - BufferedGenericBlockCipher(org.spongycastle.crypto.BlockCipher cipher) - { - this.cipher = new PaddedBufferedBlockCipher(cipher); - } - - BufferedGenericBlockCipher(org.spongycastle.crypto.BlockCipher cipher, BlockCipherPadding padding) - { - this.cipher = new PaddedBufferedBlockCipher(cipher, padding); - } - - public void init(boolean forEncryption, CipherParameters params) - throws IllegalArgumentException - { - cipher.init(forEncryption, params); - } - - public boolean wrapOnNoPadding() - { - return !(cipher instanceof CTSBlockCipher); - } - - public String getAlgorithmName() - { - return cipher.getUnderlyingCipher().getAlgorithmName(); - } - - public org.spongycastle.crypto.BlockCipher getUnderlyingCipher() - { - return cipher.getUnderlyingCipher(); - } - - public int getOutputSize(int len) - { - return cipher.getOutputSize(len); - } - - public int getUpdateOutputSize(int len) - { - return cipher.getUpdateOutputSize(len); - } - - public void updateAAD(byte[] input, int offset, int length) - { - throw new UnsupportedOperationException("AAD is not supported in the current mode."); - } - - public int processByte(byte in, byte[] out, int outOff) throws DataLengthException - { - return cipher.processByte(in, out, outOff); - } - - public int processBytes(byte[] in, int inOff, int len, byte[] out, int outOff) throws DataLengthException - { - return cipher.processBytes(in, inOff, len, out, outOff); - } - - public int doFinal(byte[] out, int outOff) throws IllegalStateException, InvalidCipherTextException - { - return cipher.doFinal(out, outOff); - } - } - - private static class AEADGenericBlockCipher - implements GenericBlockCipher - { - private AEADBlockCipher cipher; - - AEADGenericBlockCipher(AEADBlockCipher cipher) - { - this.cipher = cipher; - } - - public void init(boolean forEncryption, CipherParameters params) - throws IllegalArgumentException - { - cipher.init(forEncryption, params); - } - - public String getAlgorithmName() - { - return cipher.getUnderlyingCipher().getAlgorithmName(); - } - - public boolean wrapOnNoPadding() - { - return false; - } - - public org.spongycastle.crypto.BlockCipher getUnderlyingCipher() - { - return cipher.getUnderlyingCipher(); - } - - public int getOutputSize(int len) - { - return cipher.getOutputSize(len); - } - - public int getUpdateOutputSize(int len) - { - return cipher.getUpdateOutputSize(len); - } - - public void updateAAD(byte[] input, int offset, int length) - { - cipher.processAADBytes(input, offset, length); - } - - public int processByte(byte in, byte[] out, int outOff) throws DataLengthException - { - return cipher.processByte(in, out, outOff); - } - - public int processBytes(byte[] in, int inOff, int len, byte[] out, int outOff) throws DataLengthException - { - return cipher.processBytes(in, inOff, len, out, outOff); - } - - public int doFinal(byte[] out, int outOff) throws IllegalStateException, InvalidCipherTextException - { - return cipher.doFinal(out, outOff); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/util/ProviderJcaJceHelper.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/util/ProviderJcaJceHelper.java deleted file mode 100644 index 5f211dbe2..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jcajce/util/ProviderJcaJceHelper.java +++ /dev/null @@ -1,106 +0,0 @@ -package org.spongycastle.jcajce.util; - -import java.security.AlgorithmParameterGenerator; -import java.security.AlgorithmParameters; -import java.security.KeyFactory; -import java.security.KeyPairGenerator; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.Signature; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; - -import javax.crypto.Cipher; -import javax.crypto.KeyAgreement; -import javax.crypto.KeyGenerator; -import javax.crypto.Mac; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKeyFactory; - -import org.spongycastle.jcajce.util.JcaJceHelper; - -public class ProviderJcaJceHelper - implements JcaJceHelper -{ - protected final Provider provider; - - public ProviderJcaJceHelper(Provider provider) - { - this.provider = provider; - } - - public Cipher createCipher( - String algorithm) - throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException - { - return Cipher.getInstance(algorithm, provider.getName()); - } - - public Mac createMac(String algorithm) - throws NoSuchAlgorithmException, NoSuchProviderException - { - return Mac.getInstance(algorithm, provider.getName()); - } - - public KeyAgreement createKeyAgreement(String algorithm) - throws NoSuchAlgorithmException, NoSuchProviderException - { - return KeyAgreement.getInstance(algorithm, provider.getName()); - } - - public AlgorithmParameterGenerator createAlgorithmParameterGenerator(String algorithm) - throws NoSuchAlgorithmException, NoSuchProviderException - { - return AlgorithmParameterGenerator.getInstance(algorithm, provider.getName()); - } - - public AlgorithmParameters createAlgorithmParameters(String algorithm) - throws NoSuchAlgorithmException, NoSuchProviderException - { - return AlgorithmParameters.getInstance(algorithm, provider.getName()); - } - - public KeyGenerator createKeyGenerator(String algorithm) - throws NoSuchAlgorithmException, NoSuchProviderException - { - return KeyGenerator.getInstance(algorithm, provider.getName()); - } - - public KeyFactory createKeyFactory(String algorithm) - throws NoSuchAlgorithmException, NoSuchProviderException - { - return KeyFactory.getInstance(algorithm, provider.getName()); - } - - public SecretKeyFactory createSecretKeyFactory(String algorithm) - throws NoSuchAlgorithmException, NoSuchProviderException - { - return SecretKeyFactory.getInstance(algorithm, provider.getName()); - } - - public KeyPairGenerator createKeyPairGenerator(String algorithm) - throws NoSuchAlgorithmException, NoSuchProviderException - { - return KeyPairGenerator.getInstance(algorithm, provider.getName()); - } - - public MessageDigest createDigest(String algorithm) - throws NoSuchAlgorithmException, NoSuchProviderException - { - return MessageDigest.getInstance(algorithm, provider.getName()); - } - - public Signature createSignature(String algorithm) - throws NoSuchAlgorithmException, NoSuchProviderException - { - return Signature.getInstance(algorithm, provider.getName()); - } - - public CertificateFactory createCertificateFactory(String algorithm) - throws NoSuchAlgorithmException, CertificateException, NoSuchProviderException - { - return CertificateFactory.getInstance(algorithm, provider.getName()); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/ECKeyUtil.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/ECKeyUtil.java deleted file mode 100644 index c2343e109..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/ECKeyUtil.java +++ /dev/null @@ -1,229 +0,0 @@ -package org.spongycastle.jce; - -import java.io.UnsupportedEncodingException; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.PublicKey; -import java.security.Security; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.spongycastle.asn1.pkcs.PrivateKeyInfo; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x9.X962Parameters; -import org.spongycastle.asn1.x9.X9ECParameters; -import org.spongycastle.asn1.x9.X9ObjectIdentifiers; -import org.spongycastle.jcajce.provider.asymmetric.util.ECUtil; -import org.spongycastle.jce.provider.BouncyCastleProvider; - -/** - * Utility class to allow conversion of EC key parameters to explicit from named - * curves and back (where possible). - */ -public class ECKeyUtil -{ - /** - * Convert a passed in public EC key to have explicit parameters. If the key - * is already using explicit parameters it is returned. - * - * @param key key to be converted - * @param providerName provider name to be used. - * @return the equivalent key with explicit curve parameters - * @throws IllegalArgumentException - * @throws NoSuchAlgorithmException - * @throws NoSuchProviderException - */ - public static PublicKey publicToExplicitParameters(PublicKey key, String providerName) - throws IllegalArgumentException, NoSuchAlgorithmException, NoSuchProviderException - { - Provider provider = Security.getProvider(providerName); - - if (provider == null) - { - throw new NoSuchProviderException("cannot find provider: " + providerName); - } - - return publicToExplicitParameters(key, provider); - } - - /** - * Convert a passed in public EC key to have explicit parameters. If the key - * is already using explicit parameters it is returned. - * - * @param key key to be converted - * @param provider provider to be used. - * @return the equivalent key with explicit curve parameters - * @throws IllegalArgumentException - * @throws NoSuchAlgorithmException - */ - public static PublicKey publicToExplicitParameters(PublicKey key, Provider provider) - throws IllegalArgumentException, NoSuchAlgorithmException - { - try - { - SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(key.getEncoded())); - - if (info.getAlgorithmId().getObjectId().equals(CryptoProObjectIdentifiers.gostR3410_2001)) - { - throw new IllegalArgumentException("cannot convert GOST key to explicit parameters."); - } - else - { - X962Parameters params = X962Parameters.getInstance(info.getAlgorithmId().getParameters()); - X9ECParameters curveParams; - - if (params.isNamedCurve()) - { - ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(params.getParameters()); - - curveParams = ECUtil.getNamedCurveByOid(oid); - // ignore seed value due to JDK bug - curveParams = new X9ECParameters(curveParams.getCurve(), curveParams.getG(), curveParams.getN(), curveParams.getH()); - } - else if (params.isImplicitlyCA()) - { - curveParams = new X9ECParameters(BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getCurve(), BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getG(), BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getN(), BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getH()); - } - else - { - return key; // already explicit - } - - params = new X962Parameters(curveParams); - - info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params), info.getPublicKeyData().getBytes()); - - KeyFactory keyFact = KeyFactory.getInstance(key.getAlgorithm(), provider.getName()); - - return keyFact.generatePublic(new X509EncodedKeySpec(info.getEncoded())); - } - } - catch (IllegalArgumentException e) - { - throw e; - } - catch (NoSuchAlgorithmException e) - { - throw e; - } - catch (Exception e) - { // shouldn't really happen... - throw new UnexpectedException(e); - } - } - - /** - * Convert a passed in private EC key to have explicit parameters. If the key - * is already using explicit parameters it is returned. - * - * @param key key to be converted - * @param providerName provider name to be used. - * @return the equivalent key with explicit curve parameters - * @throws IllegalArgumentException - * @throws NoSuchAlgorithmException - * @throws NoSuchProviderException - */ - public static PrivateKey privateToExplicitParameters(PrivateKey key, String providerName) - throws IllegalArgumentException, NoSuchAlgorithmException, NoSuchProviderException - { - Provider provider = Security.getProvider(providerName); - - if (provider == null) - { - throw new NoSuchProviderException("cannot find provider: " + providerName); - } - - return privateToExplicitParameters(key, provider); - } - - /** - * Convert a passed in private EC key to have explicit parameters. If the key - * is already using explicit parameters it is returned. - * - * @param key key to be converted - * @param provider provider to be used. - * @return the equivalent key with explicit curve parameters - * @throws IllegalArgumentException - * @throws NoSuchAlgorithmException - */ - public static PrivateKey privateToExplicitParameters(PrivateKey key, Provider provider) - throws IllegalArgumentException, NoSuchAlgorithmException - { - try - { - PrivateKeyInfo info = PrivateKeyInfo.getInstance(ASN1Primitive.fromByteArray(key.getEncoded())); - - if (info.getAlgorithmId().getObjectId().equals(CryptoProObjectIdentifiers.gostR3410_2001)) - { - throw new UnsupportedEncodingException("cannot convert GOST key to explicit parameters."); - } - else - { - X962Parameters params = X962Parameters.getInstance(info.getAlgorithmId().getParameters()); - X9ECParameters curveParams; - - if (params.isNamedCurve()) - { - ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(params.getParameters()); - - curveParams = ECUtil.getNamedCurveByOid(oid); - // ignore seed value due to JDK bug - curveParams = new X9ECParameters(curveParams.getCurve(), curveParams.getG(), curveParams.getN(), curveParams.getH()); - } - else if (params.isImplicitlyCA()) - { - curveParams = new X9ECParameters(BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getCurve(), BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getG(), BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getN(), BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getH()); - } - else - { - return key; // already explicit - } - - params = new X962Parameters(curveParams); - - info = new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params), info.parsePrivateKey()); - - KeyFactory keyFact = KeyFactory.getInstance(key.getAlgorithm(), provider.getName()); - - return keyFact.generatePrivate(new PKCS8EncodedKeySpec(info.getEncoded())); - } - } - catch (IllegalArgumentException e) - { - throw e; - } - catch (NoSuchAlgorithmException e) - { - throw e; - } - catch (Exception e) - { // shouldn't really happen - throw new UnexpectedException(e); - } - } - - private static class UnexpectedException - extends RuntimeException - { - private Throwable cause; - - UnexpectedException(Throwable cause) - { - super(cause.toString()); - - this.cause = cause; - } - - public Throwable getCause() - { - return cause; - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/MultiCertStoreParameters.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/MultiCertStoreParameters.java deleted file mode 100644 index 42f46648f..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/MultiCertStoreParameters.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.spongycastle.jce; - -import org.spongycastle.jce.cert.CertStoreParameters; -import java.util.Collection; - -public class MultiCertStoreParameters - implements CertStoreParameters -{ - private Collection certStores; - private boolean searchAllStores; - - /** - * Create a parameters object which specifies searching of all the passed in stores. - * - * @param certStores CertStores making up the multi CertStore - */ - public MultiCertStoreParameters(Collection certStores) - { - this(certStores, true); - } - - /** - * Create a parameters object which can be to used to make a multi store made up - * of the passed in CertStores. If the searchAllStores parameter is false, any search on - * the multi-store will terminate as soon as a search query produces a result. - * - * @param certStores CertStores making up the multi CertStore - * @param searchAllStores true if all CertStores should be searched on request, false if a result - * should be returned on the first successful CertStore query. - */ - public MultiCertStoreParameters(Collection certStores, boolean searchAllStores) - { - this.certStores = certStores; - this.searchAllStores = searchAllStores; - } - - public Collection getCertStores() - { - return certStores; - } - - public boolean getSearchAllStores() - { - return searchAllStores; - } - - public Object clone() - { - return this; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/PKCS10CertificationRequest.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/PKCS10CertificationRequest.java deleted file mode 100644 index b9bc6e521..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/PKCS10CertificationRequest.java +++ /dev/null @@ -1,583 +0,0 @@ -package org.spongycastle.jce; - -import java.io.IOException; -import java.security.AlgorithmParameters; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.Signature; -import java.security.SignatureException; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.X509EncodedKeySpec; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Set; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1Set; -import org.spongycastle.asn1.DERBitString; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.spongycastle.asn1.nist.NISTObjectIdentifiers; -import org.spongycastle.asn1.oiw.OIWObjectIdentifiers; -import org.spongycastle.asn1.pkcs.CertificationRequest; -import org.spongycastle.asn1.pkcs.CertificationRequestInfo; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.pkcs.RSASSAPSSparams; -import org.spongycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x509.X509Name; -import org.spongycastle.asn1.x9.X9ObjectIdentifiers; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.util.Strings; - -/** - * A class for verifying and creating PKCS10 Certification requests. - *

- * CertificationRequest ::= SEQUENCE {
- *   certificationRequestInfo  CertificationRequestInfo,
- *   signatureAlgorithm        AlgorithmIdentifier{{ SignatureAlgorithms }},
- *   signature                 BIT STRING
- * }
- *
- * CertificationRequestInfo ::= SEQUENCE {
- *   version             INTEGER { v1(0) } (v1,...),
- *   subject             Name,
- *   subjectPKInfo   SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
- *   attributes          [0] Attributes{{ CRIAttributes }}
- *  }
- *
- *  Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}
- *
- *  Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {
- *    type    ATTRIBUTE.&id({IOSet}),
- *    values  SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type})
- *  }
- * 
- * @deprecated use classes in org.spongycastle.pkcs. - */ -public class PKCS10CertificationRequest - extends CertificationRequest -{ - private static Hashtable algorithms = new Hashtable(); - private static Hashtable params = new Hashtable(); - private static Hashtable keyAlgorithms = new Hashtable(); - private static Hashtable oids = new Hashtable(); - private static Set noParams = new HashSet(); - - static - { - algorithms.put("MD2WITHRSAENCRYPTION", new ASN1ObjectIdentifier("1.2.840.113549.1.1.2")); - algorithms.put("MD2WITHRSA", new ASN1ObjectIdentifier("1.2.840.113549.1.1.2")); - algorithms.put("MD5WITHRSAENCRYPTION", new ASN1ObjectIdentifier("1.2.840.113549.1.1.4")); - algorithms.put("MD5WITHRSA", new ASN1ObjectIdentifier("1.2.840.113549.1.1.4")); - algorithms.put("RSAWITHMD5", new ASN1ObjectIdentifier("1.2.840.113549.1.1.4")); - algorithms.put("SHA1WITHRSAENCRYPTION", new ASN1ObjectIdentifier("1.2.840.113549.1.1.5")); - algorithms.put("SHA1WITHRSA", new ASN1ObjectIdentifier("1.2.840.113549.1.1.5")); - algorithms.put("SHA224WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha224WithRSAEncryption); - algorithms.put("SHA224WITHRSA", PKCSObjectIdentifiers.sha224WithRSAEncryption); - algorithms.put("SHA256WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha256WithRSAEncryption); - algorithms.put("SHA256WITHRSA", PKCSObjectIdentifiers.sha256WithRSAEncryption); - algorithms.put("SHA384WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha384WithRSAEncryption); - algorithms.put("SHA384WITHRSA", PKCSObjectIdentifiers.sha384WithRSAEncryption); - algorithms.put("SHA512WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha512WithRSAEncryption); - algorithms.put("SHA512WITHRSA", PKCSObjectIdentifiers.sha512WithRSAEncryption); - algorithms.put("SHA1WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA224WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA256WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA384WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA512WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("RSAWITHSHA1", new ASN1ObjectIdentifier("1.2.840.113549.1.1.5")); - algorithms.put("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128); - algorithms.put("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128); - algorithms.put("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160); - algorithms.put("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160); - algorithms.put("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256); - algorithms.put("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256); - algorithms.put("SHA1WITHDSA", new ASN1ObjectIdentifier("1.2.840.10040.4.3")); - algorithms.put("DSAWITHSHA1", new ASN1ObjectIdentifier("1.2.840.10040.4.3")); - algorithms.put("SHA224WITHDSA", NISTObjectIdentifiers.dsa_with_sha224); - algorithms.put("SHA256WITHDSA", NISTObjectIdentifiers.dsa_with_sha256); - algorithms.put("SHA384WITHDSA", NISTObjectIdentifiers.dsa_with_sha384); - algorithms.put("SHA512WITHDSA", NISTObjectIdentifiers.dsa_with_sha512); - algorithms.put("SHA1WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA1); - algorithms.put("SHA224WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); - algorithms.put("SHA256WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); - algorithms.put("SHA384WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); - algorithms.put("SHA512WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); - algorithms.put("ECDSAWITHSHA1", X9ObjectIdentifiers.ecdsa_with_SHA1); - algorithms.put("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); - algorithms.put("GOST3410WITHGOST3411", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); - algorithms.put("GOST3411WITHECGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - algorithms.put("GOST3411WITHECGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - algorithms.put("GOST3411WITHGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - - // - // reverse mappings - // - oids.put(new ASN1ObjectIdentifier("1.2.840.113549.1.1.5"), "SHA1WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha224WithRSAEncryption, "SHA224WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha256WithRSAEncryption, "SHA256WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha384WithRSAEncryption, "SHA384WITHRSA"); - oids.put(PKCSObjectIdentifiers.sha512WithRSAEncryption, "SHA512WITHRSA"); - oids.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94, "GOST3411WITHGOST3410"); - oids.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001, "GOST3411WITHECGOST3410"); - - oids.put(new ASN1ObjectIdentifier("1.2.840.113549.1.1.4"), "MD5WITHRSA"); - oids.put(new ASN1ObjectIdentifier("1.2.840.113549.1.1.2"), "MD2WITHRSA"); - oids.put(new ASN1ObjectIdentifier("1.2.840.10040.4.3"), "SHA1WITHDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA1, "SHA1WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA224, "SHA224WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA256, "SHA256WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA384, "SHA384WITHECDSA"); - oids.put(X9ObjectIdentifiers.ecdsa_with_SHA512, "SHA512WITHECDSA"); - oids.put(OIWObjectIdentifiers.sha1WithRSA, "SHA1WITHRSA"); - oids.put(OIWObjectIdentifiers.dsaWithSHA1, "SHA1WITHDSA"); - oids.put(NISTObjectIdentifiers.dsa_with_sha224, "SHA224WITHDSA"); - oids.put(NISTObjectIdentifiers.dsa_with_sha256, "SHA256WITHDSA"); - - // - // key types - // - keyAlgorithms.put(PKCSObjectIdentifiers.rsaEncryption, "RSA"); - keyAlgorithms.put(X9ObjectIdentifiers.id_dsa, "DSA"); - - // - // According to RFC 3279, the ASN.1 encoding SHALL (id-dsa-with-sha1) or MUST (ecdsa-with-SHA*) omit the parameters field. - // The parameters field SHALL be NULL for RSA based signature algorithms. - // - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA1); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA224); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA256); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA384); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA512); - noParams.add(X9ObjectIdentifiers.id_dsa_with_sha1); - noParams.add(NISTObjectIdentifiers.dsa_with_sha224); - noParams.add(NISTObjectIdentifiers.dsa_with_sha256); - - // - // RFC 4491 - // - noParams.add(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); - noParams.add(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - // - // explicit params - // - AlgorithmIdentifier sha1AlgId = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, new DERNull()); - params.put("SHA1WITHRSAANDMGF1", creatPSSParams(sha1AlgId, 20)); - - AlgorithmIdentifier sha224AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha224, new DERNull()); - params.put("SHA224WITHRSAANDMGF1", creatPSSParams(sha224AlgId, 28)); - - AlgorithmIdentifier sha256AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, new DERNull()); - params.put("SHA256WITHRSAANDMGF1", creatPSSParams(sha256AlgId, 32)); - - AlgorithmIdentifier sha384AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha384, new DERNull()); - params.put("SHA384WITHRSAANDMGF1", creatPSSParams(sha384AlgId, 48)); - - AlgorithmIdentifier sha512AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512, new DERNull()); - params.put("SHA512WITHRSAANDMGF1", creatPSSParams(sha512AlgId, 64)); - } - - private static RSASSAPSSparams creatPSSParams(AlgorithmIdentifier hashAlgId, int saltSize) - { - return new RSASSAPSSparams( - hashAlgId, - new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, hashAlgId), - new ASN1Integer(saltSize), - new ASN1Integer(1)); - } - - private static ASN1Sequence toDERSequence( - byte[] bytes) - { - try - { - ASN1InputStream dIn = new ASN1InputStream(bytes); - - return (ASN1Sequence)dIn.readObject(); - } - catch (Exception e) - { - throw new IllegalArgumentException("badly encoded request"); - } - } - - /** - * construct a PKCS10 certification request from a DER encoded - * byte stream. - */ - public PKCS10CertificationRequest( - byte[] bytes) - { - super(toDERSequence(bytes)); - } - - public PKCS10CertificationRequest( - ASN1Sequence sequence) - { - super(sequence); - } - - /** - * create a PKCS10 certfication request using the BC provider. - */ - public PKCS10CertificationRequest( - String signatureAlgorithm, - X509Name subject, - PublicKey key, - ASN1Set attributes, - PrivateKey signingKey) - throws NoSuchAlgorithmException, NoSuchProviderException, - InvalidKeyException, SignatureException - { - this(signatureAlgorithm, subject, key, attributes, signingKey, BouncyCastleProvider.PROVIDER_NAME); - } - - - /** - * create a PKCS10 certfication request using the named provider. - */ - public PKCS10CertificationRequest( - String signatureAlgorithm, - X509Name subject, - PublicKey key, - ASN1Set attributes, - PrivateKey signingKey, - String provider) - throws NoSuchAlgorithmException, NoSuchProviderException, - InvalidKeyException, SignatureException - { - String algorithmName = Strings.toUpperCase(signatureAlgorithm); - ASN1ObjectIdentifier sigOID = (ASN1ObjectIdentifier)algorithms.get(algorithmName); - - if (sigOID == null) - { - try - { - sigOID = new ASN1ObjectIdentifier(algorithmName); - } - catch (Exception e) - { - throw new IllegalArgumentException("Unknown signature type requested"); - } - } - - if (subject == null) - { - throw new IllegalArgumentException("subject must not be null"); - } - - if (key == null) - { - throw new IllegalArgumentException("public key must not be null"); - } - - if (noParams.contains(sigOID)) - { - this.sigAlgId = new AlgorithmIdentifier(sigOID); - } - else if (params.containsKey(algorithmName)) - { - this.sigAlgId = new AlgorithmIdentifier(sigOID, (ASN1Encodable)params.get(algorithmName)); - } - else - { - this.sigAlgId = new AlgorithmIdentifier(sigOID, DERNull.INSTANCE); - } - - try - { - ASN1Sequence seq = (ASN1Sequence)ASN1Primitive.fromByteArray(key.getEncoded()); - this.reqInfo = new CertificationRequestInfo(subject, new SubjectPublicKeyInfo(seq), attributes); - } - catch (IOException e) - { - throw new IllegalArgumentException("can't encode public key"); - } - - Signature sig; - if (provider == null) - { - sig = Signature.getInstance(signatureAlgorithm); - } - else - { - sig = Signature.getInstance(signatureAlgorithm, provider); - } - - sig.initSign(signingKey); - - try - { - sig.update(reqInfo.getEncoded(ASN1Encoding.DER)); - } - catch (Exception e) - { - throw new IllegalArgumentException("exception encoding TBS cert request - " + e); - } - - this.sigBits = new DERBitString(sig.sign()); - } - - /** - * return the public key associated with the certification request - - * the public key is created using the BC provider. - */ - public PublicKey getPublicKey() - throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException - { - return getPublicKey(BouncyCastleProvider.PROVIDER_NAME); - } - - public PublicKey getPublicKey( - String provider) - throws NoSuchAlgorithmException, NoSuchProviderException, - InvalidKeyException - { - SubjectPublicKeyInfo subjectPKInfo = reqInfo.getSubjectPublicKeyInfo(); - - - try - { - X509EncodedKeySpec xspec = new X509EncodedKeySpec(new DERBitString(subjectPKInfo).getBytes()); - AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm(); - try - { - if (provider == null) - { - return KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec); - } - else - { - return KeyFactory.getInstance(keyAlg.getAlgorithm().getId(), provider).generatePublic(xspec); - } - } - catch (NoSuchAlgorithmException e) - { - // - // try an alternate - // - if (keyAlgorithms.get(keyAlg.getObjectId()) != null) - { - String keyAlgorithm = (String)keyAlgorithms.get(keyAlg.getObjectId()); - - if (provider == null) - { - return KeyFactory.getInstance(keyAlgorithm).generatePublic(xspec); - } - else - { - return KeyFactory.getInstance(keyAlgorithm, provider).generatePublic(xspec); - } - } - - throw e; - } - } - catch (InvalidKeySpecException e) - { - throw new InvalidKeyException("error decoding public key"); - } - catch (IOException e) - { - throw new InvalidKeyException("error decoding public key"); - } - } - - /** - * verify the request using the BC provider. - */ - public boolean verify() - throws NoSuchAlgorithmException, NoSuchProviderException, - InvalidKeyException, SignatureException - { - return verify(BouncyCastleProvider.PROVIDER_NAME); - } - - /** - * verify the request using the passed in provider. - */ - public boolean verify( - String provider) - throws NoSuchAlgorithmException, NoSuchProviderException, - InvalidKeyException, SignatureException - { - return verify(this.getPublicKey(provider), provider); - } - - /** - * verify the request using the passed in public key and the provider.. - */ - public boolean verify( - PublicKey pubKey, - String provider) - throws NoSuchAlgorithmException, NoSuchProviderException, - InvalidKeyException, SignatureException - { - Signature sig; - - try - { - if (provider == null) - { - sig = Signature.getInstance(getSignatureName(sigAlgId)); - } - else - { - sig = Signature.getInstance(getSignatureName(sigAlgId), provider); - } - } - catch (NoSuchAlgorithmException e) - { - // - // try an alternate - // - if (oids.get(sigAlgId.getObjectId()) != null) - { - String signatureAlgorithm = (String)oids.get(sigAlgId.getObjectId()); - - if (provider == null) - { - sig = Signature.getInstance(signatureAlgorithm); - } - else - { - sig = Signature.getInstance(signatureAlgorithm, provider); - } - } - else - { - throw e; - } - } - - setSignatureParameters(sig, sigAlgId.getParameters(), provider); - - sig.initVerify(pubKey); - - try - { - sig.update(reqInfo.getEncoded(ASN1Encoding.DER)); - } - catch (Exception e) - { - throw new SignatureException("exception encoding TBS cert request - " + e); - } - - return sig.verify(sigBits.getBytes()); - } - - /** - * return a DER encoded byte array representing this object - */ - public byte[] getEncoded() - { - try - { - return this.getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new RuntimeException(e.toString()); - } - } - - private void setSignatureParameters( - Signature signature, - ASN1Encodable params, - String provider) - throws NoSuchAlgorithmException, NoSuchProviderException, SignatureException, InvalidKeyException - { - if (params != null && !DERNull.INSTANCE.equals(params)) - { - AlgorithmParameters sigParams = AlgorithmParameters.getInstance(signature.getAlgorithm(), provider); - - try - { - sigParams.init(params.toASN1Primitive().getEncoded(ASN1Encoding.DER)); - } - catch (IOException e) - { - throw new SignatureException("IOException decoding parameters: " + e.getMessage()); - } - } - } - - static String getSignatureName( - AlgorithmIdentifier sigAlgId) - { - ASN1Encodable params = sigAlgId.getParameters(); - - if (params != null && !DERNull.INSTANCE.equals(params)) - { - if (sigAlgId.getObjectId().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) - { - RSASSAPSSparams rsaParams = RSASSAPSSparams.getInstance(params); - return getDigestAlgName(rsaParams.getHashAlgorithm().getObjectId()) + "withRSAandMGF1"; - } - } - - return sigAlgId.getObjectId().getId(); - } - - private static String getDigestAlgName( - ASN1ObjectIdentifier digestAlgOID) - { - if (PKCSObjectIdentifiers.md5.equals(digestAlgOID)) - { - return "MD5"; - } - else if (OIWObjectIdentifiers.idSHA1.equals(digestAlgOID)) - { - return "SHA1"; - } - else if (NISTObjectIdentifiers.id_sha224.equals(digestAlgOID)) - { - return "SHA224"; - } - else if (NISTObjectIdentifiers.id_sha256.equals(digestAlgOID)) - { - return "SHA256"; - } - else if (NISTObjectIdentifiers.id_sha384.equals(digestAlgOID)) - { - return "SHA384"; - } - else if (NISTObjectIdentifiers.id_sha512.equals(digestAlgOID)) - { - return "SHA512"; - } - else if (TeleTrusTObjectIdentifiers.ripemd128.equals(digestAlgOID)) - { - return "RIPEMD128"; - } - else if (TeleTrusTObjectIdentifiers.ripemd160.equals(digestAlgOID)) - { - return "RIPEMD160"; - } - else if (TeleTrusTObjectIdentifiers.ripemd256.equals(digestAlgOID)) - { - return "RIPEMD256"; - } - else if (CryptoProObjectIdentifiers.gostR3411.equals(digestAlgOID)) - { - return "GOST3411"; - } - else - { - return digestAlgOID.getId(); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CRLSelector.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CRLSelector.java deleted file mode 100644 index 0cafff5c4..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CRLSelector.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.security.cert.CRL; - -/** - * A selector that defines a set of criteria for selecting CRLs. - * Classes that implement this interface are often used to specify - * which CRLs should be retrieved from a CertStore.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this interface are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see CRL - * @see CertStore - * @see CertStore#getCRLs - **/ -public interface CRLSelector extends Cloneable -{ - /** - * Decides whether a CRL should be selected. - * - * @param crl the CRL to be checked - * - * @return true if the CRL should be selected, - * false otherwise - */ - public boolean match(CRL crl); - - /** - * Makes a copy of this CRLSelector. Changes to the - * copy will not affect the original and vice versa. - * - * @return a copy of this CRLSelector - */ - public Object clone(); -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPath.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPath.java deleted file mode 100644 index 34f9c6282..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPath.java +++ /dev/null @@ -1,296 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.io.ByteArrayInputStream; -import java.io.NotSerializableException; -import java.io.ObjectStreamException; -import java.io.Serializable; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -/** - * An immutable sequence of certificates (a certification path).
- *
- * This is an abstract class that defines the methods common to all CertPaths. - * Subclasses can handle different kinds of certificates (X.509, PGP, etc.).
- *
- * All CertPath objects have a type, a list of Certificates, and one or more - * supported encodings. Because the CertPath class is immutable, a CertPath - * cannot change in any externally visible way after being constructed. This - * stipulation applies to all public fields and methods of this class and any - * added or overridden by subclasses.
- *
- * The type is a String that identifies the type of Certificates in the - * certification path. For each certificate cert in a certification path - * certPath, cert.getType().equals(certPath.getType()) must be true.
- *
- * The list of Certificates is an ordered List of zero or more Certificates. - * This List and all of the Certificates contained in it must be immutable.
- *
- * Each CertPath object must support one or more encodings so that the object - * can be translated into a byte array for storage or transmission to other - * parties. Preferably, these encodings should be well-documented standards - * (such as PKCS#7). One of the encodings supported by a CertPath is considered - * the default encoding. This encoding is used if no encoding is explicitly - * requested (for the {@link #getEncoded()} method, for instance).
- *
- * All CertPath objects are also Serializable. CertPath objects are resolved - * into an alternate {@link CertPathRep} object during serialization. This - * allows a CertPath object to be serialized into an equivalent representation - * regardless of its underlying implementation.
- *
- * CertPath objects can be created with a CertificateFactory or they can be - * returned by other classes, such as a CertPathBuilder.
- *
- * By convention, X.509 CertPaths (consisting of X509Certificates), are ordered - * starting with the target certificate and ending with a certificate issued by - * the trust anchor. That is, the issuer of one certificate is the subject of - * the following one. The certificate representing the - * {@link TrustAnchor TrustAnchor} should not be included in the certification - * path. Unvalidated X.509 CertPaths may not follow these conventions. PKIX - * CertPathValidators will detect any departure from these conventions that - * cause the certification path to be invalid and throw a - * CertPathValidatorException.
- *
- * Concurrent Access
- *
- * All CertPath objects must be thread-safe. That is, multiple threads may - * concurrently invoke the methods defined in this class on a single CertPath - * object (or more than one) with no ill effects. This is also true for the List - * returned by CertPath.getCertificates.
- *
- * Requiring CertPath objects to be immutable and thread-safe allows them to be - * passed around to various pieces of code without worrying about coordinating - * access. Providing this thread-safety is generally not difficult, since the - * CertPath and List objects in question are immutable. - * - * @see CertificateFactory - * @see CertPathBuilder - */ -public abstract class CertPath extends Object implements Serializable -{ - private String type; - - /** - * Alternate CertPath class for serialization. - */ - protected static class CertPathRep implements Serializable - { - private String type; - - private byte[] data; - - /** - * Creates a CertPathRep with the specified type and - * encoded form of a certification path. - * - * @param type - * the standard name of a CertPath - * @param typedata - * the encoded form of the certification path - */ - protected CertPathRep(String type, byte[] data) - { - this.type = type; - this.data = data; - } - - /** - * Returns a CertPath constructed from the type and data. - * - * @return the resolved CertPath object - * @exception ObjectStreamException - * if a CertPath could not be constructed - */ - protected Object readResolve() throws ObjectStreamException - { - try - { - ByteArrayInputStream inStream = new ByteArrayInputStream(data); - CertificateFactory cf = CertificateFactory.getInstance(type); - return cf.generateCertPath(inStream); - } - catch (CertificateException ce) - { - throw new NotSerializableException( - " java.security.cert.CertPath: " + type); - } - } - } - - /** - * Creates a CertPath of the specified type. This constructor is protected - * because most users should use a CertificateFactory to create CertPaths. - * - * @param type - * the standard name of the type of Certificatesin this path - */ - protected CertPath(String type) - { - this.type = type; - } - - /** - * Returns the type of Certificates in this certification path. This is the - * same string that would be returned by - * {@link java.security.cert.Certificate#getType()} for all Certificates in - * the certification path. - * - * @return the type of Certificates in this certification path (never null) - */ - public String getType() - { - return type; - } - - /** - * Returns an iteration of the encodings supported by this certification - * path, with the default encoding first. Attempts to modify the returned - * Iterator via its remove method result in an - * UnsupportedOperationException. - * - * @return an Iterator over the names of the supported encodings (as - * Strings) - */ - public abstract Iterator getEncodings(); - - /** - * Compares this certification path for equality with the specified object. - * Two CertPaths are equal if and only if their types are equal and their - * certificate Lists (and by implication the Certificates in those Lists) - * are equal. A CertPath is never equal to an object that is not a CertPath.
- *
- * This algorithm is implemented by this method. If it is overridden, the - * behavior specified here must be maintained. - * - * @param other - * the object to test for equality with this certification path - * - * @return true if the specified object is equal to this certification path, - * false otherwise - * - * @see Object#hashCode() Object.hashCode() - */ - public boolean equals(Object other) - { - if (!(other instanceof CertPath)) - { - return false; - } - - CertPath otherCertPath = (CertPath)other; - if (!getType().equals(otherCertPath.getType())) - { - return false; - } - return getCertificates().equals(otherCertPath.getCertificates()); - } - - /** - * Returns the hashcode for this certification path. The hash code of a - * certification path is defined to be the result of the following - * calculation: - * - *
-     * hashCode = path.getType().hashCode();
-     * hashCode = 31 * hashCode + path.getCertificates().hashCode();
-     * 
- * - * This ensures that path1.equals(path2) implies that - * path1.hashCode()==path2.hashCode() for any two certification paths, path1 - * and path2, as required by the general contract of Object.hashCode. - * - * @return The hashcode value for this certification path - * - * @see #equals(Object) - */ - public int hashCode() - { - return getType().hashCode() * 31 + getCertificates().hashCode(); - } - - /** - * Returns a string representation of this certification path. This calls - * the toString method on each of the Certificates in the path. - * - * @return a string representation of this certification path - */ - public String toString() - { - StringBuffer s = new StringBuffer(); - List certs = getCertificates(); - ListIterator iter = certs.listIterator(); - s.append('\n').append(getType()).append(" Cert Path: length = ").append(certs.size()) - .append("\n[\n"); - while (iter.hasNext()) - { - s - .append("=========================================================Certificate ") - .append(iter.nextIndex()).append('\n'); - s.append(iter.next()).append('\n'); - s - .append("========================================================Certificate end\n\n\n"); - } - s.append("\n]"); - return s.toString(); - } - - /** - * Returns the encoded form of this certification path, using the default - * encoding. - * - * @return the encoded bytes - * - * @exception CertificateEncodingException - * if an encoding error occurs - */ - public abstract byte[] getEncoded() throws CertificateEncodingException; - - /** - * Returns the encoded form of this certification path, using the specified - * encoding. - * - * @param encoding - * the name of the encoding to use - * - * @return the encoded bytes - * - * @exception CertificateEncodingException - * if an encoding error occurs or the encoding requested is - * not supported - */ - public abstract byte[] getEncoded(String encoding) - throws CertificateEncodingException; - - /** - * Returns the list of certificates in this certification path. The List - * returned must be immutable and thread-safe. - * - * @return an immutable List of Certificates (may be empty, but not null) - */ - public abstract List getCertificates(); - - /** - * Replaces the CertPath to be serialized with a CertPathRep object. - * - * @return the CertPathRep to be serialized - * - * @exception ObjectStreamException - * if a CertPathRep object representing this certification - * path could not be created - */ - protected Object writeReplace() throws ObjectStreamException - { - try - { - return new CertPathRep(getType(), getEncoded()); - } - catch (CertificateException ce) - { - throw new NotSerializableException(" java.security.cert.CertPath: " - + getType()); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathBuilder.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathBuilder.java deleted file mode 100644 index 54585689d..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathBuilder.java +++ /dev/null @@ -1,255 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.Security; - -/** - * A class for building certification paths (also known as certificate chains).
- *
- * This class uses a provider-based architecture, as described in the Java - * Cryptography Architecture. To create a CertPathBuilder, call - * one of the static getInstance methods, passing in the - * algorithm name of the CertPathBuilder desired and optionally the name of the - * provider desired.
- *
- * Once a CertPathBuilder object has been created, certification - * paths can be constructed by calling the {@link #build build} method and - * passing it an algorithm-specific set of parameters. If successful, the result - * (including the CertPath that was built) is returned in an object that - * implements the CertPathBuilderResult interface.
- *
- * Concurrent Access
- *
- * The static methods of this class are guaranteed to be thread-safe. Multiple - * threads may concurrently invoke the static methods defined in this class with - * no ill effects.
- *
- * However, this is not true for the non-static methods defined by this class. - * Unless otherwise documented by a specific provider, threads that need to - * access a single CertPathBuilder instance concurrently should - * synchronize amongst themselves and provide the necessary locking. Multiple - * threads each manipulating a different CertPathBuilder instance - * need not synchronize.
- *
- */ -public class CertPathBuilder extends Object -{ - private CertPathBuilderSpi builderSpi; - - private Provider provider; - - private String algorithm; - - /** - * Creates a CertPathBuilder object of the given algorithm, and encapsulates - * the given provider implementation (SPI object) in it. - * - * @param builderSpi - * the provider implementation - * @param provider - * the provider - * @param algorithm - * the algorithm name - */ - protected CertPathBuilder( - CertPathBuilderSpi builderSpi, - Provider provider, - String algorithm) - { - this.builderSpi = builderSpi; - this.provider = provider; - this.algorithm = algorithm; - } - - /** - * Returns a CertPathBuilder object that implements the specified algorithm.
- *
- * If the default provider package provides an implementation of the - * specified CertPathBuilder algorithm, an instance of CertPathBuilder - * containing that implementation is returned. If the requested algorithm is - * not available in the default package, other packages are searched.
- *
- * - * @param algorithm - * the name of the requested CertPathBuilder algorithm - * - * @return a CertPathBuilder object that implements the specified algorithm - * - * @exception NoSuchAlgorithmException - * if the requested algorithm is not available in the default - * provider package or any of the other provider packages - * that were searched - */ - public static CertPathBuilder getInstance(String algorithm) - throws NoSuchAlgorithmException - { - try - { - CertUtil.Implementation imp = CertUtil.getImplementation( - "CertPathBuilder", algorithm, (String)null); - if (imp != null) - { - return new CertPathBuilder((CertPathBuilderSpi)imp.getEngine(), - imp.getProvider(), algorithm); - } - } - catch (NoSuchProviderException ex) - { - } - throw new NoSuchAlgorithmException("can't find type " + algorithm); - } - - /** - * Returns a CertPathBuilder object that implements the specified algorithm, - * as supplied by the specified provider. - * - * @param algorithm - * the name of the requested CertPathBuilder algorithm - * @param provider - * the name of the provider - * - * @return a CertPathBuilder object that implements the specified algorithm, - * as supplied by the specified provider - * - * @exception NoSuchAlgorithmException - * if the requested algorithm is not available from the - * specified provider - * @exception NoSuchProviderException - * if the provider has not been configured - * @exception IllegalArgumentException - * if the provider is null - */ - public static CertPathBuilder getInstance(String algorithm, String provider) - throws NoSuchAlgorithmException, NoSuchProviderException - { - if (provider == null) - { - throw new IllegalArgumentException("provider must be non-null"); - } - CertUtil.Implementation imp = CertUtil.getImplementation( - "CertPathBuilder", algorithm, provider); - - if (imp != null) - { - return new CertPathBuilder((CertPathBuilderSpi)imp.getEngine(), imp - .getProvider(), algorithm); - } - throw new NoSuchAlgorithmException("can't find type " + algorithm); - } - - /** - * Returns a CertPathBuilder object that implements the specified algorithm, - * as supplied by the specified provider. Note: the provider doesn't have to - * be registered. - * - * @param algorithm - * the name of the requested CertPathBuilder algorithm - * @param provider - * the provider - * @return a CertPathBuilder object that implements the specified algorithm, - * as supplied by the specified provider - * - * @exception NoSuchAlgorithmException - * if the requested algorithm is not available from the - * specified provider - * @exception IllegalArgumentException - * if the provider is null. - */ - public static CertPathBuilder getInstance(String algorithm, - Provider provider) throws NoSuchAlgorithmException - { - if (provider == null) - { - throw new IllegalArgumentException("provider must be non-null"); - } - CertUtil.Implementation imp = CertUtil.getImplementation( - "CertPathBuilder", algorithm, provider); - - if (imp != null) - { - return new CertPathBuilder((CertPathBuilderSpi)imp.getEngine(), - provider, algorithm); - } - throw new NoSuchAlgorithmException("can't find type " + algorithm); - } - - /** - * Returns the provider of this CertPathBuilder. - * - * @return the provider of this CertPathBuilder - */ - public final Provider getProvider() - { - return provider; - } - - /** - * Returns the name of the algorithm of this CertPathBuilder. - * - * @return the name of the algorithm of this CertPathBuilder - */ - public final String getAlgorithm() - { - return algorithm; - } - - /** - * Attempts to build a certification path using the specified algorithm - * parameter set. - * - * @param params - * the algorithm parameters - * - * @return the result of the build algorithm - * - * @exception CertPathBuilderException - * if the builder is unable to construct a certification path - * that satisfies the specified parameters - * @exception InvalidAlgorithmParameterException - * if the specified parameters * are inappropriate for this - * CertPathBuilder - */ - public final CertPathBuilderResult build(CertPathParameters params) - throws CertPathBuilderException, InvalidAlgorithmParameterException - { - return builderSpi.engineBuild(params); - } - - /** - * Returns the default CertPathBuilder type as specified in - * the Java security properties file, or the string "PKIX" if no - * such property exists. The Java security properties file is located in the - * file named <JAVA_HOME>/lib/security/java.security, where - * <JAVA_HOME> refers to the directory where the SDK was installed.
- *
- * The default CertPathBuilder type can be used by - * applications that do not want to use a hard-coded type when calling one - * of the getInstance methods, and want to provide a default - * type in case a user does not specify its own.
- *
- * The default CertPathBuilder type can be changed by setting - * the value of the "certpathbuilder.type" security property (in the Java - * security properties file) to the desired type. - * - * @return the default CertPathBuilder type as specified in - * the Java security properties file, or the string "PKIX" - * if no such property exists. - */ - public static final String getDefaultType() - { - String defaulttype = null; - defaulttype = Security.getProperty("certpathbuilder.type"); - - if (defaulttype == null || defaulttype.length() <= 0) - { - return "PKIX"; - } - else - { - return defaulttype; - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathBuilderException.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathBuilderException.java deleted file mode 100644 index 1dce8758f..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathBuilderException.java +++ /dev/null @@ -1,182 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.io.PrintStream; -import java.io.PrintWriter; -import java.security.GeneralSecurityException; - -/** - * An exception indicating one of a variety of problems encountered - * when building a certification path with a - * CertPathBuilder.
- *
- * A CertPathBuilderException provides support for - * wrapping exceptions. The {@link #getCause() getCause} method - * returns the throwable, if any, that caused this exception to be - * thrown.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are - * not thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see CertPathBuilder - **/ -public class CertPathBuilderException extends GeneralSecurityException -{ - private Throwable cause; - - /** - * Creates a CertPathBuilderException with null - * as its detail message. - */ - public CertPathBuilderException() - { - } - - /** - * Creates a CertPathBuilderException with the given detail - * message. The detail message is a String that describes - * this particular exception in more detail. - * - * @param msg - * the detail message - */ - public CertPathBuilderException(String message) - { - super(message); - } - - /** - * Creates a CertPathBuilderException that wraps the - * specified throwable. This allows any exception to be converted into a - * CertPathBuilderException, while retaining information - * about the wrapped exception, which may be useful for debugging. The - * detail message is set to - * (cause==null ? null : cause.toString()) (which typically - * contains the class and detail message of cause). - * - * @param cause - * the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, and - * indicates that the cause is nonexistent or unknown.) - */ - public CertPathBuilderException(String message, Throwable cause) - { - super(message); - this.cause = cause; - } - - /** - * Creates a CertPathBuilderException with the specified - * detail message and cause. - * - * @param msg - * the detail message - * @param cause - * the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is permitted, and - * indicates that the cause is nonexistent or unknown.) - */ - public CertPathBuilderException(Throwable cause) - { - this.cause = cause; - } - - /** - * Returns the internal (wrapped) cause, or null if the cause is nonexistent - * or unknown. - * - * @return the cause of this throwable or null if the cause - * is nonexistent or unknown. - */ - public Throwable getCause() - { - return cause; - } - - /** - * Returns the detail message for this CertPathBuilderException. - * - * @return the detail message, or null if neither the message - * nor internal cause were specified - */ - public String getMessage() - { - String message = super.getMessage(); - - if (message == null && cause == null) - { - return null; - } - - if (cause != null) - { - return cause.getMessage(); - } - - return message; - } - - /** - * Returns a string describing this exception, including a description of - * the internal (wrapped) cause if there is one. - * - * @return a string representation of this - * CertPathBuilderException - */ - public String toString() - { - String message = getMessage(); - if (message == null) - { - return ""; - } - - return message; - } - - /** - * Prints a stack trace to System.err, including the - * backtrace of the cause, if any. - */ - public void printStackTrace() - { - printStackTrace(System.err); - } - - /** - * Prints a stack trace to a PrintStream, including the - * backtrace of the cause, if any. - * - * @param ps - * the PrintStream to use for output - */ - public void printStackTrace(PrintStream ps) - { - super.printStackTrace(ps); - if (getCause() != null) - { - getCause().printStackTrace(ps); - } - } - - /** - * Prints a stack trace to a PrintWriter, including the - * backtrace of the cause, if any. - * - * @param ps - * the PrintWriter to use for output - */ - public void printStackTrace(PrintWriter pw) - { - super.printStackTrace(pw); - if (getCause() != null) - { - getCause().printStackTrace(pw); - } - } -} - diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathBuilderResult.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathBuilderResult.java deleted file mode 100644 index a1518cba4..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathBuilderResult.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.spongycastle.jce.cert; - -/** - * A specification of the result of a certification path builder algorithm. - * All results returned by the {@link CertPathBuilder#build CertPathBuilder.build} method - * must implement this interface.
- *
- * At a minimum, a CertPathBuilderResult contains the CertPath built by the - * CertPathBuilder instance. Implementations of this interface may add methods - * to return implementation or algorithm specific information, such as - * debugging information or certification path validation results.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this interface are not - * thread-safe. Multiple threads that need to access a single object - * concurrently should synchronize amongst themselves and provide the - * necessary locking. Multiple threads each manipulating separate objects - * need not synchronize. - **/ -public interface CertPathBuilderResult extends Cloneable -{ - /** - * Returns the built certification path. - * - * @return the certification path (never null) - */ - public CertPath getCertPath(); - - /** - * Makes a copy of this CertPathBuilderResult. - * Changes to the copy will not affect the original and vice - * versa. - * - * @return a copy of this CertPathBuilderResult - */ - public Object clone(); -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathBuilderSpi.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathBuilderSpi.java deleted file mode 100644 index bb08d99a4..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathBuilderSpi.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.security.InvalidAlgorithmParameterException; - -/** - * The Service Provider Interface (SPI) for the CertPathBuilder - * class. All CertPathBuilder implementations must include a class - * (the SPI class) that extends this class (CertPathBuilderSpi) and - * implements all of its methods. In general, instances of this class - * should only be accessed through the CertPathBuilder class. For - * details, see the Java Cryptography Architecture.
- *
- * Concurrent Access
- *
- * Instances of this class need not be protected against concurrent - * access from multiple threads. Threads that need to access a single - * CertPathBuilderSpi instance concurrently should synchronize amongst - * themselves and provide the necessary locking before calling the - * wrapping CertPathBuilder object.
- *
- * However, implementations of CertPathBuilderSpi may still encounter - * concurrency issues, since multiple threads each manipulating a - * different CertPathBuilderSpi instance need not synchronize. - **/ -public abstract class CertPathBuilderSpi - extends Object -{ - /** - * The default constructor. - */ - public CertPathBuilderSpi() {} - - /** - * Attempts to build a certification path using the specified - * algorithm parameter set. - * - * @param params the algorithm parameters - * - * @return the result of the build algorithm - * - * @exception CertPathBuilderException if the builder is unable - * to construct a certification path that satisfies the - * specified - * @exception parametersInvalidAlgorithmParameterException if the - * specified parameters are inappropriate for this CertPathBuilder - */ - public abstract CertPathBuilderResult engineBuild(CertPathParameters params) - throws CertPathBuilderException, - InvalidAlgorithmParameterException; -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathParameters.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathParameters.java deleted file mode 100644 index 96978bd75..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathParameters.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.spongycastle.jce.cert; - -/** - * A specification of certification path algorithm parameters. The purpose - * of this interface is to group (and provide type safety for) all CertPath - * parameter specifications. All CertPath parameter specifications must - * implement this interface. - **/ -public interface CertPathParameters extends Cloneable -{ - /** - * Makes a copy of this CertPathParameters. Changes to the - * copy will not affect the original and vice versa. - * - * @return a copy of this CertPathParameters - **/ - public Object clone(); -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathValidator.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathValidator.java deleted file mode 100644 index d2e599312..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathValidator.java +++ /dev/null @@ -1,276 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.Security; - -/** - * A class for validating certification paths (also known as certificate - * chains).
- *
- * This class uses a provider-based architecture, as described in the Java - * Cryptography Architecture. To create a CertPathValidator, - * call one of the static getInstance methods, passing in the - * algorithm name of the CertPathValidator desired and - * optionally the name of the provider desired.
- *
- * Once a CertPathValidator object has been created, it can - * be used to validate certification paths by calling the {@link #validate - * validate} method and passing it the CertPath to be validated - * and an algorithm-specific set of parameters. If successful, the result is - * returned in an object that implements the - * CertPathValidatorResult interface.
- *
- * Concurrent Access
- *
- * The static methods of this class are guaranteed to be thread-safe. - * Multiple threads may concurrently invoke the static methods defined in - * this class with no ill effects.
- *
- * However, this is not true for the non-static methods defined by this class. - * Unless otherwise documented by a specific provider, threads that need to - * access a single CertPathValidator instance concurrently should - * synchronize amongst themselves and provide the necessary locking. Multiple - * threads each manipulating a different CertPathValidator - * instance need not synchronize.
- *
- * @see CertPath - **/ -public class CertPathValidator extends Object -{ - private CertPathValidatorSpi validatorSpi; - - private Provider provider; - - private String algorithm; - - /** - * Creates a CertPathValidator object of the given algorithm, - * and encapsulates the given provider implementation (SPI object) in it. - * - * @param validatorSpi - * the provider implementation - * @param provider - * the provider - * @param algorithm - * the algorithm name - */ - protected CertPathValidator( - CertPathValidatorSpi validatorSpi, - Provider provider, - String algorithm) - { - this.validatorSpi = validatorSpi; - this.provider = provider; - this.algorithm = algorithm; - } - - /** - * Returns a CertPathValidator object that implements the - * specified algorithm.
- *
- * If the default provider package provides an implementation of the - * specified CertPathValidator algorithm, an instance of - * CertPathValidator containing that implementation is - * returned. If the requested algorithm is not available in the default - * package, other packages are searched. - * - * @param algorithm - * the name of the requested CertPathValidator - * algorithm - * - * @return a CertPathValidator object that implements the - * specified algorithm - * - * @exception NoSuchAlgorithmException - * if the requested algorithm is not available in the default - * provider package or any of the other provider packages - * that were searched - */ - public static CertPathValidator getInstance(String algorithm) - throws NoSuchAlgorithmException - { - try - { - CertUtil.Implementation imp = CertUtil.getImplementation( - "CertPathValidator", algorithm, (String)null); - if (imp != null) - { - return new CertPathValidator((CertPathValidatorSpi)imp - .getEngine(), imp.getProvider(), algorithm); - } - } - catch (NoSuchProviderException ex) - { - } - throw new NoSuchAlgorithmException("can't find algorithm " + algorithm); - } - - /** - * Returns a CertPathValidator object that implements the - * specified algorithm, as supplied by the specified provider. - * - * @param algorithm - * the name of the requested CertPathValidator - * algorithm - * @param provider - * the name of the provider - * - * @return a CertPathValidator object that implements the - * specified algorithm, as supplied by the specified provider - * - * @exception NoSuchAlgorithmException - * if the requested algorithm is not available from the - * specified provider - * @exception NoSuchProviderException - * if the provider has not been configured - * @exception IllegalArgumentException - * if the provider is null - */ - public static CertPathValidator getInstance(String algorithm, - String provider) throws NoSuchAlgorithmException, - NoSuchProviderException - { - if (provider == null) - { - throw new IllegalArgumentException("provider must be non-null"); - } - - CertUtil.Implementation imp = CertUtil.getImplementation( - "CertPathValidator", algorithm, provider); - if (imp != null) - { - return new CertPathValidator((CertPathValidatorSpi)imp.getEngine(), - imp.getProvider(), algorithm); - } - throw new NoSuchAlgorithmException("can't find algorithm " + algorithm); - } - - /** - * Returns a CertPathValidator object that implements the - * specified algorithm, as supplied by the specified provider. Note: the - * provider doesn't have to be registered. - * - * @param algorithm - * the name of the requested CertPathValidator - * algorithm - * @param provider - * the provider - * - * @return a CertPathValidator object that implements the - * specified algorithm, as supplied by the specified provider - * - * @exception NoSuchAlgorithmException - * if the requested algorithm is not available from the - * specified provider - * @exception IllegalArgumentException - * if the provider is null - */ - public static CertPathValidator getInstance(String algorithm, - Provider provider) throws NoSuchAlgorithmException - { - if (provider == null) - { - throw new IllegalArgumentException("provider must be non-null"); - } - - CertUtil.Implementation imp = CertUtil.getImplementation( - "CertPathValidator", algorithm, provider); - if (imp != null) - { - return new CertPathValidator((CertPathValidatorSpi)imp.getEngine(), - provider, algorithm); - } - throw new NoSuchAlgorithmException("can't find algorithm " + algorithm); - } - - /** - * Returns the Provider of this - * CertPathValidator. - * - * @return the Provider of this - * CertPathValidator - */ - public final Provider getProvider() - { - return provider; - } - - /** - * Returns the algorithm name of this CertPathValidator. - * - * @return the algorithm name of this CertPathValidator - */ - public final String getAlgorithm() - { - return algorithm; - } - - /** - * Validates the specified certification path using the specified algorithm - * parameter set.
- *
- * The CertPath specified must be of a type that is supported - * by the validation algorithm, otherwise an - * InvalidAlgorithmParameterException will be thrown. For - * example, a CertPathValidator that implements the PKIX - * algorithm validates CertPath objects of type X.509. - * - * @param certPath - * the CertPath to be validated - * @param params - * the algorithm parameters - * - * @return the result of the validation algorithm - * - * @exception CertPathValidatorException - * if the CertPath does not validate - * @exception InvalidAlgorithmParameterException - * if the specified parameters or the type of the specified - * CertPath are inappropriate for this - * CertPathValidator - */ - public final CertPathValidatorResult validate(CertPath certPath, - CertPathParameters params) throws CertPathValidatorException, - InvalidAlgorithmParameterException - { - return validatorSpi.engineValidate(certPath, params); - } - - /** - * Returns the default CertPathValidator type as specified in - * the Java security properties file, or the string "PKIX" if no - * such property exists. The Java security properties file is located in the - * file named <JAVA_HOME>/lib/security/java.security, where - * <JAVA_HOME> refers to the directory where the SDK was installed.
- *
- * The default CertPathValidator type can be used by - * applications that do not want to use a hard-coded type when calling one - * of the getInstance methods, and want to provide a default - * type in case a user does not specify its own.
- *
- * The default CertPathValidator type can be changed by - * setting the value of the "certpathvalidator.type" security property (in - * the Java security properties file) to the desired type. - * - * @return the default CertPathValidator type as specified in - * the Java security properties file, or the string "PKIX" - * if no such property exists. - */ - public static final String getDefaultType() - { - String defaulttype = null; - defaulttype = Security.getProperty("certpathvalidator.type"); - - if (defaulttype == null || defaulttype.length() <= 0) - { - return "PKIX"; - } - else - { - return defaulttype; - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathValidatorException.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathValidatorException.java deleted file mode 100644 index bcd67a4a7..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathValidatorException.java +++ /dev/null @@ -1,271 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.io.PrintStream; -import java.io.PrintWriter; -import java.security.GeneralSecurityException; - -/** - * An exception indicating one of a variety of problems encountered when - * validating a certification path.
- *
- * A CertPathValidatorException provides support for wrapping - * exceptions. The {@link #getCause getCause} method returns the throwable, - * if any, that caused this exception to be thrown.
- *
- * A CertPathValidatorException may also include the - * certification path that was being validated when the exception was thrown - * and the index of the certificate in the certification path that caused the - * exception to be thrown. Use the {@link #getCertPath getCertPath} and - * {@link #getIndex getIndex} methods to retrieve this information.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see CertPathValidator - **/ -public class CertPathValidatorException extends GeneralSecurityException -{ - private Throwable cause; - private CertPath certPath; - private int index = -1; - - /** - * Creates a CertPathValidatorException with no detail - * message. - */ - public CertPathValidatorException() - { - super(); - } - - /** - * Creates a CertPathValidatorException with the given detail - * message. A detail message is a String that describes this - * particular exception. - * - * @param messag - * the detail message - */ - public CertPathValidatorException(String message) - { - super(message); - } - - /** - * Creates a CertPathValidatorException with the specified - * detail message and cause. - * - * @param msg - * the detail message - * @param cause - * the cause (which is saved for later retrieval by the - * {@link #getCause getCause()} method). (A null - * value is permitted, and indicates that the cause is - * nonexistent or unknown.) - */ - public CertPathValidatorException(String message, Throwable cause) - { - super(message); - this.cause = cause; - } - - /** - * Creates a CertPathValidatorException with the specified - * detail message, cause, certification path, and index. - * - * @param msg - * the detail message (or null if none) - * @param cause - * the cause (or null if none) - * @param certPath - * the certification path that was in the process of being - * validated when the error was encountered - * @param index - * the index of the certificate in the certification path that - * caused the error (or -1 if not applicable). Note that the list - * of certificates in a CertPath is zero based. - * - * @exception IndexOutOfBoundsException - * if the index is out of range - * (index < -1 || (certPath != null && index >= - * certPath.getCertificates().size()) - * @exception IllegalArgumentException - * if certPath is null and - * index is not -1 - */ - public CertPathValidatorException( - String message, - Throwable cause, - CertPath certPath, - int index) - { - super(message); - - if (certPath == null && index != -1) - { - throw new IllegalArgumentException( - "certPath = null and index != -1"); - } - if (index < -1 - || (certPath != null && index >= certPath.getCertificates() - .size())) - { - throw new IndexOutOfBoundsException( - " index < -1 or out of bound of certPath.getCertificates()"); - } - - this.cause = cause; - this.certPath = certPath; - this.index = index; - } - - /** - * Creates a CertPathValidatorException that wraps the - * specified throwable. This allows any exception to be converted into a - * CertPathValidatorException, while retaining information - * about the wrapped exception, which may be useful for debugging. The - * detail message is set to (cause==null ? null : cause.toString() - * ) - * (which typically contains the class and detail message of cause). - * - * @param cause - * the cause (which is saved for later retrieval by the - * {@link #getCause getCause()} method). (A null - * value is permitted, and indicates that the cause is - * nonexistent or unknown.) - */ - public CertPathValidatorException(Throwable cause) - { - this.cause = cause; - } - - /** - * Returns the detail message for this - * CertPathValidatorException. - * - * @return the detail message, or null if neither the message - * nor cause were specified - */ - public String getMessage() - { - String message = super.getMessage(); - - if (message != null) - { - return message; - } - - if (cause != null) - { - return cause.getMessage(); - } - - return null; - } - - /** - * Returns the certification path that was being validated when the - * exception was thrown. - * - * @return the CertPath that was being validated when the - * exception was thrown (or null if not specified) - */ - public CertPath getCertPath() - { - return certPath; - } - - /** - * Returns the index of the certificate in the certification path that - * caused the exception to be thrown. Note that the list of certificates in - * a CertPath is zero based. If no index has been set, -1 is - * returned. - * - * @return the index that has been set, or -1 if none has been set - */ - public int getIndex() - { - return index; - } - - /** - * Returns the cause of this CertPathValidatorException or - * null if the cause is nonexistent or unknown. - * - * @return the cause of this throwable or null if the cause - * is nonexistent or unknown. - */ - public Throwable getCause() - { - return cause; - } - - /** - * Returns a string describing this exception, including a description of - * the internal (wrapped) cause if there is one. - * - * @return a string representation of this - * CertPathValidatorException - */ - public String toString() - { - StringBuffer sb = new StringBuffer(); - String s = getMessage(); - if (s != null) - { - sb.append(s); - } - if (getIndex() >= 0) - { - sb.append("index in certpath: ").append(getIndex()).append('\n'); - sb.append(getCertPath()); - } - return sb.toString(); - } - - /** - * Prints a stack trace to System.err, including the - * backtrace of the cause, if any. - */ - public void printStackTrace() - { - printStackTrace(System.err); - } - - /** - * Prints a stack trace to a PrintStream, including the - * backtrace of the cause, if any. - * - * @param ps - * the PrintStream to use for output - */ - public void printStackTrace(PrintStream ps) - { - super.printStackTrace(ps); - if (getCause() != null) - { - getCause().printStackTrace(ps); - } - } - - /** - * Prints a stack trace to a PrintWriter, including the - * backtrace of the cause, if any. - * - * @param pw - * the PrintWriter to use for output - */ - public void printStackTrace(PrintWriter pw) - { - super.printStackTrace(pw); - if (getCause() != null) - { - getCause().printStackTrace(pw); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathValidatorResult.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathValidatorResult.java deleted file mode 100644 index e31b23f29..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathValidatorResult.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.spongycastle.jce.cert; - -/** - * A specification of the result of a certification path validator algorithm.
- *
- * The purpose of this interface is to group (and provide type safety - * for) all certification path validator results. All results returned - * by the {@link CertPathValidator#validate CertPathValidator.validate} - * method must implement this interface. - * - * @see CertPathValidator - **/ -public interface CertPathValidatorResult extends Cloneable -{ - /** - * Makes a copy of this CertPathValidatorResult. Changes to the - * copy will not affect the original and vice versa. - * - * @return a copy of this CertPathValidatorResult - */ - public Object clone(); -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathValidatorSpi.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathValidatorSpi.java deleted file mode 100644 index 39f706d21..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertPathValidatorSpi.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.security.InvalidAlgorithmParameterException; - -/** - * - * The Service Provider Interface (SPI) - * for the {@link CertPathValidator CertPathValidator} class. All - * CertPathValidator implementations must include a class (the - * SPI class) that extends this class (CertPathValidatorSpi) - * and implements all of its methods. In general, instances of this class - * should only be accessed through the CertPathValidator class. - * For details, see the Java Cryptography Architecture.
- *
- * Concurrent Access
- *
- * Instances of this class need not be protected against concurrent - * access from multiple threads. Threads that need to access a single - * CertPathValidatorSpi instance concurrently should synchronize - * amongst themselves and provide the necessary locking before calling the - * wrapping CertPathValidator object.
- *
- * However, implementations of CertPathValidatorSpi may still - * encounter concurrency issues, since multiple threads each - * manipulating a different CertPathValidatorSpi instance need not - * synchronize. - **/ -public abstract class CertPathValidatorSpi extends Object -{ - /** - * The default constructor. - */ - public CertPathValidatorSpi() {} - - /** - * Validates the specified certification path using the specified - * algorithm parameter set.
- *
- * The CertPath specified must be of a type that is - * supported by the validation algorithm, otherwise an - * InvalidAlgorithmParameterException will be thrown. For - * example, a CertPathValidator that implements the PKIX - * algorithm validates CertPath objects of type X.509. - * - * @param certPath the CertPath to be validated - * @param params the algorithm parameters - * - * @return the result of the validation algorithm - * - * @exception CertPathValidatorException if the CertPath - * does not validate - * @exception InvalidAlgorithmParameterException if the specified - * parameters or the type of the specified CertPath are - * inappropriate for this CertPathValidator - */ - public abstract CertPathValidatorResult engineValidate(CertPath certPath, CertPathParameters params) - throws CertPathValidatorException, - InvalidAlgorithmParameterException; -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertSelector.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertSelector.java deleted file mode 100644 index 2f2b0b468..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertSelector.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.security.cert.Certificate; - -/** - * A selector that defines a set of criteria for selecting - * Certificates. Classes that implement this interface - * are often used to specify which Certificates should - * be retrieved from a CertStore.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this interface are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see Certificate - * @see CertStore - * @see CertStore#getCertificates - */ -public interface CertSelector extends Cloneable -{ - /** - * Decides whether a Certificate should be selected. - * - * @param cert the Certificate to be checked - * @return true if the Certificate - * should be selected, false otherwise - */ - public boolean match(Certificate cert); - - /** - * Makes a copy of this CertSelector. Changes to the - * copy will not affect the original and vice versa. - * - * @return a copy of this CertSelector - */ - public Object clone(); -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertStore.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertStore.java deleted file mode 100644 index 8a284262a..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertStore.java +++ /dev/null @@ -1,382 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.Security; -import java.util.Collection; - -/** - * A class for retrieving Certificates and CRLs - * from a repository.
- *
- * This class uses a provider-based architecture, as described in the - * Java Cryptography Architecture. - * To create a CertStore, call one of the static - * getInstance methods, passing in the type of - * CertStore desired, any applicable initialization parameters - * and optionally the name of the provider desired.
- *
- * Once the CertStore has been created, it can be used to - * retrieve Certificates and CRLs by calling its - * {@link #getCertificates(CertSelector selector) getCertificates} and - * {@link #getCRLs(CRLSelector selector) getCRLs} methods.
- *
- * Unlike a {@link java.security.KeyStore KeyStore}, which provides access - * to a cache of private keys and trusted certificates, a - * CertStore is designed to provide access to a potentially - * vast repository of untrusted certificates and CRLs. For example, an LDAP - * implementation of CertStore provides access to certificates - * and CRLs stored in one or more directories using the LDAP protocol and the - * schema as defined in the RFC service attribute. See Appendix A in the - * Java Certification Path API Programmer's Guide for more information about - * standard CertStore types.
- *
- * Concurrent Access
- *
- * All public methods of CertStore objects must be thread-safe. - * That is, multiple threads may concurrently invoke these methods on a - * single CertStore object (or more than one) with no - * ill effects. This allows a CertPathBuilder to search for a - * CRL while simultaneously searching for further certificates, for instance.
- *
- * The static methods of this class are also guaranteed to be thread-safe. - * Multiple threads may concurrently invoke the static methods defined in - * this class with no ill effects.
- *
- **/ -public class CertStore extends Object -{ - private CertStoreSpi storeSpi; - - private Provider provider; - - private String type; - - private CertStoreParameters params; - - /** - * Creates a CertStore object of the given type, and - * encapsulates the given provider implementation (SPI object) in it. - * - * @param storeSpi - * the provider implementation - * @param provider - * the provider - * @param type - * the type - * @param params - * the initialization parameters (may be null) - */ - protected CertStore( - CertStoreSpi storeSpi, - Provider provider, - String type, - CertStoreParameters params) - { - this.storeSpi = storeSpi; - this.provider = provider; - this.type = type; - this.params = params; - } - - /** - * Returns a Collection of Certificates that - * match the specified selector. If no Certificates match - * the selector, an empty Collection will be returned.
- *
- * For some CertStore types, the resulting - * Collection may not contain all of the - * Certificates that match the selector. For instance, an - * LDAP CertStore may not search all entries in the - * directory. Instead, it may just search entries that are likely to contain - * the Certificates it is looking for.
- *
- * Some CertStore implementations (especially LDAP - * CertStores) may throw a CertStoreException - * unless a non-null CertSelector is provided that includes - * specific criteria that can be used to find the certificates. Issuer - * and/or subject names are especially useful criteria. - * - * @param selector - * A CertSelector used to select which - * Certificates should be returned. Specify - * null to return all Certificates - * (if supported). - * - * @return A Collection of Certificates that - * match the specified selector (never null) - * @exception CertStoreException - * if an exception occurs - */ - public final Collection getCertificates(CertSelector selector) - throws CertStoreException - { - return storeSpi.engineGetCertificates(selector); - } - - /** - * Returns a Collection of CRLs that match - * the specified selector. If no CRLs match the selector, an - * empty Collection will be returned.
- *
- * For some CertStore types, the resulting - * Collection may not contain all of the - * CRLs that match the selector. For instance, an LDAP - * CertStore may not search all entries in the directory. - * Instead, it may just search entries that are likely to contain the - * CRLs it is looking for.
- *
- * Some CertStore implementations (especially LDAP - * CertStores) may throw a CertStoreException - * unless a non-null CRLSelector is provided that includes - * specific criteria that can be used to find the CRLs. Issuer names and/or - * the certificate to be checked are especially useful. - * - * @param selector - * A CRLSelector used to select which - * CRLs should be returned. Specify - * null to return all CRLs (if - * supported). - * - * @return A Collection of CRLs that match - * the specified selector (never null) - * - * @exception CertStoreException - * if an exception occurs - */ - public final Collection getCRLs(CRLSelector selector) - throws CertStoreException - { - return storeSpi.engineGetCRLs(selector); - } - - /** - * Returns a CertStore object that implements the specified - * CertStore type and is initialized with the specified - * parameters.
- *
- * If the default provider package provides an implementation of the - * specified CertStore type, an instance of - * CertStore containing that implementation is returned. If - * the requested type is not available in the default package, other - * packages are searched.
- *
- * The CertStore that is returned is initialized with the - * specified CertStoreParameters. The type of parameters - * needed may vary between different types of CertStores. - * Note that the specified CertStoreParameters object is - * cloned. - * - * @param type - * the name of the requested CertStore type - * @param params - * the initialization parameters (may be null) - * - * @return a CertStore object that implements the specified - * CertStore type - * - * @exception NoSuchAlgorithmException - * if the requested type is not available in the default - * provider package or any of the other provider packages - * that were searched - * @exception InvalidAlgorithmParameterException - * if the specified initialization parameters are - * inappropriate for this CertStore - */ - public static CertStore getInstance(String type, CertStoreParameters params) - throws InvalidAlgorithmParameterException, NoSuchAlgorithmException - { - try - { - CertUtil.Implementation imp = CertUtil.getImplementation( - "CertStore", type, (String)null, - new Class[] { CertStoreParameters.class }, - new Object[] { params }); - if (imp != null) - { - return new CertStore((CertStoreSpi)imp.getEngine(), imp - .getProvider(), type, params); - } - } - catch (NoSuchProviderException ex) - { - } - throw new NoSuchAlgorithmException("can't find type " + type); - } - - /** - * Returns a CertStore object that implements the specified - * CertStore type, as supplied by the specified provider and - * initialized with the specified parameters.
- *
- * The CertStore that is returned is initialized with the - * specified CertStoreParameters. The type of parameters - * needed may vary between different types of CertStores. - * Note that the specified CertStoreParameters object is - * cloned. - * - * @param type - * the requested CertStore type - * @param params - * the initialization parameters (may be null) - * @param provider - * the name of the provider - * - * @return a CertStore object that implements the specified - * type, as supplied by the specified provider - * - * @exception NoSuchAlgorithmException - * if the requested type is not available from the specified - * provider - * @exception InvalidAlgorithmParameterException - * if the specified initialization parameters are - * inappropriate for this CertStore - * @exception NoSuchProviderException - * if the provider has not been configured - * @exception IllegalArgumentException - * if the provider is null - */ - public static CertStore getInstance(String type, - CertStoreParameters params, String provider) - throws InvalidAlgorithmParameterException, - NoSuchAlgorithmException, NoSuchProviderException, - IllegalArgumentException - { - if (provider == null) - { - throw new IllegalArgumentException("provider must be non-null"); - } - - CertUtil.Implementation imp = CertUtil.getImplementation("CertStore", - type, provider, new Class[] { CertStoreParameters.class }, - new Object[] { params }); - if (imp != null) - { - return new CertStore((CertStoreSpi)imp.getEngine(), imp - .getProvider(), type, params); - } - throw new NoSuchAlgorithmException("can't find type " + type); - } - - /** - * Returns a CertStore object that implements the specified - * CertStore type, as supplied by the specified provider and - * initialized with the specified parameters. Note: the - * provider doesn't have to be registered.
- *
- * The CertStore that is returned is initialized with the - * specified CertStoreParameters. The type of parameters - * needed may vary between different types of CertStores. - * Note that the specified CertStoreParameters object is - * cloned. - * - * @param type - * the requested CertStore type - * @param params - * the initialization parameters (may be null) - * @param provider - * the provider - * - * @return a CertStore object that implements the specified - * type, as supplied by the specified provider - * - * @exception NoSuchAlgorithmException - * if the requested type is not available from the specified - * provider - * @exception InvalidAlgorithmParameterException - * if the specified initialization parameters are - * inappropriate for this CertStore - * @exception IllegalArgumentException - * if the provider is null - */ - public static CertStore getInstance(String type, - CertStoreParameters params, Provider provider) - throws NoSuchAlgorithmException, - InvalidAlgorithmParameterException, IllegalArgumentException - { - if (provider == null) - { - throw new IllegalArgumentException("provider must be non-null"); - } - CertUtil.Implementation imp = CertUtil.getImplementation("CertStore", - type, provider, new Class[] { CertStoreParameters.class }, - new Object[] { params }); - if (imp != null) - { - return new CertStore((CertStoreSpi)imp.getEngine(), provider, type, - params); - } - throw new NoSuchAlgorithmException("can't find type " + type); - } - - /** - * Returns the parameters used to initialize this CertStore. - * Note that the CertStoreParameters object is cloned before - * it is returned. - * - * @return the parameters used to initialize this CertStore - * (may be null) - */ - public final CertStoreParameters getCertStoreParameters() - { - return params; - } - - /** - * Returns the type of this CertStore. - * - * @return the type of this CertStore - */ - public final String getType() - { - return type; - } - - /** - * Returns the provider of this CertStore. - * - * @return the provider of this CertStore - */ - public final Provider getProvider() - { - return provider; - } - - /** - * Returns the default CertStore type as specified in the - * Java security properties file, or the string "LDAP" if no such - * property exists. The Java security properties file is located in the file - * named <JAVA_HOME>/lib/security/java.security, where - * <JAVA_HOME> refers to the directory where the SDK was installed.
- *
- * The default CertStore type can be used by applications - * that do not want to use a hard-coded type when calling one of the - * getInstance methods, and want to provide a default - * CertStore type in case a user does not specify its own.
- *
- * The default CertStore type can be changed by setting the - * value of the "certstore.type" security property (in the Java security - * properties file) to the desired type. - * - * @return the default CertStore type as specified in the - * Java security properties file, or the string "LDAP" if - * no such property exists. - */ - public static final String getDefaultType() - { - String defaulttype = null; - defaulttype = Security.getProperty("certstore.type"); - - if (defaulttype == null || defaulttype.length() <= 0) - { - return "LDAP"; - } - else - { - return defaulttype; - } - } -} - diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertStoreException.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertStoreException.java deleted file mode 100644 index 56c9fcfd2..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertStoreException.java +++ /dev/null @@ -1,187 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.io.PrintStream; -import java.io.PrintWriter; -import java.security.GeneralSecurityException; - -/** - * An exception indicating one of a variety of problems retrieving - * certificates and CRLs from a CertStore.
- *
- * A CertStoreException provides support for wrapping - * exceptions. The {@link #getCause getCause} method returns the throwable, - * if any, that caused this exception to be thrown.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see CertStore - **/ -public class CertStoreException extends GeneralSecurityException -{ - private Throwable cause; - - /** - * Creates a CertStoreException with null as - * its detail message. - */ - public CertStoreException() - { - super(); - } - - /** - * Creates a CertStoreException with the given detail - * message. A detail message is a String that describes this - * particular exception. - * - * @param messag - * the detail message - */ - public CertStoreException(String message) - { - super(message); - } - - /** - * Creates a CertStoreException with the specified detail - * message and cause. - * - * @param messag - * the detail message - * @param cause - * the cause (which is saved for later retrieval by the - * {@link #getCause getCause()} method). (A null - * value is permitted, and indicates that the cause is - * nonexistent or unknown.) - */ - public CertStoreException(String message, Throwable cause) - { - super(message); - this.cause = cause; - } - - /** - * Creates a CertStoreException that wraps the specified - * throwable. This allows any exception to be converted into a - * CertStoreException, while retaining information about the - * cause, which may be useful for debugging. The detail message is set to (cause==null ? null : cause.toString()) - * (which typically contains the class and detail message of cause). - * - * @param cause - * the cause (which is saved for later retrieval by the - * {@link #getCause getCause()} method). (A null - * value is permitted, and indicates that the cause is - * nonexistent or unknown.) - */ - public CertStoreException(Throwable cause) - { - this.cause = cause; - } - - /** - * Returns the detail message for this CertStoreException. - * - * @return the detail message, or null if neither the message - * nor cause were specified - */ - public String getMessage() - { - String message = super.getMessage(); - - if (message == null && cause == null) - { - return null; - } - - StringBuffer s = new StringBuffer(); - if (message != null) - { - s.append(message).append('\n'); - } - if (cause != null) - { - s.append("Cause:\n").append(cause.getMessage()); - } - return s.toString(); - } - - /** - * Returns the cause of this CertStoreException or - * null if the cause is nonexistent or unknown. - * - * @return the cause of this throwable or null if the cause - * is nonexistent or unknown. - */ - public Throwable getCause() - { - return cause; - } - - /** - * Returns a string describing this exception, including a description of - * the internal (wrapped) cause if there is one. - * - * @return a string representation of this CertStoreException - */ - public String toString() - { - String message = getMessage(); - if (message == null) - { - return ""; - } - - return message; - } - - /** - * Prints a stack trace to System.err, including the - * backtrace of the cause, if any. - */ - public void printStackTrace() - { - printStackTrace(System.err); - } - - /** - * Prints a stack trace to a PrintStream, including the - * backtrace of the cause, if any. - * - * @param ps - * the PrintStream to use for output - */ - public void printStackTrace(PrintStream ps) - { - super.printStackTrace(ps); - if (cause != null) - { - cause.printStackTrace(ps); - } - } - - /** - * Prints a stack trace to a PrintWriter, including the - * backtrace of the cause, if any. - * - * @param pw - * the PrintWriter to use for output - */ - public void printStackTrace(PrintWriter pw) - { - if (cause != null) - { - cause.printStackTrace(pw); - } - super.printStackTrace(pw); - if (cause != null) - { - cause.printStackTrace(pw); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertStoreParameters.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertStoreParameters.java deleted file mode 100644 index 0ec14ede3..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertStoreParameters.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.spongycastle.jce.cert; - -/** - * A specification of CertStore parameters.
- *
- * The purpose of this interface is to group (and provide type safety for) - * all CertStore parameter specifications. All - * CertStore parameter specifications must implement this - * interface.
- *
- * Typically, a CertStoreParameters object is passed as a parameter - * to one of the {@link CertStore#getInstance CertStore.getInstance} methods. - * The getInstance method returns a CertStore that - * is used for retrieving Certificates and CRLs. The - * CertStore that is returned is initialized with the specified - * parameters. The type of parameters needed may vary between different types - * of CertStores. - * - * @see CertStore#getInstance - **/ -public interface CertStoreParameters extends Cloneable -{ - /** - * Makes a copy of this CertStoreParameters.
- *
- * The precise meaning of "copy" may depend on the class of - * the CertStoreParameters object. A typical implementation - * performs a "deep copy" of this object, but this is not an absolute - * requirement. Some implementations may perform a "shallow copy" of some - * or all of the fields of this object.
- *
- * Note that the CertStore.getInstance methods make a copy - * of the specified CertStoreParameters. A deep copy - * implementation of clone is safer and more robust, as it - * prevents the caller from corrupting a shared CertStore by - * subsequently modifying the contents of its initialization parameters. - * However, a shallow copy implementation of clone is more - * appropriate for applications that need to hold a reference to a - * parameter contained in the CertStoreParameters. For example, - * a shallow copy clone allows an application to release the resources of - * a particular CertStore initialization parameter immediately, - * rather than waiting for the garbage collection mechanism. This should - * be done with the utmost care, since the CertStore may still - * be in use by other threads.
- *
- * Each subclass should state the precise behavior of this method so - * that users and developers know what to expect. - * - * @return a copy of this CertStoreParameters - */ - public Object clone(); -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertStoreSpi.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertStoreSpi.java deleted file mode 100644 index fd9fe6a36..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertStoreSpi.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.security.InvalidAlgorithmParameterException; -import java.util.Collection; - -/** - * The Service Provider Interface (SPI) - * for the {@link CertStore CertStore} class. All CertStore - * implementations must include a class (the SPI class) that extends - * this class (CertStoreSpi), provides a constructor with - * a single argument of type CertStoreParameters, and implements - * all of its methods. In general, instances of this class should only be - * accessed through the CertStore class. - * For details, see the Java Cryptography Architecture.
- *
- * Concurrent Access
- *
- * The public methods of all CertStoreSpi objects must be - * thread-safe. That is, multiple threads may concurrently invoke these - * methods on a single CertStoreSpi object (or more than one) - * with no ill effects. This allows a CertPathBuilder to search - * for a CRL while simultaneously searching for further certificates, for - * instance.
- *
- * Simple CertStoreSpi implementations will probably ensure - * thread safety by adding a synchronized keyword to their - * engineGetCertificates and engineGetCRLs methods. - * More sophisticated ones may allow truly concurrent access. - **/ -public abstract class CertStoreSpi - extends Object -{ - - /** - * The sole constructor. - * - * @param params the initialization parameters (may be null) - * @exception InvalidAlgorithmParameterException if the initialization - * parameters are inappropriate for this CertStoreSpi - */ - public CertStoreSpi(CertStoreParameters params) - throws InvalidAlgorithmParameterException {} - - /** - * Returns a Collection of Certificates that - * match the specified selector. If no Certificates - * match the selector, an empty Collection will be returned.
- *
- * For some CertStore types, the resulting - * Collection may not contain all of the - * Certificates that match the selector. For instance, - * an LDAP CertStore may not search all entries in the - * directory. Instead, it may just search entries that are likely to - * contain the Certificates it is looking for.
- *
- * Some CertStore implementations (especially LDAP - * CertStores) may throw a CertStoreException - * unless a non-null CertSelector is provided that includes - * specific criteria that can be used to find the certificates. Issuer - * and/or subject names are especially useful criteria. - * - * @param selector A CertSelector used to select which - * Certificates should be returned. Specify null - * to return all Certificates (if supported). - * - * @return A Collection of Certificates that - * match the specified selector (never null) - * - * @exception CertStoreException if an exception occurs - */ - public abstract Collection engineGetCertificates(CertSelector selector) - throws CertStoreException; - - /** - * Returns a Collection of CRLs that - * match the specified selector. If no CRLs - * match the selector, an empty Collection will be returned.
- *
- * For some CertStore types, the resulting - * Collection may not contain all of the - * CRLs that match the selector. For instance, - * an LDAP CertStore may not search all entries in the - * directory. Instead, it may just search entries that are likely to - * contain the CRLs it is looking for.
- *
- * Some CertStore implementations (especially LDAP - * CertStores) may throw a CertStoreException - * unless a non-null CRLSelector is provided that includes - * specific criteria that can be used to find the CRLs. Issuer names - * and/or the certificate to be checked are especially useful. - * - * @param selector A CRLSelector used to select which - * CRLs should be returned. Specify null - * to return all CRLs (if supported). - * - * @return A Collection of CRLs that - * match the specified selector (never null) - * - * @exception CertStoreException if an exception occurs - */ - public abstract Collection engineGetCRLs(CRLSelector selector) - throws CertStoreException; -} - diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertUtil.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertUtil.java deleted file mode 100644 index 60c5e8b08..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertUtil.java +++ /dev/null @@ -1,556 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.Security; - -import org.spongycastle.asn1.ASN1Object; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DERIA5String; -import org.spongycastle.asn1.DEROutputStream; -import org.spongycastle.asn1.OIDTokenizer; -import org.spongycastle.asn1.x509.X509Name; -import org.spongycastle.util.Strings; - -class CertUtil -{ - static class Implementation - { - Object engine; - Provider provider; - - Implementation( - Object engine, - Provider provider) - { - this.engine = engine; - this.provider = provider; - } - - Object getEngine() - { - return engine; - } - - Provider getProvider() - { - return provider; - } - } - - /** - * see if we can find an algorithm (or its alias and what it represents) in - * the property table for the given provider. - * - * @return null if no algorithm found, an Implementation if it is. - */ - static Implementation getImplementation( - String baseName, - String algorithm, - Provider prov) - { - if (prov == null) - { - Provider[] provider = Security.getProviders(); - - // - // search every provider looking for the algorithm we want. - // - for (int i = 0; i != provider.length; i++) - { - Implementation imp = getImplementation(baseName, algorithm, provider[i]); - if (imp != null) - { - return imp; - } - } - - return null; - } - - String alias; - - while ((alias = prov.getProperty("Alg.Alias." + baseName + "." + algorithm)) != null) - { - algorithm = alias; - } - - String className = prov.getProperty(baseName + "." + algorithm); - - if (className != null) - { - try - { - return new Implementation(Class.forName(className).newInstance(), prov); - } - catch (ClassNotFoundException e) - { - throw new IllegalStateException( - "algorithm " + algorithm + " in provider " + prov.getName() + " but no class found!"); - } - catch (Exception e) - { - throw new IllegalStateException( - "algorithm " + algorithm + " in provider " + prov.getName() + " but class inaccessible: " + e.toString()); - } - } - - return null; - } - - /** - * return an implementation for a given algorithm/provider. - * If the provider is null, we grab the first avalaible who has the required algorithm. - * - * @return null if no algorithm found, an Implementation if it is. - * @exception NoSuchProviderException if a provider is specified and not found. - */ - static Implementation getImplementation( - String baseName, - String algorithm, - String provider) - throws NoSuchProviderException - { - if (provider == null) - { - Provider[] prov = Security.getProviders(); - - // - // search every provider looking for the algorithm we want. - // - for (int i = 0; i != prov.length; i++) - { - Implementation imp = getImplementation(baseName, algorithm, prov[i]); - if (imp != null) - { - return imp; - } - } - } - else - { - Provider prov = Security.getProvider(provider); - - if (prov == null) - { - throw new NoSuchProviderException("Provider " + provider + " not found"); - } - - return getImplementation(baseName, algorithm, prov); - } - - return null; - } - - /** - * see if we can find an algorithm (or its alias and what it represents) in - * the property table for the given provider. - * - * @return null if no algorithm found, an Implementation if it is. - */ - static Implementation getImplementation(String baseName, String algorithm, - Provider prov, Class[] ctorparamtype, Object[] ctorparam) - throws InvalidAlgorithmParameterException - { - String alias; - - while ((alias = prov.getProperty("Alg.Alias." + baseName + "." - + algorithm)) != null) - { - algorithm = alias; - } - - String className = prov.getProperty(baseName + "." + algorithm); - - if (className != null) - { - try - { - return new Implementation(Class.forName(className) - .getConstructor(ctorparamtype).newInstance(ctorparam), - prov); - } - catch (ClassNotFoundException e) - { - throw new IllegalStateException("algorithm " + algorithm - + " in provider " + prov.getName() - + " but no class found!"); - } - catch (Exception e) - { - if (e instanceof InvalidAlgorithmParameterException) - { - throw (InvalidAlgorithmParameterException)e; - } - - throw new IllegalStateException("algorithm " + algorithm - + " in provider " + prov.getName() - + " but class inaccessible!"); - } - } - - return null; - } - - /** - * return an implementation for a given algorithm/provider. If the provider - * is null, we grab the first avalaible who has the required algorithm. - * - * @return null if no algorithm found, an Implementation if it is. - * - * @exception NoSuchProviderException - * if a provider is specified and not found. - */ - static Implementation getImplementation(String baseName, String algorithm, - String provider, Class[] ctorparamtype, Object[] ctorparam) - throws NoSuchProviderException, InvalidAlgorithmParameterException - { - if (provider == null) - { - Provider[] prov = Security.getProviders(); - - // - // search every provider looking for the algorithm we want. - // - for (int i = 0; i != prov.length; i++) - { - Implementation imp = getImplementation(baseName, algorithm, - prov[i], ctorparamtype, ctorparam); - if (imp != null) - { - return imp; - } - } - } - else - { - Provider prov = Security.getProvider(provider); - - if (prov == null) - { - throw new NoSuchProviderException("Provider " + provider - + " not found"); - } - - return getImplementation(baseName, algorithm, prov, ctorparamtype, - ctorparam); - } - - return null; - } - - static byte[] parseGeneralName(int type, String data) throws IOException - { - byte[] encoded = null; - - switch (type) - { - case 0: - throw new IOException( - "unable to parse OtherName String representation"); - case 1: - encoded = parseRfc822(data.trim()); - break; - case 2: - encoded = parseDNSName(data.trim()); - break; - case 3: - throw new IOException( - "unable to parse ORAddress String representation"); - case 4: - encoded = parseX509Name(data.trim()); - break; - case 5: - throw new IOException( - "unable to parse EDIPartyName String representation"); - case 6: - encoded = parseURI(data.trim()); - break; - case 7: - encoded = parseIP(data.trim()); - break; - case 8: - encoded = parseOID(data.trim()); - break; - default: - throw new IOException( - "unable to parse unkown type String representation"); - } - return encoded; - } - - /** - * Check the format of an OID.
- * Throw an IOException if the first component is not 0, 1 or 2 or the - * second component is greater than 39.
- *
- * User {@link org.spongycastle.asn1.OIDTokenizer OIDTokenizer} - * - * @param the - * OID to be checked. - * - * @exception IOException - * if the first component is not 0, 1 or 2 or the second - * component is greater than 39. - */ - static byte[] parseOID(String oid) throws IOException - { - OIDTokenizer tokenizer = new OIDTokenizer(oid); - String token; - if (!tokenizer.hasMoreTokens()) - { - throw new IOException("OID contains no tokens"); - } - token = tokenizer.nextToken(); - if (token == null) - { - throw new IOException("OID contains no tokens"); - } - try - { - int test = (Integer.valueOf(token)).intValue(); - if (test < 0 || test > 2) - { - throw new IOException("first token is not >= 0 and <=2"); - } - if (!tokenizer.hasMoreTokens()) - { - throw new IOException("OID contains only one token"); - } - token = tokenizer.nextToken(); - if (token == null) - { - throw new IOException("OID contains only one token"); - } - test = (Integer.valueOf(token)).intValue(); - if (test < 0 || test > 39) - { - throw new IOException("secon token is not >= 0 and <=39"); - } - } - catch (NumberFormatException ex) - { - throw new IOException("token: " + token + ": " + ex.toString()); - } - ASN1Object derData = new ASN1ObjectIdentifier(oid); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - DEROutputStream derOutStream = new DEROutputStream(outStream); - derOutStream.writeObject(derData); - derOutStream.close(); - return outStream.toByteArray(); - } - - /** - * Parse the given IPv4 or IPv6 into DER encoded byte array representation. - * - * @param the - * IP in well known String format - * - * @return the IP as byte array - * - * @exception IOException - * if the String could not be parsed - */ - private static byte[] parseIP(String data) throws IOException - { - byte[] encoded = parseIPv4(data); - - if (encoded == null) - { - encoded = parseIPv6(data); - } - - if (encoded == null) - { - throw new IOException( - "unable to parse IP to DER encoded byte array"); - } - - return encoded; - } - - /** - * Parse the given IPv4 into DER encoded byte array representation. - * - * @param the - * IP in well known String format - * - * @return the IP as byte array or null if not parseable - */ - private static byte[] parseIPv4(String data) - { - if (data.length() == 0) - { - return null; - } - - int octet; - int octets = 0; - byte[] dst = new byte[4]; - - int pos = 0; - int start = 0; - while (start < data.length() - && (pos = data.indexOf('.', start)) > start && pos - start > 3) - { - try - { - octet = (Integer.valueOf(data.substring(start, pos - start))) - .intValue(); - } - catch (NumberFormatException ex) - { - return null; - } - if (octet < 0 || octet > 255) - { - return null; - } - dst[octets++] = (byte)(octet & 0xff); - - start = pos + 1; - } - - if (octets < 4) - { - return null; - } - - return dst; - } - - /** - * Parse the given IPv6 into DER encoded byte array representation.
- *
- * TODO: implement this - * - * @param the - * IP in well known String format - * - * @return the IP as byte array or null if not parseable - */ - private static byte[] parseIPv6(String data) - { - return null; - } - - /** - * Parse the given URI into DER encoded byte array representation. - * - * @param the - * URI in well known String format - * - * @return the URI as byte array - * - * @exception IOException - * if the String could not be parsed - */ - private static byte[] parseURI(String data) throws IOException - { - // TODO do parsing test - ASN1Object derData = new DERIA5String(data); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - DEROutputStream derOutStream = new DEROutputStream(outStream); - derOutStream.writeObject(derData); - derOutStream.close(); - return outStream.toByteArray(); - } - - /** - * Parse the given rfc822 addr-spec into DER encoded byte array - * representation. - * - * @param the - * rfc822 addr-spec in well known String format - * - * @return the rfc822 addr-spec as byte array - * - * @exception IOException - * if the String could not be parsed - */ - private static byte[] parseRfc822(String data) throws IOException - { - int tmpInt = data.indexOf('@'); - if (tmpInt < 0 || tmpInt >= data.length() - 1) - { - throw new IOException("wrong format of rfc822Name:" + data); - } - // TODO more test for illegal charateers - ASN1Object derData = new DERIA5String(data); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - DEROutputStream derOutStream = new DEROutputStream(outStream); - derOutStream.writeObject(derData); - derOutStream.close(); - return outStream.toByteArray(); - } - - /** - * Parse the given DNS name into DER encoded byte array representation. The - * String must be in den preffered name syntax as defined in RFC 1034. - * - * @param the - * DNS name in well known String format - * - * @return the DNS name as byte array - * - * @exception IOException - * if the String could not be parsed - */ - private static byte[] parseDNSName(String data) throws IOException - { - // TODO more test for illegal charateers - ASN1Object derData = new DERIA5String(data); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - DEROutputStream derOutStream = new DEROutputStream(outStream); - derOutStream.writeObject(derData); - derOutStream.close(); - return outStream.toByteArray(); - } - - /** - * Parse the given X.509 name into DER encoded byte array representation. - * - * @param the - * X.509 name in well known String format - * - * @return the X.509 name as byte array - * - * @exception IOException - * if the String could not be parsed - */ - private static byte[] parseX509Name(String data) throws IOException - { - // TODO more test for illegal charateers - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - DEROutputStream derOutStream = new DEROutputStream(outStream); - derOutStream.writeObject(new X509Name(trimX509Name(data))); - derOutStream.close(); - return outStream.toByteArray(); - } - - /** - * Returns the given name converted to upper case and all multi spaces squezed - * to one space. - **/ - static String trimX509Name(String name) - { - String data = Strings.toUpperCase(name.trim()); - int pos; - while ((pos = data.indexOf(" ")) >= 0) - { - data = data.substring(0, pos) + data.substring(pos + 1); - } - while ((pos = data.indexOf(" =")) >= 0) - { - data = data.substring(0, pos) + data.substring(pos + 1); - } - while ((pos = data.indexOf("= ")) >= 0) - { - data = data.substring(0, pos + 1) + data.substring(pos + 2); - } - return data; - } -} \ No newline at end of file diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertificateFactory.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertificateFactory.java deleted file mode 100644 index a1ead1a63..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertificateFactory.java +++ /dev/null @@ -1,183 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.io.InputStream; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.cert.CRL; -import java.security.cert.CRLException; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -/** - **/ -public class CertificateFactory -{ - private CertificateFactorySpi certFacSpi; - private Provider provider; - private String type; - - protected CertificateFactory( - CertificateFactorySpi certFacSpi, - Provider provider, - String type) - { - this.certFacSpi = certFacSpi; - this.provider = provider; - this.type = type; - } - - public final CRL generateCRL(InputStream inStream) - throws CRLException - { - return certFacSpi.engineGenerateCRL(inStream); - } - - public final Collection generateCRLs(InputStream inStream) - throws CRLException - { - return certFacSpi.engineGenerateCRLs(inStream); - } - - public final Certificate generateCertificate(InputStream inStream) - throws CertificateException - { - return certFacSpi.engineGenerateCertificate(inStream); - } - - public final /*Sk13 Vector*/ Collection generateCertificates(InputStream inStream) - throws CertificateException - { - return certFacSpi.engineGenerateCertificates(inStream); - } - - /** - * Returns an iteration of the CertPath encodings supported - * by this certificate factory, with the default encoding first. See - * Appendix A in the - * Java Certification Path API Programmer's Guide for information about - * standard encoding names and their formats.
- *
- * Attempts to modify the returned Iterator via its - * remove method result in an - * UnsupportedOperationException. - * - * @return an Iterator over the names of the supported - * CertPath encodings (as Strings) - */ - public final Iterator getCertPathEncodings() - { - return certFacSpi.engineGetCertPathEncodings(); - } - - /** - * Generates a CertPath object and initializes it with - * the data read from the InputStream inStream. The data - * is assumed to be in the default encoding. The name of the default - * encoding is the first element of the Iterator returned by - * the {@link #getCertPathEncodings getCertPathEncodings} method. - * - * @param inStream an InputStream containing the data - * - * @return a CertPath initialized with the data from the - * InputStream - * - * @exception CertificateException if an exception occurs while decoding - */ - public final CertPath generateCertPath(InputStream inStream) - throws CertificateException - { - return certFacSpi.engineGenerateCertPath(inStream); - } - - /** - * Generates a CertPath object and initializes it with - * the data read from the InputStream inStream. The data - * is assumed to be in the specified encoding. See Appendix A in the - *
- * Java Certification Path API Programmer's Guide - * for information about standard encoding names and their formats. - * - * @param inStream an InputStream containing the data - * @param encoding the encoding used for the data - * - * @return a CertPath initialized with the data from the - * InputStream - * - * @exception CertificateException if an exception occurs while decoding or - * the encoding requested is not supported - */ - public final CertPath generateCertPath(InputStream inStream, String encoding) - throws CertificateException - { - return certFacSpi.engineGenerateCertPath(inStream, encoding); - } - - /** - * Generates a CertPath object and initializes it with - * a List of Certificates.
- *
- * The certificates supplied must be of a type supported by the - * CertificateFactory. They will be copied out of the supplied - * List object. - * - * @param certificates a List of Certificates - * - * @return a CertPath initialized with the supplied list of - * certificates - * - * @exception CertificateException if an exception occurs - */ - public final CertPath generateCertPath(List certificates) - throws CertificateException - { - return certFacSpi.engineGenerateCertPath(certificates); - } - - public static final CertificateFactory getInstance(String type) - throws CertificateException - { - try - { - CertUtil.Implementation imp = CertUtil.getImplementation("CertificateFactory", type, (String)null); - - if (imp != null) - { - return new CertificateFactory((CertificateFactorySpi)imp.getEngine(), imp.getProvider(), type); - } - - throw new CertificateException("can't find type " + type); - } - catch (NoSuchProviderException e) - { - throw new CertificateException(type + " not found"); - } - } - - public static final CertificateFactory getInstance( - String type, - String provider) - throws CertificateException, NoSuchProviderException - { - CertUtil.Implementation imp = CertUtil.getImplementation("CertificateFactory", type, provider); - - if (imp != null) - { - return new CertificateFactory((CertificateFactorySpi)imp.getEngine(), imp.getProvider(), type); - } - - throw new CertificateException("can't find type " + type); - } - - public final Provider getProvider() - { - return provider; - } - - public final String getType() - { - return type; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertificateFactorySpi.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertificateFactorySpi.java deleted file mode 100644 index 1bed77211..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CertificateFactorySpi.java +++ /dev/null @@ -1,99 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.io.InputStream; -import java.security.cert.CertificateException; -import java.util.Iterator; -import java.util.List; - -public abstract class CertificateFactorySpi - extends java.security.cert.CertificateFactorySpi -{ - public CertificateFactorySpi() - { - } - - /** - * Returns an iteration of the CertPath encodings supported - * by this certificate factory, with the default encoding first. See - * Appendix A in the - * Java Certification Path API Programmer's Guide - * for information about standard encoding names.
- *
- * Attempts to modify the returned Iterator via its - * remove method result in an - * UnsupportedOperationException.
- *
- * This method was added to version 1.4 of the Java 2 Platform - * Standard Edition. In order to maintain backwards compatibility with - * existing service providers, this method cannot be abstract - * and by default throws an UnsupportedOperationException. - * - * @return an Iterator over the names of the supported - * CertPath encodings (as Strings) - * - * @exception UnsupportedOperationException if the method is not supported - */ - public abstract Iterator engineGetCertPathEncodings(); - - /** - * Generates a CertPath object and initializes it with - * the data read from the InputStream inStream. The data - * is assumed to be in the default encoding. - * - * @param inStream an InputStream containing the data - * - * @return a CertPath initialized with the data from the - * InputStream - * - * @exception CertificateException if an exception occurs while decoding - */ - public abstract CertPath engineGenerateCertPath(InputStream inStream) - throws CertificateException; - - /** - * Generates a CertPath object and initializes it with - * the data read from the InputStream inStream. The data - * is assumed to be in the specified encoding.
- *
- * This method was added to version 1.4 of the Java 2 Platform - * Standard Edition. In order to maintain backwards compatibility with - * existing service providers, this method cannot be abstract - * and by default throws an UnsupportedOperationException. - * - * @param inStream an InputStream containing the data - * @param encoding the encoding used for the data - * - * @return a CertPath initialized with the data from the - * InputStream - * - * @exception CertificateException if an exception occurs while decoding or - * the encoding requested is not supported - * @exception UnsupportedOperationException if the method is not supported - */ - public abstract CertPath engineGenerateCertPath(InputStream inStream, String encoding) - throws CertificateException; - - /** - * Generates a CertPath object and initializes it with - * a List of Certificates.
- *
- * The certificates supplied must be of a type supported by the - * CertificateFactory. They will be copied out of the supplied - * List object.
- *
- * This method was added to version 1.4 of the Java 2 Platform - * Standard Edition. In order to maintain backwards compatibility with - * existing service providers, this method cannot be abstract - * and by default throws an UnsupportedOperationException. - * - * @param certificates a List of Certificates - * - * @return a CertPath initialized with the supplied list of - * certificates - * - * @exception CertificateException if an exception occurs - * @exception UnsupportedOperationException if the method is not supported - */ - public abstract CertPath engineGenerateCertPath(List certificates) - throws CertificateException; -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CollectionCertStoreParameters.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CollectionCertStoreParameters.java deleted file mode 100644 index 1692fefa8..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/CollectionCertStoreParameters.java +++ /dev/null @@ -1,124 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.util.ArrayList; -import java.util.Collection; - -/** - * Parameters used as input for the Collection CertStore - * algorithm.
- *
- * This class is used to provide necessary configuration parameters - * to implementations of the Collection CertStore - * algorithm. The only parameter included in this class is the - * Collection from which the CertStore will - * retrieve certificates and CRLs.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see java.util.Collection - * @see CertStore - **/ -public class CollectionCertStoreParameters implements CertStoreParameters -{ - private Collection collection; - - /** - * Creates an instance of CollectionCertStoreParameters which - * will allow certificates and CRLs to be retrieved from the specified - * Collection. If the specified Collection - * contains an object that is not a Certificate or - * CRL, that object will be ignored by the Collection - * CertStore.
- *
- * The Collection is not copied. Instead, a reference - * is used. This allows the caller to subsequently add or remove - * Certificates or CRLs from the - * Collection, thus changing the set of - * Certificates or CRLs available to the - * Collection CertStore. The Collection - * CertStore will not modify the contents of the - * Collection.
- *
- * If the Collection will be modified by one thread while - * another thread is calling a method of a Collection CertStore - * that has been initialized with this Collection, the - * Collection must have fail-fast iterators. - * - * @param collection - * a Collection of Certificates - * and CRLs - * - * @exception NullPointerException - * if collection is null - */ - public CollectionCertStoreParameters(Collection collection) - { - if (collection == null) - { - throw new NullPointerException("collection must be non-null"); - } - this.collection = collection; - } - - /** - * Creates an instance of CollectionCertStoreParameters with - * the an empty Collection. - */ - public CollectionCertStoreParameters() - { - collection = new ArrayList(); - } - - /** - * Returns the Collection from which Certificates - * and CRLs are retrieved. This is not a copy of the - * Collection, it is a reference. This allows the caller to - * subsequently add or remove Certificates or - * CRLs from the Collection. - * - * @return the Collection (never null) - */ - public Collection getCollection() - { - return collection; - } - - /** - * Returns a copy of this object. Note that only a reference to the - * Collection is copied, and not the contents. - * - * @return the copy - */ - public Object clone() - { - try - { - return super.clone(); - } - catch (CloneNotSupportedException e) - { - /* Cannot happen */ - throw new InternalError(e.toString()); - } - } - - /** - * Returns a formatted string describing the parameters. - * - * @return a formatted string describing the parameters - */ - public String toString() - { - StringBuffer s = new StringBuffer(); - s.append("CollectionCertStoreParameters: [\n collections:\n"); - s.append(getCollection()); - s.append("\n]"); - return s.toString(); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/LDAPCertStoreParameters.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/LDAPCertStoreParameters.java deleted file mode 100644 index 306c66610..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/LDAPCertStoreParameters.java +++ /dev/null @@ -1,138 +0,0 @@ -package org.spongycastle.jce.cert; - -/** - * Parameters used as input for the LDAP CertStore algorithm.
- *
- * This class is used to provide necessary configuration parameters (server - * name and port number) to implementations of the LDAP CertStore - * algorithm.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see CertStore - **/ -public class LDAPCertStoreParameters implements CertStoreParameters -{ - private static final int LDAP_DEFAULT_PORT = 389; - - /** - * the port number of the LDAP server - */ - private String serverName; - - /** - * the DNS name of the LDAP server - */ - private int port; - - /** - * Creates an instance of LDAPCertStoreParameters with the - * default parameter values (server name "localhost", port 389). - */ - public LDAPCertStoreParameters() - { - this("localhost", LDAP_DEFAULT_PORT); - } - - /** - * Creates an instance of LDAPCertStoreParameters with the - * specified server name and a default port of 389. - * - * @param serverName - * the DNS name of the LDAP server - * - * @exception NullPointerException - * if serverName is null - */ - public LDAPCertStoreParameters(String serverName) - { - this(serverName, LDAP_DEFAULT_PORT); - } - - /** - * Creates an instance of LDAPCertStoreParameters with the - * specified parameter values. - * - * @param serverName - * the DNS name of the LDAP server - * @param port - * the port number of the LDAP server - * - * @exception NullPointerException - * if serverName is null - */ - public LDAPCertStoreParameters(String serverName, int port) - { - if (serverName == null) - { - throw new NullPointerException("serverName must be non-null"); - } - this.serverName = serverName; - this.port = port; - } - - /** - * Returns the DNS name of the LDAP server. - * - * @return the name (not null) - */ - public String getServerName() - { - return serverName; - } - - /** - * Returns the port number of the LDAP server. - * - * @return the port number - */ - public int getPort() - { - return port; - } - - /** - * Returns a copy of this object. Changes to the copy will not affect the - * original and vice versa.
- *
- * Note: this method currently performs a shallow copy of the object (simply - * calls Object.clone()). This may be changed in a future - * revision to perform a deep copy if new parameters are added that should - * not be shared. - * - * @return the copy - */ - public Object clone() - { - try - { - return super.clone(); - } - catch (CloneNotSupportedException e) - { - /* Cannot happen */ - throw new InternalError(e.toString()); - } - } - - /** - * Returns a formatted string describing the parameters. - * - * @return a formatted string describing the parameters - */ - public String toString() - { - StringBuffer sb = new StringBuffer(); - sb.append("LDAPCertStoreParameters: [\n"); - sb.append(" serverName: ").append(serverName).append('\n'); - sb.append(" port: ").append(port).append('\n'); - sb.append(']'); - return sb.toString(); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXBuilderParameters.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXBuilderParameters.java deleted file mode 100644 index 79136ad39..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXBuilderParameters.java +++ /dev/null @@ -1,190 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidParameterException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.util.Set; - -/** - * Parameters used as input for the PKIX CertPathBuilder - * algorithm.
- *
- * A PKIX CertPathBuilder uses these parameters to {@link - * CertPathBuilder#build build} a CertPath which has been - * validated according to the PKIX certification path validation algorithm.
- *
- * To instantiate a PKIXBuilderParameters object, an - * application must specify one or more most-trusted CAs as defined by - * the PKIX certification path validation algorithm. The most-trusted CA - * can be specified using one of two constructors. An application - * can call {@link #PKIXBuilderParameters(Set, CertSelector) - * PKIXBuilderParameters(Set, CertSelector)}, specifying a - * Set of TrustAnchor objects, each of which - * identifies a most-trusted CA. Alternatively, an application can call - * {@link #PKIXBuilderParameters(KeyStore, CertSelector) - * PKIXBuilderParameters(KeyStore, CertSelector)}, specifying a - * KeyStore instance containing trusted certificate entries, each - * of which will be considered as a most-trusted CA.
- *
- * In addition, an application must specify constraints on the target - * certificate that the CertPathBuilder will attempt - * to build a path to. The constraints are specified as a - * CertSelector object. These constraints should provide the - * CertPathBuilder with enough search criteria to find the target - * certificate. Minimal criteria for an X509Certificate usually - * include the subject name and/or one or more subject alternative names. - * If enough criteria is not specified, the CertPathBuilder - * may throw a CertPathBuilderException.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see CertPathBuilder - **/ -public class PKIXBuilderParameters extends PKIXParameters -{ - private int maxPathLength = 5; - - /** - * Creates an instance of PKIXBuilderParameters with the - * specified Set of most-trusted CAs. Each element of the set - * is a {@link TrustAnchor TrustAnchor}.
- *
- * Note that the Set is copied to protect against subsequent - * modifications. - * - * @param trustAnchors - * a Set of TrustAnchors - * @param targetConstraints - * a CertSelector specifying the constraints on - * the target certificate - * - * @exception InvalidAlgorithmParameterException - * if trustAnchors is empty - * (trustAnchors.isEmpty() == true) - * @exception NullPointerException - * if trustAnchors is null - * @exception ClassCastException - * if any of the elements of trustAnchors are - * not of type java.security.cert.TrustAnchor - */ - public PKIXBuilderParameters( - Set trustAnchors, - CertSelector targetConstraints) - throws InvalidAlgorithmParameterException - { - super(trustAnchors); - setTargetCertConstraints(targetConstraints); - } - - /** - * Creates an instance of PKIXBuilderParameters that - * populates the set of most-trusted CAs from the trusted certificate - * entries contained in the specified KeyStore. Only - * keystore entries that contain trusted X509Certificates - * are considered; all other certificate types are ignored. - * - * @param keystore - * a KeyStore from which the set of most-trusted - * CAs will be populated - * @param targetConstraints - * a CertSelector specifying the constraints on - * the target certificate - * - * @exception KeyStoreException - * if keystore has not been initialized - * @exception InvalidAlgorithmParameterException - * if keystore does not contain at least one - * trusted certificate entry - * @exception NullPointerException - * if keystore is null - */ - public PKIXBuilderParameters( - KeyStore keystore, - CertSelector targetConstraints) throws KeyStoreException, - InvalidAlgorithmParameterException - { - super(keystore); - setTargetCertConstraints(targetConstraints); - } - - /** - * Sets the value of the maximum number of non-self-issued intermediate - * certificates that may exist in a certification path. A certificate is - * self-issued if the DNs that appear in the subject and issuer fields are - * identical and are not empty. Note that the last certificate in a - * certification path is not an intermediate certificate, and is not - * included in this limit. Usually the last certificate is an end entity - * certificate, but it can be a CA certificate. A PKIX - * CertPathBuilder instance must not build paths longer than - * the length specified.
- *
- * A value of 0 implies that the path can only contain a single certificate. - * A value of -1 implies that the path length is unconstrained (i.e. there - * is no maximum). The default maximum path length, if not specified, is 5. - * Setting a value less than -1 will cause an exception to be thrown.
- *
- * If any of the CA certificates contain the - * BasicConstraintsExtension, the value of the - * pathLenConstraint field of the extension overrides the - * maximum path length parameter whenever the result is a certification path - * of smaller length. - * - * @param maxPathLength - * the maximum number of non-self-issued intermediate - * certificates that may exist in a certification path - * - * @exception InvalidParameterException - * if maxPathLength is set to a value less - * than -1 - * - * @see #getMaxPathLength - */ - public void setMaxPathLength(int maxPathLength) - { - if (maxPathLength < -1) - { - throw new InvalidParameterException( - "the maximum path length parameter can not be less than -1"); - } - this.maxPathLength = maxPathLength; - } - - /** - * Returns the value of the maximum number of intermediate non-self-issued - * certificates that may exist in a certification path. See the - * {@link #setMaxPathLength} method for more details. - * - * @return the maximum number of non-self-issued intermediate certificates - * that may exist in a certification path, or -1 if there is no - * limit - * - * @see #setMaxPathLength - */ - public int getMaxPathLength() - { - return maxPathLength; - } - - /** - * Returns a formatted string describing the parameters. - * - * @return a formatted string describing the parameters - */ - public String toString() - { - StringBuffer s = new StringBuffer(); - s.append("PKIXBuilderParameters [\n"); - s.append(super.toString()); - s.append(" Maximum Path Length: "); - s.append(getMaxPathLength()); - s.append("\n]\n"); - return s.toString(); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXCertPathBuilderResult.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXCertPathBuilderResult.java deleted file mode 100644 index 0288b8506..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXCertPathBuilderResult.java +++ /dev/null @@ -1,103 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.security.PublicKey; - -/** - * This class represents the successful result of the PKIX certification - * path builder algorithm. All certification paths that are built and - * returned using this algorithm are also validated according to the PKIX - * certification path validation algorithm.
- *
- * Instances of PKIXCertPathBuilderResult are returned by - * the build method of CertPathBuilder - * objects implementing the PKIX algorithm.
- *
- * All PKIXCertPathBuilderResult objects contain the - * certification path constructed by the build algorithm, the - * valid policy tree and subject public key resulting from the build - * algorithm, and a TrustAnchor describing the certification - * authority (CA) that served as a trust anchor for the certification path.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see CertPathBuilderResult - * - **/ -public class PKIXCertPathBuilderResult extends PKIXCertPathValidatorResult - implements CertPathBuilderResult -{ - private CertPath certPath; - - /** - * Creates an instance of PKIXCertPathBuilderResult - * containing the specified parameters. - * - * @param certPath - * the validated CertPath - * @param trustAnchor - * a TrustAnchor describing the CA that served as - * a trust anchor for the certification path - * @param policyTree - * the immutable valid policy tree, or null if - * there are no valid policies - * @param subjectPublicKey - * the public key of the subject - * - * @exception NullPointerException - * if the certPath, trustAnchor - * or subjectPublicKey parameters are - * null - */ - public PKIXCertPathBuilderResult( - CertPath certPath, - TrustAnchor trustAnchor, - PolicyNode policyTree, - PublicKey subjectPublicKey) - { - super(trustAnchor, policyTree, subjectPublicKey); - if (certPath == null) - { - throw new NullPointerException("certPath must be non-null"); - } - this.certPath = certPath; - } - - /** - * Returns the built and validated certification path. The - * CertPath object does not include the trust anchor. - * Instead, use the {@link #getTrustAnchor() getTrustAnchor()} method to - * obtain the TrustAnchor that served as the trust anchor for - * the certification path. - * - * @return the built and validated CertPath (never - * null) - */ - public CertPath getCertPath() - { - return certPath; - } - - /** - * Return a printable representation of this - * PKIXCertPathBuilderResult. - * - * @return a String describing the contents of this - * PKIXCertPathBuilderResult - */ - public String toString() - { - StringBuffer s = new StringBuffer(); - s.append("PKIXCertPathBuilderResult: [\n"); - s.append(" Certification Path: ").append(getCertPath()).append('\n'); - s.append(" Trust Anchor: ").append(getTrustAnchor()).append('\n'); - s.append(" Policy Tree: ").append(getPolicyTree()).append('\n'); - s.append(" Subject Public Key: ").append(getPublicKey()).append("\n]"); - return s.toString(); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXCertPathChecker.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXCertPathChecker.java deleted file mode 100644 index 07c71ca27..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXCertPathChecker.java +++ /dev/null @@ -1,163 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.security.cert.Certificate; -import java.util.Collection; -import java.util.Set; - -/** - * An abstract class that performs one or more checks on an - * X509Certificate.
- *
- * A concrete implementation of the PKIXCertPathChecker class - * can be created to extend the PKIX certification path validation algorithm. - * For example, an implementation may check for and process a critical private - * extension of each certificate in a certification path.
- *
- * Instances of PKIXCertPathChecker are passed as parameters - * using the {@link PKIXParameters#setCertPathCheckers setCertPathCheckers} - * or {@link PKIXParameters#addCertPathChecker addCertPathChecker} methods - * of the PKIXParameters and PKIXBuilderParameters - * class. Each of the PKIXCertPathCheckers {@link #check check} - * methods will be called, in turn, for each certificate processed by a PKIX - * CertPathValidator or CertPathBuilder - * implementation.
- *
- * A PKIXCertPathChecker may be called multiple times on - * successive certificates in a certification path. Concrete subclasses - * are expected to maintain any internal state that may be necessary to - * check successive certificates. The {@link #init init} method is used - * to initialize the internal state of the checker so that the certificates - * of a new certification path may be checked. A stateful implementation - * must override the {@link #clone clone} method if necessary in - * order to allow a PKIX CertPathBuilder to efficiently - * backtrack and try other paths. In these situations, the - * CertPathBuilder is able to restore prior path validation - * states by restoring the cloned PKIXCertPathCheckers.
- *
- * The order in which the certificates are presented to the - * PKIXCertPathChecker may be either in the forward direction - * (from target to most-trusted CA) or in the reverse direction (from - * most-trusted CA to target). A PKIXCertPathChecker implementation - * must support reverse checking (the ability to perform its checks when - * it is presented with certificates in the reverse direction) and may - * support forward checking (the ability to perform its checks when it is - * presented with certificates in the forward direction). The - * {@link #isForwardCheckingSupported isForwardCheckingSupported} method - * indicates whether forward checking is supported.
- *
- * Additional input parameters required for executing the check may be - * specified through constructors of concrete implementations of this class.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize. - * - * @see PKIXParameters - * @see PKIXBuilderParameters - **/ -public abstract class PKIXCertPathChecker implements Cloneable -{ - - /** - * Default constructor. - */ - protected PKIXCertPathChecker() - { - } - - /** - * Initializes the internal state of this PKIXCertPathChecker. - *

- * The forward flag specifies the order that certificates - * will be passed to the {@link #check check} method (forward or reverse). A - * PKIXCertPathChecker must support reverse checking - * and may support forward checking. - * - * @param forward - * the order that certificates are presented to the - * check method. If true, - * certificates are presented from target to most-trusted CA - * (forward); if false, from most-trusted CA to - * target (reverse). - * @exception CertPathValidatorException - * if this PKIXCertPathChecker is unable to - * check certificates in the specified order; it should never - * be thrown if the forward flag is false since reverse - * checking must be supported - */ - public abstract void init(boolean forward) - throws CertPathValidatorException; - - /** - * Indicates if forward checking is supported. Forward checking refers to - * the ability of the PKIXCertPathChecker to perform its - * checks when certificates are presented to the check method - * in the forward direction (from target to most-trusted CA). - * - * @return true if forward checking is supported, - * false otherwise - */ - public abstract boolean isForwardCheckingSupported(); - - /** - * Returns an immutable Set of X.509 certificate extensions - * that this PKIXCertPathChecker supports (i.e. recognizes, - * is able to process), or null if no extensions are - * supported. - *

- * Each element of the set is a String representing the - * Object Identifier (OID) of the X.509 extension that is supported. The OID - * is represented by a set of nonnegative integers separated by periods. - *

- * All X.509 certificate extensions that a PKIXCertPathChecker - * might possibly be able to process should be included in the set. - * - * @return an immutable Set of X.509 extension OIDs (in - * String format) supported by this - * PKIXCertPathChecker, or null if no - * extensions are supported - */ - public abstract Set getSupportedExtensions(); - - /** - * Performs the check(s) on the specified certificate using its internal - * state and removes any critical extensions that it processes from the - * specified collection of OID strings that represent the unresolved - * critical extensions. The certificates are presented in the order - * specified by the init method. - * - * @param cert - * the Certificate to be checked - * @param unresolvedCritExts - * a Collection of OID strings representing the - * current set of unresolved critical extensions - * @exception CertPathValidatorException - * if the specified certificate does not pass the check - */ - public abstract void check(Certificate cert, Collection unresolvedCritExts) - throws CertPathValidatorException; - - /** - * Returns a clone of this object. Calls the Object.clone() - * method. All subclasses which maintain state must support and override - * this method, if necessary. - * - * @return a copy of this PKIXCertPathChecker - */ - public Object clone() - { - try - { - return super.clone(); - } - catch (CloneNotSupportedException ex) - { - /* Cannot happen */ - throw new InternalError(ex.toString()); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXCertPathValidatorResult.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXCertPathValidatorResult.java deleted file mode 100644 index aa9b530f4..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXCertPathValidatorResult.java +++ /dev/null @@ -1,150 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.security.PublicKey; - -/** - * This class represents the successful result of the PKIX certification path - * validation algorithm.
- *
- * Instances of PKIXCertPathValidatorResult are returned by the - * {@link CertPathValidator#validate validate} method of - * CertPathValidator objects implementing the PKIX algorithm.
- *
- * All PKIXCertPathValidatorResult objects contain the valid - * policy tree and subject public key resulting from the validation algorithm, - * as well as a TrustAnchor describing the certification - * authority (CA) that served as a trust anchor for the certification path.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single object - * concurrently should synchronize amongst themselves and provide the necessary - * locking. Multiple threads each manipulating separate objects need not - * synchronize. - * - * @see CertPathValidatorResult - */ -public class PKIXCertPathValidatorResult implements CertPathValidatorResult -{ - private TrustAnchor trustAnchor; - - private PolicyNode policyTree; - - private PublicKey subjectPublicKey; - - /** - * Creates an instance of PKIXCertPathValidatorResult - * containing the specified parameters. - * - * @param trustAnchor - * a TrustAnchor describing the CA that served as - * a trust anchor for the certification path - * @param policyTree - * the immutable valid policy tree, or null if - * there are no valid policies - * @param subjectPublicKey - * the public key of the subject - * - * @exception NullPointerException - * if the subjectPublicKey or - * trustAnchor parameters are - * null - */ - public PKIXCertPathValidatorResult( - TrustAnchor trustAnchor, - PolicyNode policyTree, - PublicKey subjectPublicKey) - { - if (subjectPublicKey == null) - { - throw new NullPointerException("subjectPublicKey must be non-null"); - } - if (trustAnchor == null) - { - throw new NullPointerException("trustAnchor must be non-null"); - } - - this.trustAnchor = trustAnchor; - this.policyTree = policyTree; - this.subjectPublicKey = subjectPublicKey; - } - - /** - * Returns the TrustAnchor describing the CA that served as a - * trust anchor for the certification path. - * - * @return the TrustAnchor (never null) - */ - public TrustAnchor getTrustAnchor() - { - return trustAnchor; - } - - /** - * Returns the root node of the valid policy tree resulting from the PKIX - * certification path validation algorithm. The PolicyNode - * object that is returned and any objects that it returns through public - * methods are immutable.
- *
- * Most applications will not need to examine the valid policy tree. They - * can achieve their policy processing goals by setting the policy-related - * parameters in PKIXParameters. However, more sophisticated - * applications, especially those that process policy qualifiers, may need - * to traverse the valid policy tree using the - * {@link PolicyNode#getParent PolicyNode.getParent} and - * {@link PolicyNode#getChildren PolicyNode.getChildren} methods. - * - * @return the root node of the valid policy tree, or null if - * there are no valid policies - */ - public PolicyNode getPolicyTree() - { - return policyTree; - } - - /** - * Returns the public key of the subject (target) of the certification path, - * including any inherited public key parameters if applicable. - * - * @return the public key of the subject (never null) - */ - public PublicKey getPublicKey() - { - return subjectPublicKey; - } - - /** - * Returns a copy of this object. - * - * @return the copy - */ - public Object clone() - { - try - { - return super.clone(); - } - catch (CloneNotSupportedException ex) - { - throw new InternalError(ex.toString()); - } - } - - /** - * Return a printable representation of this - * PKIXCertPathValidatorResult. - * - * @return a String describing the contents of this - * PKIXCertPathValidatorResult - */ - public String toString() - { - StringBuffer s = new StringBuffer(); - s.append("PKIXCertPathValidatorResult: [ \n"); - s.append(" Trust Anchor: ").append(getTrustAnchor()).append('\n'); - s.append(" Policy Tree: ").append(getPolicyTree()).append('\n'); - s.append(" Subject Public Key: ").append(getPublicKey()).append("\n]"); - return s.toString(); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXParameters.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXParameters.java deleted file mode 100644 index a9d2d3835..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PKIXParameters.java +++ /dev/null @@ -1,844 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -/** - * Parameters used as input for the PKIX CertPathValidator algorithm.
- *
- * A PKIX CertPathValidator uses these parameters to validate a - * CertPath according to the PKIX certification path validation - * algorithm.
- *
- * To instantiate a PKIXParameters object, an application must - * specify one or more most-trusted CAs as defined by the PKIX - * certification path validation algorithm. The most-trusted CAs can be - * specified using one of two constructors. An application can call - * {@link #PKIXParameters(Set)}, specifying a Set of TrustAnchor - * objects, each of which identify a most-trusted CA. Alternatively, an - * application can call {@link #PKIXParameters(KeyStore)}, specifying a - * KeyStore instance containing trusted certificate entries, each - * of which will be considered as a most-trusted CA.
- *
- * Once a PKIXParameters object has been created, other - * parameters can be specified (by calling {@link #setInitialPolicies} or - * {@link #setDate}, for instance) and then the PKIXParameters - * is passed along with the CertPath to be validated to - * {@link CertPathValidator#validate}.
- *
- * Any parameter that is not set (or is set to null) will be set to the default - * value for that parameter. The default value for the date parameter is null, - * which indicates the current time when the path is validated. The default for - * the remaining parameters is the least constrained.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single object - * concurrently should synchronize amongst themselves and provide the necessary - * locking. Multiple threads each manipulating separate objects need not - * synchronize. - * - * @see CertPathValidator - */ -public class PKIXParameters implements CertPathParameters -{ - private Set trustAnchors; - - private Set initialPolicies = new HashSet(); - - private List certStores = new ArrayList(); - - private CertSelector certSelector; - - private List certPathCheckers = new ArrayList(); - - private boolean revocationEnabled = true; - - private boolean explicitPolicyRequired = false; - - private boolean policyMappingInhibited = false; - - private boolean anyPolicyInhibited = false; - - private boolean policyQualifiersRejected = true; - - private Date date; - - private String sigProvider; - - /** - * Creates an instance of PKIXParameters with the specified Set of - * most-trusted CAs. Each element of the set is a TrustAnchor.
- *
- * Note that the Set is copied to protect against subsequent modifications. - * - * @param trustAnchors - * a Set of TrustAnchors - * - * @exception InvalidAlgorithmParameterException - * if the specified Set is empty - * (trustAnchors.isEmpty() == true) - * @exception NullPointerException - * if the specified Set is null - * @exception ClassCastException - * if any of the elements in the Set are not of type - * java.security.cert.TrustAnchor - */ - public PKIXParameters(Set trustAnchors) - throws InvalidAlgorithmParameterException - { - setTrustAnchors(trustAnchors); - } - - /** - * Creates an instance of PKIXParameters that populates the set of - * most-trusted CAs from the trusted certificate entries contained in the - * specified KeyStore. Only keystore entries that contain trusted - * X509Certificates are considered; all other certificate types are ignored. - * - * @param keystore - * a KeyStore from which the set of most-trusted CAs will be - * populated - * - * @exception KeyStoreException - * if the keystore has not been initialized - * @exception InvalidAlgorithmParameterException - * if the keystore does not contain at least one trusted - * certificate entry - * @exception NullPointerException - * if the keystore is null - */ - public PKIXParameters(KeyStore keystore) throws KeyStoreException, - InvalidAlgorithmParameterException - { - if (keystore == null) - { - throw new NullPointerException( - "the keystore parameter must be non-null"); - } - - Set trustAnchors = new HashSet(); - String alias; - Certificate cert; - Enumeration enum = keystore.aliases(); - while (enum.hasMoreElements()) - { - alias = (String)enum.nextElement(); - if (keystore.isCertificateEntry(alias)) - { - cert = keystore.getCertificate(alias); - if (cert instanceof X509Certificate) - { - trustAnchors.add(new TrustAnchor((X509Certificate)cert, - null)); - } - } - } - setTrustAnchors(trustAnchors); - } - - /** - * Returns an immutable Set of the most-trusted CAs. - * - * @return an immutable Set of TrustAnchors - * (never null) - * - * @see #setTrustAnchors - */ - public Set getTrustAnchors() - { - return Collections.unmodifiableSet(trustAnchors); - } - - /** - * Sets the Set of most-trusted CAs.
- *
- * Note that the Set is copied to protect against subsequent modifications.
- *
- * - * @param trustAnchors - * a Set of TrustAnchors - * - * @exception InvalidAlgorithmParameterException - * if the specified Set is empty - * (trustAnchors.isEmpty() == true) - * @exception NullPointerException - * if the specified Set is null - * @exception ClassCastException - * if any of the elements in the set are not of type - * java.security.cert.TrustAnchor - * - * @see #getTrustAnchors - */ - public void setTrustAnchors(Set trustAnchors) - throws InvalidAlgorithmParameterException - { - if (trustAnchors == null) - { - throw new NullPointerException( - "the trustAnchors parameter must be non-null"); - } - if (trustAnchors.isEmpty()) - { - throw new InvalidAlgorithmParameterException( - "the trustAnchors parameter must be non-empty"); - } - - Iterator iter = trustAnchors.iterator(); - TrustAnchor obj; - this.trustAnchors = new HashSet(); - while (iter.hasNext()) - { - obj = (TrustAnchor)iter.next(); - if (obj != null) - { - this.trustAnchors.add(obj); - } - } - } - - /** - * Returns an immutable Set of initial policy identifiers (OID strings), - * indicating that any one of these policies would be acceptable to the - * certificate user for the purposes of certification path processing. The - * default return value is an empty Set, which is - * interpreted as meaning that any policy would be acceptable. - * - * @return an immutable Set of initial policy OIDs in String - * format, or an empty Set (implying any policy is - * acceptable). Never returns null. - * - * @see #setInitialPolicies(java.util.Set) - */ - public Set getInitialPolicies() - { - Set returnSet = initialPolicies; - if (initialPolicies == null) - { - returnSet = new HashSet(); - } - - return Collections.unmodifiableSet(returnSet); - } - - /** - * Sets the Set of initial policy identifiers (OID strings), - * indicating that any one of these policies would be acceptable to the - * certificate user for the purposes of certification path processing. By - * default, any policy is acceptable (i.e. all policies), so a user that - * wants to allow any policy as acceptable does not need to call this - * method, or can call it with an empty Set (or - * null).
- *
- * Note that the Set is copied to protect against subsequent modifications.
- *
- * - * @param initialPolicies - * a Set of initial policy OIDs in String format (or - * null) - * - * @exception ClassCastException - * if any of the elements in the set are not of type String - * - * @see #getInitialPolicies() - */ - public void setInitialPolicies(Set initialPolicies) - { - if (initialPolicies == null || initialPolicies.isEmpty()) - { - this.initialPolicies = null; - } - else - { - Iterator iter = initialPolicies.iterator(); - this.initialPolicies = new HashSet(); - String obj; - while (iter.hasNext()) - { - obj = (String)iter.next(); - if (obj != null) - { - this.initialPolicies.add(obj); - } - } - } - } - - /** - * Sets the list of CertStores to be used in finding certificates and CRLs. - * May be null, in which case no CertStores will be used. The first - * CertStores in the list may be preferred to those that appear later.
- *
- * Note that the List is copied to protect against subsequent modifications.
- *
- * - * @param stores - * a List of CertStores (or null) - * - * @exception ClassCastException - * if any of the elements in the list are not of type - * java.security.cert.CertStore - * - * @see #getCertStores() - */ - public void setCertStores(List stores) - { - certStores = new ArrayList(); - if (stores != null && !stores.isEmpty()) - { - Iterator iter = stores.iterator(); - CertStore obj; - while (iter.hasNext()) - { - obj = (CertStore)iter.next(); - if (obj != null) - { - certStores.add(obj); - } - } - } - } - - /** - * Adds a CertStore to the end of the list of CertStores used in finding - * certificates and CRLs. - * - * @param store - * the CertStore to add. If - * nullnull) - * - * @see #setCertStores(java.util.List) - */ - public List getCertStores() - { - return Collections.unmodifiableList(certStores); - } - - /** - * Sets the RevocationEnabled flag. If this flag is true, the default - * revocation checking mechanism of the underlying PKIX service provider - * will be used. If this flag is false, the default revocation checking - * mechanism will be disabled (not used).
- *
- * When a PKIXParameters object is created, this flag is set - * to true. This setting reflects the most common strategy for checking - * revocation, since each service provider must support revocation checking - * to be PKIX compliant. Sophisticated applications should set this flag to - * false when it is not practical to use a PKIX service provider's default - * revocation checking mechanism or when an alternative revocation checking - * mechanism is to be substituted (by also calling the - * {@link #addCertPathChecker addCertPathChecker} or {@link - * #setCertPathCheckers setCertPathCheckers} methods). - * - * @param val - * the new value of the RevocationEnabled flag - */ - public void setRevocationEnabled(boolean val) - { - revocationEnabled = val; - } - - /** - * Checks the RevocationEnabled flag. If this flag is true, the default - * revocation checking mechanism of the underlying PKIX service provider - * will be used. If this flag is false, the default revocation checking - * mechanism will be disabled (not used). See the setRevocationEnabled - * method for more details on setting the value of this flag. - * - * @return the current value of the RevocationEnabled flag - */ - public boolean isRevocationEnabled() - { - return revocationEnabled; - } - - /** - * Sets the ExplicitPolicyRequired flag. If this flag is true, an acceptable - * policy needs to be explicitly identified in every certificate. By - * default, the ExplicitPolicyRequired flag is false. - * - * @param val - * true if explicit policy is to be required, false otherwise - */ - public void setExplicitPolicyRequired(boolean val) - { - explicitPolicyRequired = val; - } - - /** - * Checks if explicit policy is required. If this flag is true, an - * acceptable policy needs to be explicitly identified in every certificate. - * By default, the ExplicitPolicyRequired flag is false. - * - * @return true if explicit policy is required, false otherwise - */ - public boolean isExplicitPolicyRequired() - { - return explicitPolicyRequired; - } - - /** - * Sets the PolicyMappingInhibited flag. If this flag is true, policy - * mapping is inhibited. By default, policy mapping is not inhibited (the - * flag is false). - * - * @param val - * true if policy mapping is to be inhibited, false otherwise - */ - public void setPolicyMappingInhibited(boolean val) - { - policyMappingInhibited = val; - } - - /** - * Checks if policy mapping is inhibited. If this flag is true, policy - * mapping is inhibited. By default, policy mapping is not inhibited (the - * flag is false). - * - * @return true if policy mapping is inhibited, false otherwise - */ - public boolean isPolicyMappingInhibited() - { - return policyMappingInhibited; - } - - /** - * Sets state to determine if the any policy OID should be processed if it - * is included in a certificate. By default, the any policy OID is not - * inhibited ({@link #isAnyPolicyInhibited()} returns false). - * - * @return val - true if the any policy OID is to be - * inhibited, false otherwise - */ - public void setAnyPolicyInhibited(boolean val) - { - anyPolicyInhibited = val; - } - - /** - * Checks whether the any policy OID should be processed if it is included - * in a certificate. - * - * @return true if the any policy OID is inhibited, - * false otherwise - */ - public boolean isAnyPolicyInhibited() - { - return anyPolicyInhibited; - } - - /** - * Sets the PolicyQualifiersRejected flag. If this flag is true, - * certificates that include policy qualifiers in a certificate policies - * extension that is marked critical are rejected. If the flag is false, - * certificates are not rejected on this basis.
- *
- * When a PKIXParameters object is created, this flag is set - * to true. This setting reflects the most common (and simplest) strategy - * for processing policy qualifiers. Applications that want to use a more - * sophisticated policy must set this flag to false.
- *
- * Note that the PKIX certification path validation algorithm specifies that - * any policy qualifier in a certificate policies extension that is marked - * critical must be processed and validated. Otherwise the certification - * path must be rejected. If the policyQualifiersRejected flag is set to - * false, it is up to the application to validate all policy qualifiers in - * this manner in order to be PKIX compliant. - * - * @param qualifiersRejected - * the new value of the PolicyQualifiersRejected flag - * - * @see #getPolicyQualifiersRejected() - * @see PolicyQualifierInfo - */ - public void setPolicyQualifiersRejected(boolean qualifiersRejected) - { - policyQualifiersRejected = qualifiersRejected; - } - - /** - * Gets the PolicyQualifiersRejected flag. If this flag is true, - * certificates that include policy qualifiers in a certificate policies - * extension that is marked critical are rejected. If the flag is false, - * certificates are not rejected on this basis.
- *
- * When a PKIXParameters object is created, this flag is set to true. This - * setting reflects the most common (and simplest) strategy for processing - * policy qualifiers. Applications that want to use a more sophisticated - * policy must set this flag to false. - * - * @return the current value of the PolicyQualifiersRejected flag - * - * @see #setPolicyQualifiersRejected(boolean) - */ - public boolean getPolicyQualifiersRejected() - { - return policyQualifiersRejected; - } - - /** - * Returns the time for which the validity of the certification path should - * be determined. If null, the current time is used.
- *
- * Note that the Date returned is copied to protect against subsequent - * modifications. - * - * @return the Date, or null if not set - * - * @see #setDate(java.util.Date) - */ - public Date getDate() - { - if (date == null) - { - return null; - } - - return new Date(date.getTime()); - } - - /** - * Sets the time for which the validity of the certification path should be - * determined. If null, the current time is used.
- *
- * Note that the Date supplied here is copied to protect against subsequent - * modifications. - * - * @param date - * the Date, or null for the current time - * - * @see #getDate() - */ - public void setDate(Date date) - { - if (date == null) - { - this.date = null; - } - else - { - this.date = new Date(date.getTime()); - } - } - - /** - * Sets a List of additional certification path checkers. If - * the specified List contains an object that is not a PKIXCertPathChecker, - * it is ignored.
- *
- * Each PKIXCertPathChecker specified implements additional - * checks on a certificate. Typically, these are checks to process and - * verify private extensions contained in certificates. Each - * PKIXCertPathChecker should be instantiated with any - * initialization parameters needed to execute the check.
- *
- * This method allows sophisticated applications to extend a PKIX - * CertPathValidator or CertPathBuilder. Each - * of the specified PKIXCertPathCheckers will be called, in turn, by a PKIX - * CertPathValidator or CertPathBuilder for - * each certificate processed or validated.
- *
- * Regardless of whether these additional PKIXCertPathCheckers are set, a - * PKIX CertPathValidator or CertPathBuilder - * must perform all of the required PKIX checks on each certificate. The one - * exception to this rule is if the RevocationEnabled flag is set to false - * (see the {@link #setRevocationEnabled(boolean) setRevocationEnabled} - * method).
- *
- * Note that the List supplied here is copied and each PKIXCertPathChecker - * in the list is cloned to protect against subsequent modifications. - * - * @param checkers - * a List of PKIXCertPathCheckers. May be null, in which case no - * additional checkers will be used. - * @exception ClassCastException - * if any of the elements in the list are not of type - * java.security.cert.PKIXCertPathChecker - * @see #getCertPathCheckers() - */ - public void setCertPathCheckers(List checkers) - { - certPathCheckers = new ArrayList(); - if (checkers == null) - { - return; - } - Iterator iter = checkers.iterator(); - while (iter.hasNext()) - { - certPathCheckers - .add((PKIXCertPathChecker)((PKIXCertPathChecker)iter.next()) - .clone()); - } - } - - /** - * Returns the List of certification path checkers. The returned List is - * immutable, and each PKIXCertPathChecker in the List is cloned to protect - * against subsequent modifications. - * - * @return an immutable List of PKIXCertPathCheckers (may be empty, but not - * null) - * - * @see #setCertPathCheckers(java.util.List) - */ - public List getCertPathCheckers() - { - List checkers = new ArrayList(); - Iterator iter = certPathCheckers.iterator(); - while (iter.hasNext()) - { - checkers - .add((PKIXCertPathChecker)((PKIXCertPathChecker)iter.next()) - .clone()); - } - return Collections.unmodifiableList(checkers); - } - - /** - * Adds a PKIXCertPathChecker to the list of certification path checkers. - * See the {@link #setCertPathCheckers} method for more details.
- *
- * Note that the PKIXCertPathChecker is cloned to protect - * against subsequent modifications. - * - * @param checker - * a PKIXCertPathChecker to add to the list of - * checks. If null, the checker is ignored (not - * added to list). - */ - public void addCertPathChecker(PKIXCertPathChecker checker) - { - if (checker != null) - { - certPathCheckers.add(checker.clone()); - } - } - - /** - * Returns the signature provider's name, or null if not set. - * - * @return the signature provider's name (or null) - * - * @see #setSigProvider(java.lang.String) - */ - public String getSigProvider() - { - return sigProvider; - } - - /** - * Sets the signature provider's name. The specified provider will be - * preferred when creating Signature objects. If null or not set, the first - * provider found supporting the algorithm will be used. - * - * @param sigProvider - * the signature provider's name (or null) - * - * @see #getSigProvider() - */ - public void setSigProvider(String sigProvider) - { - this.sigProvider = sigProvider; - } - - /** - * Returns the required constraints on the target certificate. The - * constraints are returned as an instance of CertSelector. If - * null, no constraints are defined.
- *
- * Note that the CertSelector returned is cloned to protect against - * subsequent modifications. - * - * @return a CertSelector specifying the constraints on the target - * certificate (or null) - * - * @see #setTargetCertConstraints(CertSelector) - */ - public CertSelector getTargetCertConstraints() - { - if (certSelector == null) - { - return null; - } - - return (CertSelector)certSelector.clone(); - } - - /** - * Sets the required constraints on the target certificate. The constraints - * are specified as an instance of CertSelector. If null, no constraints are - * defined.
- *
- * Note that the CertSelector specified is cloned to protect against - * subsequent modifications. - * - * @param selector - * a CertSelector specifying the constraints on the target - * certificate (or null) - * - * @see #getTargetCertConstraints() - */ - public void setTargetCertConstraints(CertSelector selector) - { - if (selector == null) - { - certSelector = null; - } - else - { - certSelector = (CertSelector)selector.clone(); - } - } - - /** - * Makes a copy of this PKIXParameters object. Changes to the copy will not - * affect the original and vice versa. - * - * @return a copy of this PKIXParameters object - */ - public Object clone() - { - try - { - PKIXParameters obj = (PKIXParameters)super.clone(); - obj.certStores = new ArrayList(certStores); - Iterator iter = certPathCheckers.iterator(); - obj.certPathCheckers = new ArrayList(); - while (iter.hasNext()) - { - obj.certPathCheckers.add(((PKIXCertPathChecker)iter.next()) - .clone()); - } - if (initialPolicies != null) - { - obj.initialPolicies = new HashSet(initialPolicies); - } - if (trustAnchors != null) - { - obj.trustAnchors = new HashSet(trustAnchors); - } - if (certSelector != null) - { - obj.certSelector = (CertSelector)certSelector.clone(); - } - return obj; - } - catch (CloneNotSupportedException ex) - { - throw new InternalError(); - } - } - - /** - * Returns a formatted string describing the parameters. - * - * @return a formatted string describing the parameters. - */ - public String toString() - { - StringBuffer s = new StringBuffer(); - s.append("[\n"); - if (trustAnchors != null) - { - s.append(" Trust Anchors: ").append(trustAnchors).append('\n'); - } - if (initialPolicies != null) - { - if (initialPolicies.isEmpty()) - { - s.append(" Initial Policy OIDs: any\n"); - } - else - { - s.append(" Initial Policy OIDs: [") - .append(initialPolicies).append("]\n"); - } - } - s.append(" Validity Date: "); - if (date != null) - { - s.append(date); - } - else - { - s.append("null"); - } - s.append('\n'); - - s.append(" Signature Provider: "); - if (sigProvider != null) - { - s.append(sigProvider); - } - else - { - s.append("null"); - } - s.append('\n'); - - s.append(" Default Revocation Enabled: "); - s.append(revocationEnabled); - s.append('\n'); - - s.append(" Explicit Policy Required: "); - s.append(explicitPolicyRequired); - s.append('\n'); - - s.append(" Policy Mapping Inhibited: "); - s.append(policyMappingInhibited); - s.append('\n'); - - s.append(" Any Policy Inhibited: "); - s.append(anyPolicyInhibited); - s.append('\n'); - - s.append(" Policy Qualifiers Rejected: "); - s.append(policyQualifiersRejected); - s.append('\n'); - - s.append(" Target Cert Constraints: "); - s.append(certSelector); - s.append('\n'); - - s.append(" Certification Path Checkers: ["); - s.append(certPathCheckers); - s.append("}\n"); - - s.append(" CertStores: ["); - s.append(certStores); - s.append("}\n"); - - s.append("]\n"); - - return s.toString(); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PolicyNode.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PolicyNode.java deleted file mode 100644 index ae9199b37..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PolicyNode.java +++ /dev/null @@ -1,107 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.util.Iterator; -import java.util.Set; - -/** - * An immutable valid policy tree node as defined by the PKIX certification - * path validation algorithm.
- *
- * One of the outputs of the PKIX certification path validation - * algorithm is a valid policy tree, which includes the policies that - * were determined to be valid, how this determination was reached, - * and any policy qualifiers encountered. This tree is of depth - * n, where n is the length of the certification - * path that has been validated.
- *
- * Most applications will not need to examine the valid policy tree. - * They can achieve their policy processing goals by setting the - * policy-related parameters in PKIXParameters. However, - * the valid policy tree is available for more sophisticated applications, - * especially those that process policy qualifiers.
- *
- * {@link PKIXCertPathValidatorResult#getPolicyTree() - * PKIXCertPathValidatorResult.getPolicyTree} returns the root node of the - * valid policy tree. The tree can be traversed using the - * {@link #getChildren getChildren} and {@link #getParent getParent} methods. - * Data about a particular node can be retrieved using other methods of - * PolicyNode.
- *
- * Concurrent Access
- *
- * All PolicyNode objects must be immutable and - * thread-safe. Multiple threads may concurrently invoke the methods defined - * in this class on a single PolicyNode object (or more than one) - * with no ill effects. This stipulation applies to all public fields and - * methods of this class and any added or overridden by subclasses. - **/ -public interface PolicyNode -{ - - /** - * Returns the parent of this node, or null if this is the - * root node. - * - * @return the parent of this node, or null if this is the - * root node - */ - public PolicyNode getParent(); - - /** - * Returns an iterator over the children of this node. Any attempts to - * modify the children of this node through the - * Iterator's remove method must throw an - * UnsupportedOperationException. - * - * @return an iterator over the children of this node - */ - public Iterator getChildren(); - - /** - * Returns the depth of this node in the valid policy tree. - * - * @return the depth of this node (0 for the root node, 1 for its - * children, and so on) - */ - public int getDepth(); - - /** - * Returns the valid policy represented by this node. - * - * @return the String OID of the valid policy - * represented by this node, or the special value "any-policy". For - * the root node, this method always returns the special value "any-policy". - */ - public String getValidPolicy(); - - /** - * Returns the set of policy qualifiers associated with the - * valid policy represented by this node. - * - * @return an immutable Set of - * PolicyQualifierInfos. For the root node, this - * is always an empty Set. - */ - public Set getPolicyQualifiers(); - - /** - * Returns the set of expected policies that would satisfy this - * node's valid policy in the next certificate to be processed. - * - * @return an immutable Set of expected policy - * String OIDs, or an immutable Set with - * the single special value "any-policy". For the root node, this method - * always returns a Set with the single value "any-policy". - */ - public Set getExpectedPolicies(); - - /** - * Returns the criticality indicator of the certificate policy extension - * in the most recently processed certificate. - * - * @return true if extension marked critical, - * false otherwise. For the root node, false - * is always returned. - */ - public boolean isCritical(); -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PolicyQualifierInfo.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PolicyQualifierInfo.java deleted file mode 100644 index 97e9c5faa..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/PolicyQualifierInfo.java +++ /dev/null @@ -1,196 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Object; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.DEROutputStream; -import org.spongycastle.asn1.util.ASN1Dump; - -/** - * An immutable policy qualifier represented by the ASN.1 PolicyQualifierInfo - * structure.
- *
- * The ASN.1 definition is as follows:
- *
- * - *

- *    PolicyQualifierInfo ::= SEQUENCE {
- *         policyQualifierId       PolicyQualifierId,
- *         qualifier               ANY DEFINED BY policyQualifierId }
- * 
- * - *
- *
- * A certificate policies extension, if present in an X.509 version 3 - * certificate, contains a sequence of one or more policy information terms, - * each of which consists of an object identifier (OID) and optional qualifiers. - * In an end-entity certificate, these policy information terms indicate the - * policy under which the certificate has been issued and the purposes for which - * the certificate may be used. In a CA certificate, these policy information - * terms limit the set of policies for certification paths which include this - * certificate.
- *
- * A Set of PolicyQualifierInfo objects are - * returned by the - * {@link PolicyNode#getPolicyQualifiers PolicyNode.getPolicyQualifiers} method. - * This allows applications with specific policy requirements to process and - * validate each policy qualifier. Applications that need to process policy - * qualifiers should explicitly set the policyQualifiersRejected - * flag to false (by calling the - * {@link PKIXParameters#setPolicyQualifiersRejected - * PKIXParameters.setPolicyQualifiersRejected} method) before validating a - * certification path.
- *
- * Note that the PKIX certification path validation algorithm specifies that any - * policy qualifier in a certificate policies extension that is marked critical - * must be processed and validated. Otherwise the certification path must be - * rejected. If the policyQualifiersRejected flag is set to - * false, it is up to the application to validate all policy qualifiers in this - * manner in order to be PKIX compliant.
- *
- * Concurrent Access
- *
- * All PolicyQualifierInfo objects must be immutable and - * thread-safe. That is, multiple threads may concurrently invoke the methods - * defined in this class on a single PolicyQualifierInfo object - * (or more than one) with no ill effects. Requiring - * PolicyQualifierInfo objects to be immutable and thread-safe - * allows them to be passed around to various pieces of code without worrying - * about coordinating access.
- *
- * Uses {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Sequence ASN1Sequence}, - * {@link org.spongycastle.asn1.ASN1ObjectIdentifier ASN1ObjectIdentifier}, - * {@link org.spongycastle.asn1.DEROutputStream DEROutputStream}, - * {@link org.spongycastle.asn1.ASN1Object ASN1Object} - */ -public final class PolicyQualifierInfo -{ - private String id; - - private byte[] encoded; - - private byte[] qualifier; - - /** - * Creates an instance of PolicyQualifierInfo from the - * encoded bytes. The encoded byte array is copied on construction.
- *
- * Uses {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Sequence ASN1Sequence}, - * {@link org.spongycastle.asn1.ASN1ObjectIdentifier ASN1ObjectIdentifier} and - * {@link org.spongycastle.asn1.DEROutputStream DEROutputStream} - * - * @param encoded - * a byte array containing the qualifier in DER encoding - * - * @exception IOException - * thrown if the byte array does not represent a valid and - * parsable policy qualifier - */ - public PolicyQualifierInfo(byte[] encoded) throws IOException - { - this.encoded = (byte[])encoded.clone(); - try - { - ByteArrayInputStream inStream = new ByteArrayInputStream( - this.encoded); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Sequence obj = (ASN1Sequence)derInStream.readObject(); - id = ((ASN1ObjectIdentifier)obj.getObjectAt(0)).getId(); - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - DEROutputStream derOutStream = new DEROutputStream(outStream); - - derOutStream.writeObject(obj.getObjectAt(1)); - derOutStream.close(); - - qualifier = outStream.toByteArray(); - } - catch (Exception ex) - { - throw new IOException("parsing exception : " + ex.toString()); - } - } - - /** - * Returns the policyQualifierId field of this - * PolicyQualifierInfo. The policyQualifierId - * is an Object Identifier (OID) represented by a set of nonnegative - * integers separated by periods. - * - * @return the OID (never null) - */ - public String getPolicyQualifierId() - { - return id; - } - - /** - * Returns the ASN.1 DER encoded form of this - * PolicyQualifierInfo. - * - * @return the ASN.1 DER encoded bytes (never null). Note - * that a copy is returned, so the data is cloned each time this - * method is called. - */ - public byte[] getEncoded() - { - return (byte[])encoded.clone(); - } - - /** - * Returns the ASN.1 DER encoded form of the qualifier field - * of this PolicyQualifierInfo. - * - * @return the ASN.1 DER encoded bytes of the qualifier - * field. Note that a copy is returned, so the data is cloned each - * time this method is called. - */ - public byte[] getPolicyQualifier() - { - if (qualifier == null) - { - return null; - } - - return (byte[])qualifier.clone(); - } - - /** - * Return a printable representation of this - * PolicyQualifierInfo.
- *
- * Uses {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Object ASN1Object} - * - * @return a String describing the contents of this - * PolicyQualifierInfo - */ - public String toString() - { - StringBuffer s = new StringBuffer(); - s.append("PolicyQualifierInfo: [\n"); - s.append("qualifierID: ").append(id).append('\n'); - try - { - ByteArrayInputStream inStream = new ByteArrayInputStream(qualifier); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); - s - .append(" qualifier:\n").append(ASN1Dump.dumpAsString(derObject)) - .append('\n'); - } - catch (IOException ex) - { - s.append(ex.getMessage()); - } - s.append("qualifier: ").append(id).append('\n'); - s.append(']'); - return s.toString(); - } -} \ No newline at end of file diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/TrustAnchor.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/TrustAnchor.java deleted file mode 100644 index 68a9abf3d..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/TrustAnchor.java +++ /dev/null @@ -1,293 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.security.PublicKey; -import java.security.cert.X509Certificate; - -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Object; -import org.spongycastle.asn1.ASN1Sequence; - -/** - * A trust anchor or most-trusted Certification Authority (CA).
- *
- * This class represents a "most-trusted CA", which is used as a trust anchor - * for validating X.509 certification paths. A most-trusted CA includes the - * public key of the CA, the CA's name, and any constraints upon the set of - * paths which may be validated using this key. These parameters can be - * specified in the form of a trusted X509Certificate or as individual - * parameters.
- *
- * Concurrent Access
- *
- * All TrustAnchor objects must be immutable and thread-safe. That is, multiple - * threads may concurrently invoke the methods defined in this class on a - * single TrustAnchor object (or more than one) with no ill effects. Requiring - * TrustAnchor objects to be immutable and thread-safe allows them to be passed - * around to various pieces of code without worrying about coordinating access. - * This stipulation applies to all public fields and methods of this class and - * any added or overridden by subclasses.
- *
- * TODO: implement better nameConstraints testing. - **/ -public class TrustAnchor -{ - private X509Certificate trustCert = null; - - private PublicKey trustPublicKey = null; - - private String trustName = null; - - private byte[] nameConstraints = null; - - /** - * Creates an instance of TrustAnchor with the specified X509Certificate and - * optional name constraints, which are intended to be used as additional - * constraints when validating an X.509 certification path.
- *
- * The name constraints are specified as a byte array. This byte array - * should contain the DER encoded form of the name constraints, as they - * would appear in the NameConstraints structure defined in RFC 2459 and - * X.509. The ASN.1 definition of this structure appears below.
- *
- * - *
-     *   NameConstraints ::= SEQUENCE {
-     *        permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
-     *        excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
-     * 
-     *   GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
-     * 
-     *   GeneralSubtree ::= SEQUENCE {
-     *        base                    GeneralName,
-     *        minimum         [0]     BaseDistance DEFAULT 0,
-     *        maximum         [1]     BaseDistance OPTIONAL }
-     * 
-     *   BaseDistance ::= INTEGER (0..MAX)
-     * 
-     *   GeneralName ::= CHOICE {
-     *        otherName                       [0]     OtherName,
-     *        rfc822Name                      [1]     IA5String,
-     *        dNSName                         [2]     IA5String,
-     *        x400Address                     [3]     ORAddress,
-     *        directoryName                   [4]     Name,
-     *        ediPartyName                    [5]     EDIPartyName,
-     *        uniformResourceIdentifier       [6]     IA5String,
-     *        iPAddress                       [7]     OCTET STRING,
-     *        registeredID                    [8]     OBJECT IDENTIFIER}
-     * 
- * - *
- *
- * Note that the name constraints byte array supplied is cloned to protect - * against subsequent modifications. - * - * @param trustedCert - * a trusted X509Certificate - * @param nameConstraints - * a byte array containing the ASN.1 DER encoding of a - * NameConstraints extension to be used for checking name - * constraints. Only the value of the extension is included, not - * the OID or criticality flag. Specify null to omit the - * parameter. - * - * @exception IllegalArgumentException - * if the name constraints cannot be decoded - * @exception NullPointerException - * if the specified X509Certificate is null - */ - public TrustAnchor(X509Certificate trustedCert, byte[] nameConstraints) - { - if (trustedCert == null) - { - throw new NullPointerException("trustedCert must be non-null"); - } - - this.trustCert = trustedCert; - if (nameConstraints != null) - { - this.nameConstraints = (byte[])nameConstraints.clone(); - checkNameConstraints(this.nameConstraints); - } - } - - /** - * Creates an instance of TrustAnchor where the most-trusted - * CA is specified as a distinguished name and public key. Name constraints - * are an optional parameter, and are intended to be used as additional - * constraints when validating an X.509 certification path. - * - * The name constraints are specified as a byte array. This byte array - * contains the DER encoded form of the name constraints, as they would - * appear in the NameConstraints structure defined in RFC 2459 and X.509. - * The ASN.1 notation for this structure is supplied in the documentation - * for {@link #TrustAnchor(X509Certificate trustedCert, byte[] - * nameConstraints) TrustAnchor(X509Certificate trustedCert, byte[] - * nameConstraints) }. - * - * Note that the name constraints byte array supplied here is cloned to - * protect against subsequent modifications. - * - * @param caName - * the X.500 distinguished name of the most-trusted CA in RFC - * 2253 String format - * @param pubKey - * the public key of the most-trusted CA - * @param nameConstraints - * a byte array containing the ASN.1 DER encoding of a - * NameConstraints extension to be used for checking name - * constraints. Only the value of the extension is included, not - * the OID or criticality flag. Specify null to omit the - * parameter. - * - * @exception IllegalArgumentException - * if the specified caName parameter is empty (caName.length() == 0) - * or incorrectly formatted or the name constraints cannot be - * decoded - * @exception NullPointerException - * if the specified caName or pubKey parameter is null - */ - public TrustAnchor(String caName, PublicKey pubKey, byte[] nameConstraints) - { - if (caName == null) - { - throw new NullPointerException("caName must be non-null"); - } - if (pubKey == null) - { - throw new NullPointerException("pubKey must be non-null"); - } - if (caName.length() == 0) - { - throw new IllegalArgumentException( - "caName can not be an empty string"); - } - - this.trustName = caName; - this.trustPublicKey = pubKey; - if (nameConstraints != null) - { - this.nameConstraints = (byte[])nameConstraints.clone(); - checkNameConstraints(this.nameConstraints); - } - } - - /** - * Returns the most-trusted CA certificate. - * - * @return a trusted X509Certificate or null - * if the trust anchor was not specified as a trusted certificate - */ - public final X509Certificate getTrustedCert() - { - return trustCert; - } - - /** - * Returns the name of the most-trusted CA in RFC 2253 String format. - * - * @return the X.500 distinguished name of the most-trusted CA, or - * null if the trust anchor was not specified as a - * trusted public key and name pair - */ - public final String getCAName() - { - return trustName; - } - - /** - * Returns the public key of the most-trusted CA. - * - * @return the public key of the most-trusted CA, or null if the trust - * anchor was not specified as a trusted public key and name pair - */ - public final PublicKey getCAPublicKey() - { - return trustPublicKey; - } - - /** - * Returns the name constraints parameter. The specified name constraints - * are associated with this trust anchor and are intended to be used as - * additional constraints when validating an X.509 certification path.
- *
- * The name constraints are returned as a byte array. This byte array - * contains the DER encoded form of the name constraints, as they would - * appear in the NameConstraints structure defined in RFC 2459 and X.509. - * The ASN.1 notation for this structure is supplied in the documentation - * for TrustAnchor(X509Certificate trustedCert, byte[] - * nameConstraints).
- *
- * Note that the byte array returned is cloned to protect against subsequent - * modifications. - * - * @return a byte array containing the ASN.1 DER encoding of a - * NameConstraints extension used for checking name constraints, or - * null if not set. - */ - public final byte[] getNameConstraints() - { - return (byte[])nameConstraints.clone(); - } - - /** - * Returns a formatted string describing the TrustAnchor. - * - * @return a formatted string describing the TrustAnchor - */ - public String toString() - { - StringBuffer sb = new StringBuffer(); - sb.append("[\n"); - if (getCAPublicKey() != null) - { - sb.append(" Trusted CA Public Key: ").append(getCAPublicKey()).append('\n'); - sb.append(" Trusted CA Issuer Name: ").append(getCAName()).append('\n'); - } - else - { - sb.append(" Trusted CA cert: ").append(getTrustedCert()).append('\n'); - } - if (nameConstraints != null) - { - sb.append(" Name Constraints: ").append(nameConstraints).append('\n'); - } - return sb.toString(); - } - - /** - * Check given DER encoded nameConstraints for correct decoding. Currently - * only basic DER decoding test.
- *
- * TODO: implement more testing. - * - * @param data - * the DER encoded nameConstrains to be checked or - * null - * @exception IllegalArgumentException - * if the check failed. - */ - private void checkNameConstraints(byte[] data) - { - if (data != null) - { - try - { - ByteArrayInputStream inStream = new ByteArrayInputStream(data); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); - if (!(derObject instanceof ASN1Sequence)) - { - throw new IllegalArgumentException( - "nameConstraints parameter decoding error"); - } - } - catch (IOException ex) - { - throw new IllegalArgumentException( - "nameConstraints parameter decoding error: " + ex); - } - } - } -} \ No newline at end of file diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/X509CRLSelector.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/X509CRLSelector.java deleted file mode 100644 index 4a377ed36..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/X509CRLSelector.java +++ /dev/null @@ -1,717 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.security.cert.CRL; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.util.Collection; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Object; -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.x509.X509Extensions; -import org.spongycastle.asn1.x509.X509Name; -import org.spongycastle.jce.PrincipalUtil; - -/** - * A CRLSelector that selects X509CRLs that match - * all specified criteria. This class is particularly useful when selecting CRLs - * from a CertStore to check revocation status of a particular - * certificate.
- *
- * When first constructed, an X509CRLSelector has no criteria - * enabled and each of the get methods return a default value (null). - * Therefore, the {@link #match match} method would return true - * for any X509CRL. Typically, several criteria are enabled (by - * calling {@link #setIssuerNames setIssuerNames} or - * {@link #setDateAndTime setDateAndTime}, for instance) and then the - * X509CRLSelector is passed to - * {@link CertStore#getCRLs CertStore.getCRLs} or some similar method.
- *
- * Please refer to RFC 2459 for definitions of the X.509 CRL fields and - * extensions mentioned below.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are not - * thread-safe. Multiple threads that need to access a single object - * concurrently should synchronize amongst themselves and provide the necessary - * locking. Multiple threads each manipulating separate objects need not - * synchronize.
- *
- * Uses {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Sequence ASN1Sequence}, - * {@link org.spongycastle.asn1.ASN1ObjectIdentifier ASN1ObjectIdentifier}, - * {@link org.spongycastle.asn1.DEROutputStream DEROutputStream}, - * {@link org.spongycastle.asn1.ASN1Object ASN1Object}, - * {@link org.spongycastle.asn1.x509.X509Name X509Name} - * - * @see CRLSelector - * @see X509CRL - */ -public class X509CRLSelector implements CRLSelector -{ - private Set issuerNames = null; - - private Set issuerNamesX509 = null; - - private BigInteger minCRL = null; - - private BigInteger maxCRL = null; - - private Date dateAndTime = null; - - private X509Certificate certChecking = null; - - /** - * Creates an X509CRLSelector. Initially, no criteria are - * set so any X509CRL will match. - */ - public X509CRLSelector() - { - } - - /** - * Sets the issuerNames criterion. The issuer distinguished name in the - * X509CRL must match at least one of the specified - * distinguished names. If null, any issuer distinguished - * name will do.
- *
- * This method allows the caller to specify, with a single method call, the - * complete set of issuer names which X509CRLs may contain. - * The specified value replaces the previous value for the issuerNames - * criterion.
- *
- * The names parameter (if not null) is a - * Collection of names. Each name is a String - * or a byte array representing a distinguished name (in RFC 2253 or ASN.1 - * DER encoded form, respectively). If null is supplied as - * the value for this argument, no issuerNames check will be performed.
- *
- * Note that the names parameter can contain duplicate - * distinguished names, but they may be removed from the - * Collection of names returned by the - * {@link #getIssuerNames getIssuerNames} method.
- *
- * If a name is specified as a byte array, it should contain a single DER - * encoded distinguished name, as defined in X.501. The ASN.1 notation for - * this structure is as follows. - * - *

-     *  Name ::= CHOICE {
-     *    RDNSequence }
-     * 
-     *  RDNSequence ::= SEQUENCE OF RDN
-     * 
-     *  RDN ::=
-     *    SET SIZE (1 .. MAX) OF AttributeTypeAndValue
-     * 
-     *  AttributeTypeAndValue ::= SEQUENCE {
-     *    type     AttributeType,
-     *    value    AttributeValue }
-     * 
-     *  AttributeType ::= OBJECT IDENTIFIER
-     * 
-     *  AttributeValue ::= ANY DEFINED BY AttributeType
-     *  ....
-     *  DirectoryString ::= CHOICE {
-     *        teletexString           TeletexString (SIZE (1..MAX)),
-     *        printableString         PrintableString (SIZE (1..MAX)),
-     *        universalString         UniversalString (SIZE (1..MAX)),
-     *        utf8String              UTF8String (SIZE (1.. MAX)),
-     *        bmpString               BMPString (SIZE (1..MAX)) }
-     * 
- * - *
- *
- * Note that a deep copy is performed on the Collection to - * protect against subsequent modifications. - * - * @param names - * a Collection of names (or null) - * - * @exception IOException - * if a parsing error occurs - * - * @see #getIssuerNames - */ - public void setIssuerNames(Collection names) throws IOException - { - if (names == null || names.isEmpty()) - { - issuerNames = null; - issuerNamesX509 = null; - } - else - { - Object item; - Iterator iter = names.iterator(); - while (iter.hasNext()) - { - item = iter.next(); - if (item instanceof String) - { - addIssuerName((String)item); - } - else if (item instanceof byte[]) - { - addIssuerName((byte[])item); - } - else - { - throw new IOException("name not byte[]or String: " - + item.toString()); - } - } - } - } - - /** - * Adds a name to the issuerNames criterion. The issuer distinguished name - * in the X509CRL must match at least one of the specified - * distinguished names.
- *
- * This method allows the caller to add a name to the set of issuer names - * which X509CRLs may contain. The specified name is added to - * any previous value for the issuerNames criterion. If the specified name - * is a duplicate, it may be ignored.
- *
- * Uses {@link org.spongycastle.asn1.x509.X509Name X509Name} for parsing the - * name - * - * @param name - * the name in RFC 2253 form - * - * @exception IOException - * if a parsing error occurs - */ - public void addIssuerName(String name) throws IOException - { - if (issuerNames == null) - { - issuerNames = new HashSet(); - issuerNamesX509 = new HashSet(); - } - X509Name nameX509; - try - { - nameX509 = new X509Name(name); - } - catch (IllegalArgumentException ex) - { - throw new IOException(ex.getMessage()); - } - issuerNamesX509.add(nameX509); - issuerNames.add(name); - } - - /** - * Adds a name to the issuerNames criterion. The issuer distinguished name - * in the X509CRL must match at least one of the specified - * distinguished names.
- *
- * This method allows the caller to add a name to the set of issuer names - * which X509CRLs may contain. The specified name is added to - * any previous value for the issuerNames criterion. If the specified name - * is a duplicate, it may be ignored. If a name is specified as a byte - * array, it should contain a single DER encoded distinguished name, as - * defined in X.501. The ASN.1 notation for this structure is as follows.
- *
- * The name is provided as a byte array. This byte array should contain a - * single DER encoded distinguished name, as defined in X.501. The ASN.1 - * notation for this structure appears in the documentation for - * {@link #setIssuerNames setIssuerNames(Collection names)}.
- *
- * Note that the byte array supplied here is cloned to protect against - * subsequent modifications.
- *
- * Uses {@link org.spongycastle.asn1.x509.X509Name X509Name} for parsing the - * name, {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Object ASN1Object} and - * {@link org.spongycastle.asn1.ASN1Sequence ASN1Sequence} - * - * @param name - * a byte array containing the name in ASN.1 DER encoded form - * - * @exception IOException - * if a parsing error occurs - */ - public void addIssuerName(byte[] name) throws IOException - { - if (issuerNames == null) - { - issuerNames = new HashSet(); - issuerNamesX509 = new HashSet(); - } - - ByteArrayInputStream inStream = new ByteArrayInputStream(name); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object obj = derInStream.readObject(); - if (obj instanceof ASN1Sequence) - { - issuerNamesX509.add(new X509Name((ASN1Sequence)obj)); - } - else - { - throw new IOException("parsing error"); - } - issuerNames.add(name.clone()); - } - - /** - * Sets the minCRLNumber criterion. The X509CRL must have a - * CRL number extension whose value is greater than or equal to the - * specified value. If null, no minCRLNumber check will be - * done. - * - * @param minCRL - * the minimum CRL number accepted (or null) - */ - public void setMinCRLNumber(BigInteger minCRL) - { - this.minCRL = minCRL; - } - - /** - * Sets the maxCRLNumber criterion. The X509CRL must have a - * CRL number extension whose value is less than or equal to the specified - * value. If null, no maxCRLNumber check will be done. - * - * @param maxCRL - * the maximum CRL number accepted (or null) - */ - public void setMaxCRLNumber(BigInteger maxCRL) - { - this.maxCRL = maxCRL; - } - - /** - * Sets the dateAndTime criterion. The specified date must be equal to or - * later than the value of the thisUpdate component of the - * X509CRL and earlier than the value of the nextUpdate - * component. There is no match if the X509CRL does not - * contain a nextUpdate component. If null, no dateAndTime - * check will be done.
- *
- * Note that the Date supplied here is cloned to protect - * against subsequent modifications. - * - * @param dateAndTime - * the Date to match against (or null) - * - * @see #getDateAndTime - */ - public void setDateAndTime(Date dateAndTime) - { - if (dateAndTime == null) - { - this.dateAndTime = null; - } - else - { - this.dateAndTime = new Date(dateAndTime.getTime()); - } - } - - /** - * Sets the certificate being checked. This is not a criterion. Rather, it - * is optional information that may help a CertStore find - * CRLs that would be relevant when checking revocation for the specified - * certificate. If null is specified, then no such optional - * information is provided. - * - * @param cert - * the X509Certificate being checked (or - * null) - * - * @see #getCertificateChecking - */ - public void setCertificateChecking(X509Certificate cert) - { - certChecking = cert; - } - - /** - * Returns a copy of the issuerNames criterion. The issuer distinguished - * name in the X509CRL must match at least one of the - * specified distinguished names. If the value returned is null, - * any issuer distinguished name will do.
- *
- * If the value returned is not null, it is a - * Collection of names. Each name is a String - * or a byte array representing a distinguished name (in RFC 2253 or ASN.1 - * DER encoded form, respectively). Note that the Collection - * returned may contain duplicate names.
- *
- * If a name is specified as a byte array, it should contain a single DER - * encoded distinguished name, as defined in X.501. The ASN.1 notation for - * this structure is given in the documentation for - * {@link #setIssuerNames setIssuerNames(Collection names)}.
- *
- * Note that a deep copy is performed on the Collection to - * protect against subsequent modifications. - * - * @return a Collection of names (or null) - * @see #setIssuerNames - */ - public Collection getIssuerNames() - { - if (issuerNames == null) - { - return null; - } - - Collection set = new HashSet(); - Iterator iter = issuerNames.iterator(); - Object item; - while (iter.hasNext()) - { - item = iter.next(); - if (item instanceof String) - { - set.add(new String((String)item)); - } - else if (item instanceof byte[]) - { - set.add(((byte[])item).clone()); - } - } - return set; - } - - /** - * Returns the minCRLNumber criterion. The X509CRL must have - * a CRL number extension whose value is greater than or equal to the - * specified value. If null, no minCRLNumber check will be - * done. - * - * @return the minimum CRL number accepted (or null) - */ - public BigInteger getMinCRL() - { - return minCRL; - } - - /** - * Returns the maxCRLNumber criterion. The X509CRL must have - * a CRL number extension whose value is less than or equal to the specified - * value. If null, no maxCRLNumber check will be done. - * - * @return the maximum CRL number accepted (or null) - */ - public BigInteger getMaxCRL() - { - return maxCRL; - } - - /** - * Returns the dateAndTime criterion. The specified date must be equal to or - * later than the value of the thisUpdate component of the - * X509CRL and earlier than the value of the nextUpdate - * component. There is no match if the X509CRL does not - * contain a nextUpdate component. If null, no dateAndTime - * check will be done.
- *
- * Note that the Date returned is cloned to protect against - * subsequent modifications. - * - * @return the Date to match against (or null) - * - * @see #setDateAndTime - */ - public Date getDateAndTime() - { - if (dateAndTime == null) - { - return null; - } - - return new Date(dateAndTime.getTime()); - } - - /** - * Returns the certificate being checked. This is not a criterion. Rather, - * it is optional information that may help a CertStore find - * CRLs that would be relevant when checking revocation for the specified - * certificate. If the value returned is null, then no such - * optional information is provided. - * - * @return the certificate being checked (or null) - * - * @see #setCertificateChecking - */ - public X509Certificate getCertificateChecking() - { - return certChecking; - } - - /** - * Returns a printable representation of the X509CRLSelector.
- *
- * Uses - * {@link org.spongycastle.asn1.x509.X509Name#toString X509Name.toString} to - * format the output - * - * @return a String describing the contents of the - * X509CRLSelector. - */ - public String toString() - { - StringBuffer s = new StringBuffer(); - s.append("X509CRLSelector: [\n"); - if (issuerNamesX509 != null) - { - s.append(" IssuerNames:\n"); - Iterator iter = issuerNamesX509.iterator(); - while (iter.hasNext()) - { - s.append(" ").append(iter.next()).append('\n'); - } - } - if (minCRL != null) - { - s.append(" minCRLNumber: ").append(minCRL).append('\n'); - } - if (maxCRL != null) - { - s.append(" maxCRLNumber: ").append(maxCRL).append('\n'); - } - if (dateAndTime != null) - { - s.append(" dateAndTime: ").append(dateAndTime).append('\n'); - } - if (certChecking != null) - { - s.append(" Certificate being checked: ").append(certChecking).append('\n'); - } - s.append(']'); - return s.toString(); - } - - /** - * Decides whether a CRL should be selected.
- *
- * Uses - * {@link org.spongycastle.asn1.x509.X509Name#toString X509Name.toString} to - * parse and to compare the crl parameter issuer and - * {@link org.spongycastle.asn1.x509.X509Extensions#CRLNumber CRLNumber} to - * access the CRL number extension. - * - * @param crl - * the CRL to be checked - * - * @return true if the CRL should be selected, - * false otherwise - */ - public boolean match(CRL crl) - { - if (!(crl instanceof X509CRL)) - { - return false; - } - - X509CRL crlX509 = (X509CRL)crl; - boolean test; - - if (issuerNamesX509 != null) - { - Iterator iter = issuerNamesX509.iterator(); - test = false; - X509Name crlIssuer = null; - try - { - crlIssuer = PrincipalUtil.getIssuerX509Principal(crlX509); - } - catch (Exception ex) - { - - return false; - } - - while (iter.hasNext()) - { - if (crlIssuer.equals(iter.next(), true)) - { - test = true; - break; - } - } - if (!test) - { - return false; - } - } - - byte[] data = crlX509.getExtensionValue(X509Extensions.CRLNumber - .getId()); - if (data != null) - { - try - { - ByteArrayInputStream inStream = new ByteArrayInputStream(data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - inStream = new ByteArrayInputStream( - ((ASN1OctetString)derInputStream.readObject()) - .getOctets()); - derInputStream = new ASN1InputStream(inStream); - BigInteger crlNumber = ((ASN1Integer)derInputStream.readObject()) - .getPositiveValue(); - if (minCRL != null && minCRL.compareTo(crlNumber) > 0) - { - return false; - } - if (maxCRL != null && maxCRL.compareTo(crlNumber) < 0) - { - return false; - } - } - catch (IOException ex) - { - return false; - } - } - else if (minCRL != null || maxCRL != null) - { - return false; - } - - if (dateAndTime != null) - { - Date check = crlX509.getThisUpdate(); - if (check == null) - { - return false; - } - else if (dateAndTime.before(check)) - { - return false; - } - - check = crlX509.getNextUpdate(); - if (check == null) - { - return false; - } - else if (!dateAndTime.before(check)) - { - return false; - } - } - - return true; - } - - /** - * Returns a copy of this object. - * - * @return the copy - */ - public Object clone() - { - try - { - X509CRLSelector copy = (X509CRLSelector)super.clone(); - if (issuerNames != null) - { - copy.issuerNames = new HashSet(); - Iterator iter = issuerNames.iterator(); - Object obj; - while (iter.hasNext()) - { - obj = iter.next(); - if (obj instanceof byte[]) - { - copy.issuerNames.add(((byte[])obj).clone()); - } - else - { - copy.issuerNames.add(obj); - } - } - copy.issuerNamesX509 = new HashSet(issuerNamesX509); - } - return copy; - } - catch (CloneNotSupportedException e) - { - /* Cannot happen */ - throw new InternalError(e.toString()); - } - } - - /** - * Decides whether a CRL should be selected. - * - * @param crl - * the CRL to be checked - * - * @return true if the CRL should be selected, - * false otherwise - */ - public boolean equals(Object obj) - { - if (!(obj instanceof X509CRLSelector)) - { - return false; - } - - X509CRLSelector equalsCRL = (X509CRLSelector)obj; - - if (!equals(dateAndTime, equalsCRL.dateAndTime)) - { - return false; - } - - if (!equals(minCRL, equalsCRL.minCRL)) - { - return false; - } - - if (!equals(maxCRL, equalsCRL.maxCRL)) - { - return false; - } - - if (!equals(issuerNamesX509, equalsCRL.issuerNamesX509)) - { - return false; - } - - if (!equals(certChecking, equalsCRL.certChecking)) - { - return false; - } - - return true; - } - - /** - * Return true if two Objects are unequal. - * This means that one is null and the other is - * not or obj1.equals(obj2) returns - * false. - **/ - private boolean equals(Object obj1, Object obj2) - { - if (obj1 == null) - { - if (obj2 != null) - { - return true; - } - } - else if (!obj1.equals(obj2)) - { - return true; - } - return false; - } -} \ No newline at end of file diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/X509CertSelector.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/X509CertSelector.java deleted file mode 100644 index 0b288faa4..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/X509CertSelector.java +++ /dev/null @@ -1,2469 +0,0 @@ -package org.spongycastle.jce.cert; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.security.PublicKey; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Object; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1TaggedObject; -import org.spongycastle.asn1.DERGeneralizedTime; -import org.spongycastle.asn1.ASN1GeneralizedTime; -import org.spongycastle.asn1.DEROutputStream; -import org.spongycastle.asn1.util.ASN1Dump; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.ExtendedKeyUsage; -import org.spongycastle.asn1.x509.KeyPurposeId; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x509.X509Extensions; -import org.spongycastle.asn1.x509.X509Name; -import org.spongycastle.jce.PrincipalUtil; -import org.spongycastle.util.Integers; - -/** - * A CertSelector that selects - * X509Certificates that match all - * specified criteria. This class is particularly useful when - * selecting certificates from a CertStore to build a PKIX-compliant - * certification path.
- *
- * When first constructed, an X509CertSelector has no criteria enabled - * and each of the get methods return a default value (null, or -1 for - * the {@link #getBasicConstraints} method). Therefore, the {@link #match} method would - * return true for any X509Certificate. Typically, several criteria - * are enabled (by calling {@link #setIssuer} or {@link #setKeyUsage}, for instance) and - * then the X509CertSelector is passed to {@link CertStore#getCertificates} or - * some similar method.
- *
- * Several criteria can be enabled (by calling {@link #setIssuer} and - * {@link #setSerialNumber}, for example) such that the match method usually - * uniquely matches a single X509Certificate. We say usually, since it - * is possible for two issuing CAs to have the same distinguished name - * and each issue a certificate with the same serial number. Other - * unique combinations include the issuer, subject, - * subjectKeyIdentifier and/or the subjectPublicKey criteria.
- *
- * Please refer to RFC 2459 for definitions of the X.509 certificate - * extensions mentioned below.
- *
- * Concurrent Access
- *
- * Unless otherwise specified, the methods defined in this class are - * not thread-safe. Multiple threads that need to access a single - * object concurrently should synchronize amongst themselves and - * provide the necessary locking. Multiple threads each manipulating - * separate objects need not synchronize.
- *
- * TODO: implement name constraints - * TODO: implement match check for path to names
- *
- * Uses {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Sequence ASN1Sequence}, - * {@link org.spongycastle.asn1.ASN1ObjectIdentifier ASN1ObjectIdentifier}, - * {@link org.spongycastle.asn1.DEROutputStream DEROutputStream}, - * {@link org.spongycastle.asn1.ASN1Object ASN1Object}, - * {@link org.spongycastle.asn1.OIDTokenizer OIDTokenizer}, - * {@link org.spongycastle.asn1.x509.X509Name X509Name}, - * {@link org.spongycastle.asn1.x509.X509Extensions X509Extensions}, - * {@link org.spongycastle.asn1.x509.ExtendedKeyUsage ExtendedKeyUsage}, - * {@link org.spongycastle.asn1.x509.KeyPurposeId KeyPurposeId}, - * {@link org.spongycastle.asn1.x509.SubjectPublicKeyInfo SubjectPublicKeyInfo}, - * {@link org.spongycastle.asn1.x509.AlgorithmIdentifier AlgorithmIdentifier} - */ -public class X509CertSelector implements CertSelector -{ - private static final Hashtable keyPurposeIdMap = new Hashtable(); - static - { - keyPurposeIdMap.put(KeyPurposeId.id_kp_serverAuth.getId(), - KeyPurposeId.id_kp_serverAuth); - keyPurposeIdMap.put(KeyPurposeId.id_kp_clientAuth.getId(), - KeyPurposeId.id_kp_clientAuth); - keyPurposeIdMap.put(KeyPurposeId.id_kp_codeSigning.getId(), - KeyPurposeId.id_kp_codeSigning); - keyPurposeIdMap.put(KeyPurposeId.id_kp_emailProtection.getId(), - KeyPurposeId.id_kp_emailProtection); - keyPurposeIdMap.put(KeyPurposeId.id_kp_ipsecEndSystem.getId(), - KeyPurposeId.id_kp_ipsecEndSystem); - keyPurposeIdMap.put(KeyPurposeId.id_kp_ipsecTunnel.getId(), - KeyPurposeId.id_kp_ipsecTunnel); - keyPurposeIdMap.put(KeyPurposeId.id_kp_ipsecUser.getId(), - KeyPurposeId.id_kp_ipsecUser); - keyPurposeIdMap.put(KeyPurposeId.id_kp_timeStamping.getId(), - KeyPurposeId.id_kp_timeStamping); - } - - private X509Certificate x509Cert = null; - - private BigInteger serialNumber = null; - - private Object issuerDN = null; - - private X509Name issuerDNX509 = null; - - private Object subjectDN = null; - - private X509Name subjectDNX509 = null; - - private byte[] subjectKeyID = null; - - private byte[] authorityKeyID = null; - - private Date certValid = null; - - private Date privateKeyValid = null; - - private ASN1ObjectIdentifier subjectKeyAlgID = null; - - private PublicKey subjectPublicKey = null; - - private byte[] subjectPublicKeyByte = null; - - private boolean[] keyUsage = null; - - private Set keyPurposeSet = null; - - private boolean matchAllSubjectAltNames = true; - - private Set subjectAltNames = null; - - private Set subjectAltNamesByte = null; - - private int minMaxPathLen = -1; - - private Set policy = null; - - private Set policyOID = null; - - private Set pathToNames = null; - - private Set pathToNamesByte = null; - - /** - * Creates an X509CertSelector. Initially, no criteria are - * set so any X509Certificate will match. - */ - public X509CertSelector() - { - } - - /** - * Sets the certificateEquals criterion. The specified - * X509Certificate must be equal to the - * X509Certificate passed to the match method. If - * null, then this check is not applied.
- *
- * This method is particularly useful when it is necessary to match a single - * certificate. Although other criteria can be specified in conjunction with - * the certificateEquals criterion, it is usually not practical or - * necessary. - * - * @param cert - * the X509Certificate to match (or null) - * - * @see #getCertificate() - */ - public void setCertificate(X509Certificate cert) - { - x509Cert = cert; - } - - /** - * Sets the serialNumber criterion. The specified serial number must match - * the certificate serial number in the X509Certificate. If - * null, any certificate serial number will do. - * - * @param serial - * the certificate serial number to match (or null) - * - * @see #getSerialNumber() - */ - public void setSerialNumber(BigInteger serial) - { - serialNumber = serial; - } - - /** - * Sets the issuer criterion. The specified distinguished name must match - * the issuer distinguished name in the X509Certificate. If - * null, any issuer distinguished name will do.
- *
- * If issuerDN is not null, it should contain - * a distinguished name, in RFC 2253 format.
- *
- * Uses {@link org.spongycastle.asn1.x509.X509Name X509Name} for parsing the - * issuerDN. - * - * @param issuerDN - * a distinguished name in RFC 2253 format (or null) - * - * @exception IOException - * if a parsing error occurs (incorrect form for DN) - */ - public void setIssuer(String issuerDN) throws IOException - { - if (issuerDN == null) - { - this.issuerDN = null; - this.issuerDNX509 = null; - } - else - { - X509Name nameX509; - try - { - nameX509 = new X509Name(issuerDN); - } - catch (IllegalArgumentException ex) - { - throw new IOException(ex.getMessage()); - } - this.issuerDNX509 = nameX509; - this.issuerDN = issuerDN; - } - } - - /** - * Sets the issuer criterion. The specified distinguished name must match - * the issuer distinguished name in the X509Certificate. If - * null is specified, the issuer criterion is disabled and any issuer - * distinguished name will do.
- *
- * If issuerDN is not null, it should contain - * a single DER encoded distinguished name, as defined in X.501. The ASN.1 - * notation for this structure is as follows.
- *
- * - *
-     *    Name ::= CHOICE {
-     *      RDNSequence }
-     * 
-     *    RDNSequence ::= SEQUENCE OF RDN
-     * 
-     *    RDN ::=
-     *      SET SIZE (1 .. MAX) OF AttributeTypeAndValue
-     * 
-     *    AttributeTypeAndValue ::= SEQUENCE {
-     *      type     AttributeType,
-     *      value    AttributeValue }
-     * 
-     *    AttributeType ::= OBJECT IDENTIFIER
-     * 
-     *    AttributeValue ::= ANY DEFINED BY AttributeType
-     *    ....
-     *    DirectoryString ::= CHOICE {
-     *      teletexString           TeletexString (SIZE (1..MAX)),
-     *      printableString         PrintableString (SIZE (1..MAX)),
-     *      universalString         UniversalString (SIZE (1..MAX)),
-     *      utf8String              UTF8String (SIZE (1.. MAX)),
-     *      bmpString               BMPString (SIZE (1..MAX)) }
-     * 
- * - *
- *
- * Note that the byte array specified here is cloned to protect against - * subsequent modifications.
- *
- * Uses {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Object ASN1Object}, - * {@link org.spongycastle.asn1.ASN1Sequence ASN1Sequence}, - * {@link org.spongycastle.asn1.x509.X509Name X509Name} - * - * @param issuerDN - - * a byte array containing the distinguished name in ASN.1 DER - * encoded form (or null) - * - * @exception IOException - * if an encoding error occurs (incorrect form for DN) - */ - public void setIssuer(byte[] issuerDN) throws IOException - { - if (issuerDN == null) - { - this.issuerDN = null; - this.issuerDNX509 = null; - } - else - { - ByteArrayInputStream inStream = new ByteArrayInputStream(issuerDN); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object obj = derInStream.readObject(); - if (obj instanceof ASN1Sequence) - { - this.issuerDNX509 = new X509Name((ASN1Sequence)obj); - } - else - { - throw new IOException("parsing error"); - } - this.issuerDN = (byte[])issuerDN.clone(); - } - } - - /** - * Sets the subject criterion. The specified distinguished name must match - * the subject distinguished name in the X509Certificate. If - * null, any subject distinguished name will do.
- *
- * If subjectDN is not null, it should - * contain a distinguished name, in RFC 2253 format.
- *
- * Uses {@link org.spongycastle.asn1.x509.X509Name X509Name} for parsing the - * subjectDN. - * - * @param subjectDN - * a distinguished name in RFC 2253 format (or null) - * - * @exception IOException - * if a parsing error occurs (incorrect form for DN) - */ - public void setSubject(String subjectDN) throws IOException - { - if (subjectDN == null) - { - this.subjectDN = null; - this.subjectDNX509 = null; - } - else - { - X509Name nameX509; - try - { - nameX509 = new X509Name(subjectDN); - } - catch (IllegalArgumentException ex) - { - throw new IOException(ex.getMessage()); - } - - this.subjectDNX509 = nameX509; - this.subjectDN = subjectDN; - } - } - - /** - * Sets the subject criterion. The specified distinguished name must match - * the subject distinguished name in the X509Certificate. If - * null, any subject distinguished name will do.
- *
- * If subjectDN is not null, it should - * contain a single DER encoded distinguished name, as defined in X.501. For - * the ASN.1 notation for this structure, see - * {@link #setIssuer(byte []) setIssuer(byte [] issuerDN)}.
- *
- * Uses {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Object ASN1Object}, - * {@link org.spongycastle.asn1.ASN1Sequence ASN1Sequence}, - * {@link org.spongycastle.asn1.x509.X509Name X509Name} - * - * @param subjectDN - * a byte array containing the distinguished name in ASN.1 DER - * format (or null) - * - * @exception IOException - * if an encoding error occurs (incorrect form for DN) - */ - public void setSubject(byte[] subjectDN) throws IOException - { - if (subjectDN == null) - { - this.subjectDN = null; - this.subjectDNX509 = null; - } - else - { - ByteArrayInputStream inStream = new ByteArrayInputStream(subjectDN); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object obj = derInStream.readObject(); - - if (obj instanceof ASN1Sequence) - { - this.subjectDNX509 = new X509Name((ASN1Sequence)obj); - } - else - { - throw new IOException("parsing error"); - } - this.subjectDN = (byte[])subjectDN.clone(); - } - } - - /** - * Sets the subjectKeyIdentifier criterion. The X509Certificate - * must contain a SubjectKeyIdentifier extension for which the contents of - * the extension matches the specified criterion value. If the criterion - * value is null, no subjectKeyIdentifier check will be done.
- *
- * If subjectKeyID is not null, it should - * contain a single DER encoded value corresponding to the contents of the - * extension value (not including the object identifier, criticality - * setting, and encapsulating OCTET STRING) for a SubjectKeyIdentifier - * extension. The ASN.1 notation for this structure follows.
- *
- * - *
-     *    SubjectKeyIdentifier ::= KeyIdentifier
-     * 
-     *    KeyIdentifier ::= OCTET STRING
-     * 
- * - *
- *
- * Since the format of subject key identifiers is not mandated by any - * standard, subject key identifiers are not parsed by the - * X509CertSelector. Instead, the values are compared using - * a byte-by-byte comparison.
- *
- * Note that the byte array supplied here is cloned to protect against - * subsequent modifications. - * - * @param subjectKeyID - - * the subject key identifier (or null) - * - * @see #getSubjectKeyIdentifier() - */ - public void setSubjectKeyIdentifier(byte[] subjectKeyID) - { - if (subjectKeyID == null) - { - this.subjectKeyID = null; - } - else - { - this.subjectKeyID = (byte[])subjectKeyID.clone(); - } - } - - /** - * Sets the authorityKeyIdentifier criterion. The - * X509Certificate must contain an AuthorityKeyIdentifier - * extension for which the contents of the extension value matches the - * specified criterion value. If the criterion value is null, - * no authorityKeyIdentifier check will be done.
- *
- * If authorityKeyID is not null, it should - * contain a single DER encoded value corresponding to the contents of the - * extension value (not including the object identifier, criticality - * setting, and encapsulating OCTET STRING) for an AuthorityKeyIdentifier - * extension. The ASN.1 notation for this structure follows.
- *
- * - *
-     *    AuthorityKeyIdentifier ::= SEQUENCE {
-     *      keyIdentifier             [0] KeyIdentifier           OPTIONAL,
-     *      authorityCertIssuer       [1] GeneralNames            OPTIONAL,
-     *      authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL  }
-     * 
-     *    KeyIdentifier ::= OCTET STRING
-     * 
- * - *
- *
- * Authority key identifiers are not parsed by the - * X509CertSelector. Instead, the values are compared using - * a byte-by-byte comparison.
- *
- * When the keyIdentifier field of - * AuthorityKeyIdentifier is populated, the value is usually - * taken from the SubjectKeyIdentifier extension in the issuer's - * certificate. Note, however, that the result of - * X509Certificate.getExtensionValue() on the issuer's certificate may NOT be used directly as the - * input to setAuthorityKeyIdentifier. This is because the - * SubjectKeyIdentifier contains only a KeyIdentifier OCTET STRING, and not - * a SEQUENCE of KeyIdentifier, GeneralNames, and CertificateSerialNumber. - * In order to use the extension value of the issuer certificate's - * SubjectKeyIdentifier extension, it will be necessary to extract the value - * of the embedded KeyIdentifier OCTET STRING, then DER encode this OCTET - * STRING inside a SEQUENCE. For more details on SubjectKeyIdentifier, see - * {@link #setSubjectKeyIdentifier(byte[]) setSubjectKeyIdentifier(byte[] subjectKeyID }).
- *
- * Note also that the byte array supplied here is cloned to protect against - * subsequent modifications. - * - * @param authorityKeyID - * the authority key identifier (or null) - * - * @see #getAuthorityKeyIdentifier() - */ - public void setAuthorityKeyIdentifier(byte[] authorityKeyID) - { - if (authorityKeyID == null) - { - this.authorityKeyID = null; - } - else - { - this.authorityKeyID = (byte[])authorityKeyID.clone(); - } - } - - /** - * Sets the certificateValid criterion. The specified date must fall within - * the certificate validity period for the X509Certificate. If - * null, no certificateValid check will be done.
- *
- * Note that the Date supplied here is cloned to protect against subsequent - * modifications. - * - * @param certValid - * the Date to check (or null) - * - * @see #getCertificateValid() - */ - public void setCertificateValid(Date certValid) - { - if (certValid == null) - { - this.certValid = null; - } - else - { - this.certValid = new Date(certValid.getTime()); - } - } - - /** - * Sets the privateKeyValid criterion. The specified date must fall within - * the private key validity period for the X509Certificate. If - * null, no privateKeyValid check will be done.
- *
- * Note that the Date supplied here is cloned to protect against subsequent - * modifications. - * - * @param privateKeyValid - * the Date to check (or null) - * - * @see #getPrivateKeyValid() - */ - public void setPrivateKeyValid(Date privateKeyValid) - { - if (privateKeyValid == null) - { - this.privateKeyValid = null; - } - else - { - this.privateKeyValid = new Date(privateKeyValid.getTime()); - } - } - - /** - * Sets the subjectPublicKeyAlgID criterion. The X509Certificate must - * contain a subject public key with the specified algorithm. If - * null, no subjectPublicKeyAlgID check will be done. - * - * @param oid - * The object identifier (OID) of the algorithm to check for (or - * null). An OID is represented by a set of - * nonnegative integers separated by periods. - * - * @exception IOException - * if the OID is invalid, such as the first component being - * not 0, 1 or 2 or the second component being greater than - * 39. - * - * @see #getSubjectPublicKeyAlgID() - */ - public void setSubjectPublicKeyAlgID(String oid) throws IOException - { - if (oid != null) - { - CertUtil.parseOID(oid); - subjectKeyAlgID = new ASN1ObjectIdentifier(oid); - } - else - { - subjectKeyAlgID = null; - } - } - - /** - * Sets the subjectPublicKey criterion. The X509Certificate must contain the - * specified subject public key. If null, no subjectPublicKey check will be - * done. - * - * @param key - * the subject public key to check for (or null) - * - * @see #getSubjectPublicKey() - */ - public void setSubjectPublicKey(PublicKey key) - { - if (key == null) - { - subjectPublicKey = null; - subjectPublicKeyByte = null; - } - else - { - subjectPublicKey = key; - subjectPublicKeyByte = key.getEncoded(); - } - } - - /** - * Sets the subjectPublicKey criterion. The X509Certificate - * must contain the specified subject public key. If null, - * no subjectPublicKey check will be done.
- *
- * Because this method allows the public key to be specified as a byte - * array, it may be used for unknown key types.
- *
- * If key is not null, it should contain a single DER - * encoded SubjectPublicKeyInfo structure, as defined in X.509. The ASN.1 - * notation for this structure is as follows.
- *
- * - *
-     *    SubjectPublicKeyInfo  ::=  SEQUENCE  {
-     *      algorithm            AlgorithmIdentifier,
-     *      subjectPublicKey     BIT STRING  }
-     * 
-     *    AlgorithmIdentifier  ::=  SEQUENCE  {
-     *      algorithm               OBJECT IDENTIFIER,
-     *      parameters              ANY DEFINED BY algorithm OPTIONAL  }
-     *                                -- contains a value of the type
-     *                                -- registered for use with the
-     *                                -- algorithm object identifier value
-     * 
- * - *
- *
- * Note that the byte array supplied here is cloned to protect against - * subsequent modifications. - * - * @param key - * a byte array containing the subject public key in ASN.1 DER - * form (or null) - * - * @exception IOException - * if an encoding error occurs (incorrect form for subject - * public key) - * - * @see #getSubjectPublicKey() - */ - public void setSubjectPublicKey(byte[] key) throws IOException - { - if (key == null) - { - subjectPublicKey = null; - subjectPublicKeyByte = null; - } - else - { - subjectPublicKey = null; - subjectPublicKeyByte = (byte[])key.clone(); - // TODO - // try to generyte PublicKey Object from subjectPublicKeyByte - } - } - - /** - * Sets the keyUsage criterion. The X509Certificate must allow the specified - * keyUsage values. If null, no keyUsage check will be done. Note that an - * X509Certificate that has no keyUsage extension implicitly allows all - * keyUsage values.
- *
- * Note that the boolean array supplied here is cloned to protect against - * subsequent modifications. - * - * @param keyUsage - * a boolean array in the same format as the boolean array - * returned by X509Certificate.getKeyUsage(). Or - * null. - * - * @see #getKeyUsage() - */ - public void setKeyUsage(boolean[] keyUsage) - { - if (keyUsage == null) - { - this.keyUsage = null; - } - else - { - this.keyUsage = (boolean[])keyUsage.clone(); - } - } - - /** - * Sets the extendedKeyUsage criterion. The X509Certificate - * must allow the specified key purposes in its extended key usage - * extension. If keyPurposeSet is empty or null, - * no extendedKeyUsage check will be done. Note that an - * X509Certificate that has no extendedKeyUsage extension - * implicitly allows all key purposes.
- *
- * Note that the Set is cloned to protect against subsequent modifications.
- *
- * Uses {@link org.spongycastle.asn1.x509.KeyPurposeId KeyPurposeId} - * - * @param keyPurposeSet - * a Set of key purpose OIDs in string format (or - * null). Each OID is represented by a set of - * nonnegative integers separated by periods. - * - * @exception IOException - * if the OID is invalid, such as the first component being - * not 0, 1 or 2 or the second component being greater than - * 39. - * - * @see #getExtendedKeyUsage() - */ - public void setExtendedKeyUsage(Set keyPurposeSet) throws IOException - { - if (keyPurposeSet == null || keyPurposeSet.isEmpty()) - { - this.keyPurposeSet = keyPurposeSet; - } - else - { - this.keyPurposeSet = new HashSet(); - Iterator iter = keyPurposeSet.iterator(); - Object obj; - KeyPurposeId purposeID; - while (iter.hasNext()) - { - obj = iter.next(); - if (obj instanceof String) - { - purposeID = (KeyPurposeId)keyPurposeIdMap.get((String)obj); - if (purposeID == null) - { - throw new IOException("unknown purposeID " - + (String)obj); - } - this.keyPurposeSet.add(purposeID); - } - } - } - } - - /** - * Enables/disables matching all of the subjectAlternativeNames specified in - * the {@link #setSubjectAlternativeNames setSubjectAlternativeNames} or - * {@link #addSubjectAlternativeName addSubjectAlternativeName} methods. If - * enabled, the X509Certificate must contain all of the - * specified subject alternative names. If disabled, the X509Certificate - * must contain at least one of the specified subject alternative names.
- *
- * The matchAllNames flag is true by default. - * - * @param matchAllNames - * if true, the flag is enabled; if - * false, the flag is disabled. - * - * @see #getMatchAllSubjectAltNames() - */ - public void setMatchAllSubjectAltNames(boolean matchAllNames) - { - matchAllSubjectAltNames = matchAllNames; - } - - /** - * Sets the subjectAlternativeNames criterion. The - * X509Certificate must contain all or at least one of the - * specified subjectAlternativeNames, depending on the value of the - * matchAllNames flag (see {@link #setMatchAllSubjectAltNames}).
- *
- * This method allows the caller to specify, with a single method call, the - * complete set of subject alternative names for the subjectAlternativeNames - * criterion. The specified value replaces the previous value for the - * subjectAlternativeNames criterion.
- *
- * The names parameter (if not null) is a - * Collection with one entry for each name to be included in - * the subject alternative name criterion. Each entry is a List - * whose first entry is an Integer (the name type, 0-8) and - * whose second entry is a String or a byte array (the name, - * in string or ASN.1 DER encoded form, respectively). There can be multiple - * names of the same type. If null is supplied as the value - * for this argument, no subjectAlternativeNames check will be performed.
- *
- * Each subject alternative name in the Collection may be - * specified either as a String or as an ASN.1 encoded byte - * array. For more details about the formats used, see - * {@link #addSubjectAlternativeName(int, String) addSubjectAlternativeName(int type, String name)} - * and - * {@link #addSubjectAlternativeName(int, byte[]) addSubjectAlternativeName(int type, byte [] name}).
- *
- * Note that the names parameter can contain duplicate names - * (same name and name type), but they may be removed from the - * Collection of names returned by the - * {@link #getSubjectAlternativeNames} method.
- *
- * Note that a deep copy is performed on the Collection to protect against - * subsequent modifications. - * - * @param names - - * a Collection of names (or null) - * - * @exception IOException - * if a parsing error occurs - * - * @see #getSubjectAlternativeNames() - */ - public void setSubjectAlternativeNames(Collection names) throws IOException - { - try - { - if (names == null || names.isEmpty()) - { - subjectAltNames = null; - subjectAltNamesByte = null; - } - else - { - subjectAltNames = new HashSet(); - subjectAltNamesByte = new HashSet(); - Iterator iter = names.iterator(); - List item; - int type; - Object data; - while (iter.hasNext()) - { - item = (List)iter.next(); - type = ((Integer)item.get(0)).intValue(); - data = item.get(1); - if (data instanceof String) - { - addSubjectAlternativeName(type, (String)data); - } - else if (data instanceof byte[]) - { - addSubjectAlternativeName(type, (byte[])data); - } - else - { - throw new IOException( - "parsing error: unknown data type"); - } - } - } - } - catch (Exception ex) - { - throw new IOException("parsing exception:\n" + ex.toString()); - } - } - - /** - * Adds a name to the subjectAlternativeNames criterion. The - * X509Certificate must contain all or at least one of the - * specified subjectAlternativeNames, depending on the value of the - * matchAllNames flag (see {@link #setMatchAllSubjectAltNames}).
- *
- * This method allows the caller to add a name to the set of subject - * alternative names. The specified name is added to any previous value for - * the subjectAlternativeNames criterion. If the specified name is a - * duplicate, it may be ignored.
- *
- * The name is provided in string format. RFC 822, DNS, and URI names use - * the well-established string formats for those types (subject to the - * restrictions included in RFC 2459). IPv4 address names are supplied using - * dotted quad notation. OID address names are represented as a series of - * nonnegative integers separated by periods. And directory names - * (distinguished names) are supplied in RFC 2253 format. No standard string - * format is defined for otherNames, X.400 names, EDI party names, IPv6 - * address names, or any other type of names. They should be specified using - * the - * {@link #addSubjectAlternativeName(int, byte[]) addSubjectAlternativeName(int type, byte [] name)} - * method. - * - * @param type - * the name type (0-8, as specified in RFC 2459, section 4.2.1.7) - * @param name - - * the name in string form (not null) - * - * @exception IOException - * if a parsing error occurs - */ - public void addSubjectAlternativeName(int type, String name) - throws IOException - { - // TODO full implementation of CertUtil.parseGeneralName - byte[] encoded = CertUtil.parseGeneralName(type, name); - List tmpList = new ArrayList(); - tmpList.add(Integers.valueOf(type)); - tmpList.add(name); - subjectAltNames.add(tmpList); - tmpList.set(1, encoded); - subjectAltNamesByte.add(tmpList); - } - - /** - * Adds a name to the subjectAlternativeNames criterion. The - * X509Certificate must contain all or at least one of the - * specified subjectAlternativeNames, depending on the value of the - * matchAllNames flag (see {@link #setMatchAllSubjectAltNames}).
- *
- * This method allows the caller to add a name to the set of subject - * alternative names. The specified name is added to any previous value for - * the subjectAlternativeNames criterion. If the specified name is a - * duplicate, it may be ignored.
- *
- * The name is provided as a byte array. This byte array should contain the - * DER encoded name, as it would appear in the GeneralName structure defined - * in RFC 2459 and X.509. The encoded byte array should only contain the - * encoded value of the name, and should not include the tag associated with - * the name in the GeneralName structure. The ASN.1 definition of this - * structure appears below.
- *
- * - *
-     *    GeneralName ::= CHOICE {
-     *        otherName                       [0]     OtherName,
-     *        rfc822Name                      [1]     IA5String,
-     *        dNSName                         [2]     IA5String,
-     *        x400Address                     [3]     ORAddress,
-     *        directoryName                   [4]     Name,
-     *        ediPartyName                    [5]     EDIPartyName,
-     *        uniformResourceIdentifier       [6]     IA5String,
-     *        iPAddress                       [7]     OCTET STRING,
-     *        registeredID                    [8]     OBJECT IDENTIFIER}
-     * 
- * - *
- *
- * Note that the byte array supplied here is cloned to protect against - * subsequent modifications.
- *
- * TODO: check encoded format - * - * @param type - * the name type (0-8, as listed above) - * @param name - * a byte array containing the name in ASN.1 DER encoded form - * - * @exception IOException - * if a parsing error occurs - */ - public void addSubjectAlternativeName(int type, byte[] name) - throws IOException - { - // TODO check encoded format - List tmpList = new ArrayList(); - tmpList.add(Integers.valueOf(type)); - tmpList.add(name.clone()); - subjectAltNames.add(tmpList); - subjectAltNamesByte.add(tmpList); - } - - /** - * Sets the name constraints criterion. The X509Certificate - * must have subject and subject alternative names that meet the specified - * name constraints.
- *
- * The name constraints are specified as a byte array. This byte array - * should contain the DER encoded form of the name constraints, as they - * would appear in the NameConstraints structure defined in RFC 2459 and - * X.509. The ASN.1 definition of this structure appears below.
- *
- * - *
-     *   NameConstraints ::= SEQUENCE {
-     *        permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
-     *        excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
-     * 
-     *   GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
-     * 
-     *   GeneralSubtree ::= SEQUENCE {
-     *        base                    GeneralName,
-     *        minimum         [0]     BaseDistance DEFAULT 0,
-     *        maximum         [1]     BaseDistance OPTIONAL }
-     * 
-     *   BaseDistance ::= INTEGER (0..MAX)
-     * 
-     *   GeneralName ::= CHOICE {
-     *        otherName                       [0]     OtherName,
-     *        rfc822Name                      [1]     IA5String,
-     *        dNSName                         [2]     IA5String,
-     *        x400Address                     [3]     ORAddress,
-     *        directoryName                   [4]     Name,
-     *        ediPartyName                    [5]     EDIPartyName,
-     *        uniformResourceIdentifier       [6]     IA5String,
-     *        iPAddress                       [7]     OCTET STRING,
-     *        registeredID                    [8]     OBJECT IDENTIFIER}
-     * 
- * - *
- *
- * Note that the byte array supplied here is cloned to protect against - * subsequent modifications.
- *
- * TODO: implement this - * - * @param bytes - * a byte array containing the ASN.1 DER encoding of a - * NameConstraints extension to be used for checking name - * constraints. Only the value of the extension is included, not - * the OID or criticality flag. Can be null, in - * which case no name constraints check will be performed - * - * @exception IOException - * if a parsing error occurs - * @exception UnsupportedOperationException - * because this method is not supported - * @see #getNameConstraints() - */ - public void setNameConstraints(byte[] bytes) throws IOException - { - throw new UnsupportedOperationException(); - } - - /** - * Sets the basic constraints constraint. If the value is greater than or - * equal to zero, X509Certificates must include a - * basicConstraints extension with a pathLen of at least this value. If the - * value is -2, only end-entity certificates are accepted. If the value is - * -1, no check is done.
- *
- * This constraint is useful when building a certification path forward - * (from the target toward the trust anchor. If a partial path has been - * built, any candidate certificate must have a maxPathLen value greater - * than or equal to the number of certificates in the partial path. - * - * @param minMaxPathLen - * the value for the basic constraints constraint - * - * @exception IllegalArgumentException - * if the value is less than -2 - * - * @see #getBasicConstraints() - */ - public void setBasicConstraints(int minMaxPathLen) - { - if (minMaxPathLen < -2) - { - throw new IllegalArgumentException("minMaxPathLen must be >= -2"); - } - - this.minMaxPathLen = minMaxPathLen; - } - - /** - * Sets the policy constraint. The X509Certificate must include at least one - * of the specified policies in its certificate policies extension. If - * certPolicySet is empty, then the X509Certificate must include at least - * some specified policy in its certificate policies extension. If - * certPolicySet is null, no policy check will be performed.
- *
- * Note that the Set is cloned to protect against subsequent modifications.
- *
- * TODO: implement match check for this - * - * @param certPolicySet - * a Set of certificate policy OIDs in string format (or null). - * Each OID is represented by a set of nonnegative integers - * separated by periods. - * - * @exception IOException - * if a parsing error occurs on the OID such as the first - * component is not 0, 1 or 2 or the second component is - * greater than 39. - * - * @see #getPolicy() - */ - public void setPolicy(Set certPolicySet) throws IOException - { - if (certPolicySet == null) - { - policy = null; - policyOID = null; - } - else - { - policyOID = new HashSet(); - Iterator iter = certPolicySet.iterator(); - Object item; - while (iter.hasNext()) - { - item = iter.next(); - if (item instanceof String) - { - CertUtil.parseOID((String)item); - policyOID.add(new ASN1ObjectIdentifier((String)item)); - } - else - { - throw new IOException( - "certPolicySet contains null values or non String objects"); - } - } - policy = new HashSet(certPolicySet); - } - } - - /** - * Sets the pathToNames criterion. The X509Certificate must - * not include name constraints that would prohibit building a path to the - * specified names.
- *
- * This method allows the caller to specify, with a single method call, the - * complete set of names which the X509Certificates's name - * constraints must permit. The specified value replaces the previous value - * for the pathToNames criterion.
- *
- * This constraint is useful when building a certification path forward - * (from the target toward the trust anchor. If a partial path has been - * built, any candidate certificate must not include name constraints that - * would prohibit building a path to any of the names in the partial path.
- *
- * The names parameter (if not null) is a - * Collection with one entry for each name to be included in - * the pathToNames criterion. Each entry is a List whose - * first entry is an Integer (the name type, 0-8) and whose second entry is - * a String or a byte array (the name, in string or ASN.1 DER - * encoded form, respectively). There can be multiple names of the same - * type. If null is supplied as the value for this argument, - * no pathToNames check will be performed.
- *
- * Each name in the Collection may be specified either as a String or as an - * ASN.1 encoded byte array. For more details about the formats used, see - * {@link #addPathToName(int, String) addPathToName(int type, String name)} - * and - * {@link #addPathToName(int, byte[]) addPathToName(int type, byte [] name)}.
- *
- * Note that the names parameter can contain duplicate names (same name and - * name type), but they may be removed from the Collection of names returned - * by the {@link #getPathToNames} method.
- *
- * Note that a deep copy is performed on the Collection to protect against - * subsequent modifications.
- *
- * TODO: implement this match check for this - * - * @param names - * a Collection with one entry per name (or null) - * - * @exception IOException - * if a parsing error occurs - * @exception UnsupportedOperationException - * because this method is not supported - * - * @see #getPathToNames() - */ - public void setPathToNames(Collection names) throws IOException - { - try - { - if (names == null || names.isEmpty()) - { - pathToNames = null; - pathToNamesByte = null; - } - else - { - pathToNames = new HashSet(); - pathToNamesByte = new HashSet(); - Iterator iter = names.iterator(); - List item; - int type; - Object data; - - while (iter.hasNext()) - { - item = (List)iter.next(); - type = ((Integer)item.get(0)).intValue(); - data = item.get(1); - if (data instanceof String) - { - addPathToName(type, (String)data); - } - else if (data instanceof byte[]) - { - addPathToName(type, (byte[])data); - } - else - { - throw new IOException( - "parsing error: unknown data type"); - } - } - } - } - catch (Exception ex) - { - throw new IOException("parsing exception:\n" + ex.toString()); - } - } - - /** - * Adds a name to the pathToNames criterion. The - * X509Certificate must not include name constraints that - * would prohibit building a path to the specified name.
- *
- * This method allows the caller to add a name to the set of names which the - * X509Certificates's name constraints must permit. The - * specified name is added to any previous value for the pathToNames - * criterion. If the name is a duplicate, it may be ignored.
- *
- * The name is provided in string format. RFC 822, DNS, and URI names use - * the well-established string formats for those types (subject to the - * restrictions included in RFC 2459). IPv4 address names are supplied using - * dotted quad notation. OID address names are represented as a series of - * nonnegative integers separated by periods. And directory names - * (distinguished names) are supplied in RFC 2253 format. No standard string - * format is defined for otherNames, X.400 names, EDI party names, IPv6 - * address names, or any other type of names. They should be specified using - * the - * {@link #addPathToName(int, byte[]) addPathToName(int type, byte [] name)} - * method.
- *
- * TODO: implement this match check for this - * - * @param type - * the name type (0-8, as specified in RFC 2459, section 4.2.1.7) - * @param name - * the name in string form - * - * @exceptrion IOException if a parsing error occurs - */ - public void addPathToName(int type, String name) throws IOException - { - // TODO full implementation of CertUtil.parseGeneralName - byte[] encoded = CertUtil.parseGeneralName(type, name); - List tmpList = new ArrayList(); - tmpList.add(Integers.valueOf(type)); - tmpList.add(name); - pathToNames.add(tmpList); - tmpList.set(1, encoded); - pathToNamesByte.add(tmpList); - throw new UnsupportedOperationException(); - } - - /** - * Adds a name to the pathToNames criterion. The - * X509Certificate must not include name constraints that - * would prohibit building a path to the specified name.
- *
- * This method allows the caller to add a name to the set of names which the - * X509Certificates's name constraints must permit. The - * specified name is added to any previous value for the pathToNames - * criterion. If the name is a duplicate, it may be ignored.
- *
- * The name is provided as a byte array. This byte array should contain the - * DER encoded name, as it would appear in the GeneralName structure defined - * in RFC 2459 and X.509. The ASN.1 definition of this structure appears in - * the documentation for - * {@link #addSubjectAlternativeName(int,byte[]) addSubjectAlternativeName(int type, byte[] name)}.
- *
- * Note that the byte array supplied here is cloned to protect against - * subsequent modifications.
- *
- * TODO: implement this match check for this - * - * @param type - * the name type (0-8, as specified in RFC 2459, section 4.2.1.7) - * @param name - * a byte array containing the name in ASN.1 DER encoded form - * - * @exception IOException - * if a parsing error occurs - */ - public void addPathToName(int type, byte[] name) throws IOException - { - // TODO check encoded format - List tmpList = new ArrayList(); - tmpList.add(Integers.valueOf(type)); - tmpList.add(name.clone()); - pathToNames.add(tmpList); - pathToNamesByte.add(tmpList); - } - - /** - * Returns the certificateEquals criterion. The specified - * X509Certificate must be equal to the - * X509Certificate passed to the match method. If - * null, this check is not applied. - * - * @retrun the X509Certificate to match (or null) - * - * @see #setCertificate(java.security.cert.X509Certificate) - */ - public X509Certificate getCertificate() - { - return x509Cert; - } - - /** - * Returns the serialNumber criterion. The specified serial number must - * match the certificate serial number in the X509Certificate. - * If null, any certificate serial number will do. - * - * @return the certificate serial number to match (or null) - * - * @see #setSerialNumber(java.math.BigInteger) - */ - public BigInteger getSerialNumber() - { - return serialNumber; - } - - /** - * Returns the issuer criterion as a String. This distinguished name must - * match the issuer distinguished name in the X509Certificate. - * If null, the issuer criterion is disabled and any issuer - * distinguished name will do.
- *
- * If the value returned is not null, it is a distinguished - * name, in RFC 2253 format.
- *
- * Uses {@link org.spongycastle.asn1.x509.X509Name X509Name} for formatiing - * byte[] issuerDN to String. - * - * @return the required issuer distinguished name in RFC 2253 format (or - * null) - */ - public String getIssuerAsString() - { - if (issuerDN instanceof String) - { - return new String((String)issuerDN); - } - else if (issuerDNX509 != null) - { - return issuerDNX509.toString(); - } - - return null; - } - - /** - * Returns the issuer criterion as a byte array. This distinguished name - * must match the issuer distinguished name in the - * X509Certificate. If null, the issuer - * criterion is disabled and any issuer distinguished name will do.
- *
- * If the value returned is not null, it is a byte array - * containing a single DER encoded distinguished name, as defined in X.501. - * The ASN.1 notation for this structure is supplied in the documentation - * for {@link #setIssuer(byte[]) setIssuer(byte [] issuerDN)}.
- *
- * Note that the byte array returned is cloned to protect against subsequent - * modifications.
- *
- * Uses {@link org.spongycastle.asn1.DEROutputStream DEROutputStream}, - * {@link org.spongycastle.asn1.x509.X509Name X509Name} to gnerate byte[] - * output for String issuerDN. - * - * @return a byte array containing the required issuer distinguished name in - * ASN.1 DER format (or null) - * - * @exception IOException - * if an encoding error occurs - */ - public byte[] getIssuerAsBytes() throws IOException - { - if (issuerDN instanceof byte[]) - { - return (byte[])((byte[])issuerDN).clone(); - } - else if (issuerDNX509 != null) - { - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - DEROutputStream derOutStream = new DEROutputStream(outStream); - - derOutStream.writeObject(issuerDNX509.toASN1Primitive()); - derOutStream.close(); - - return outStream.toByteArray(); - } - - return null; - } - - /** - * Returns the subject criterion as a String. This distinguished name must - * match the subject distinguished name in the X509Certificate. - * If null, the subject criterion is disabled and any - * subject distinguished name will do.
- *
- * If the value returned is not null, it is a distinguished - * name, in RFC 2253 format.
- *
- * Uses {@link org.spongycastle.asn1.x509.X509Name X509Name} for formatiing - * byte[] subjectDN to String. - * - * @return the required subject distinguished name in RFC 2253 format (or - * null) - */ - public String getSubjectAsString() - { - if (subjectDN instanceof String) - { - return new String((String)subjectDN); - } - else if (subjectDNX509 != null) - { - return subjectDNX509.toString(); - } - - return null; - } - - /** - * Returns the subject criterion as a byte array. This distinguished name - * must match the subject distinguished name in the - * X509Certificate. If null, the subject - * criterion is disabled and any subject distinguished name will do.
- *
- * If the value returned is not null, it is a byte array - * containing a single DER encoded distinguished name, as defined in X.501. - * The ASN.1 notation for this structure is supplied in the documentation - * for {@link #setSubject(byte [] subjectDN) setSubject(byte [] subjectDN)}.
- *
- * Note that the byte array returned is cloned to protect against subsequent - * modifications.
- *
- * Uses {@link org.spongycastle.asn1.DEROutputStream DEROutputStream}, - * {@link org.spongycastle.asn1.x509.X509Name X509Name} to gnerate byte[] - * output for String subjectDN. - * - * @return a byte array containing the required subject distinguished name - * in ASN.1 DER format (or null) - * - * @exception IOException - * if an encoding error occurs - */ - public byte[] getSubjectAsBytes() throws IOException - { - if (subjectDN instanceof byte[]) - { - return (byte[])((byte[])subjectDN).clone(); - } - else if (subjectDNX509 != null) - { - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - DEROutputStream derOutStream = new DEROutputStream(outStream); - - derOutStream.writeObject(subjectDNX509.toASN1Primitive()); - derOutStream.close(); - - return outStream.toByteArray(); - } - - return null; - } - - /** - * Returns the subjectKeyIdentifier criterion. The - * X509Certificate must contain a SubjectKeyIdentifier - * extension with the specified value. If null, no - * subjectKeyIdentifier check will be done.
- *
- * Note that the byte array returned is cloned to protect against subsequent - * modifications. - * - * @return the key identifier (or null) - * - * @see #setSubjectKeyIdentifier - */ - public byte[] getSubjectKeyIdentifier() - { - if (subjectKeyID != null) - { - return (byte[])subjectKeyID.clone(); - } - - return null; - } - - /** - * Returns the authorityKeyIdentifier criterion. The - * X509Certificate must contain a AuthorityKeyIdentifier - * extension with the specified value. If null, no - * authorityKeyIdentifier check will be done.
- *
- * Note that the byte array returned is cloned to protect against subsequent - * modifications. - * - * @return the key identifier (or null) - * - * @see #setAuthorityKeyIdentifier - */ - public byte[] getAuthorityKeyIdentifier() - { - if (authorityKeyID != null) - { - return (byte[])authorityKeyID.clone(); - } - - return null; - } - - /** - * Returns the certificateValid criterion. The specified date must fall - * within the certificate validity period for the - * X509Certificate. If null, no - * certificateValid check will be done.
- *
- * Note that the Date returned is cloned to protect against - * subsequent modifications. - * - * @return the Date to check (or null) - * - * @see #setCertificateValid - */ - public Date getCertificateValid() - { - if (certValid != null) - { - return new Date(certValid.getTime()); - } - - return null; - } - - /** - * Returns the privateKeyValid criterion. The specified date must fall - * within the private key validity period for the - * X509Certificate. If null, no - * privateKeyValid check will be done.
- *
- * Note that the Date returned is cloned to protect against - * subsequent modifications. - * - * @return the Date to check (or null) - * - * @see #setPrivateKeyValid - */ - public Date getPrivateKeyValid() - { - if (privateKeyValid != null) - { - return new Date(privateKeyValid.getTime()); - } - - return null; - } - - /** - * Returns the subjectPublicKeyAlgID criterion. The - * X509Certificate must contain a subject public key with the - * specified algorithm. If null, no subjectPublicKeyAlgID - * check will be done. - * - * @return the object identifier (OID) of the signature algorithm to check - * for (or null). An OID is represented by a set of - * nonnegative integers separated by periods. - * - * @see #setSubjectPublicKeyAlgID - */ - public String getSubjectPublicKeyAlgID() - { - if (subjectKeyAlgID != null) - { - return subjectKeyAlgID.toString(); - } - - return null; - } - - /** - * Returns the subjectPublicKey criterion. The X509Certificate - * must contain the specified subject public key. If null, - * no subjectPublicKey check will be done. - * - * @return the subject public key to check for (or null) - * - * @see #setSubjectPublicKey - */ - public PublicKey getSubjectPublicKey() - { - return subjectPublicKey; - } - - /** - * Returns the keyUsage criterion. The X509Certificate must - * allow the specified keyUsage values. If null, no keyUsage check will be - * done.
- *
- * Note that the boolean array returned is cloned to protect against - * subsequent modifications. - * - * @return a boolean array in the same format as the boolean array returned - * by - * {@link X509Certificate#getKeyUsage() X509Certificate.getKeyUsage()}. - * Or null. - * - * @see #setKeyUsage - */ - public boolean[] getKeyUsage() - { - if (keyUsage != null) - { - return (boolean[])keyUsage.clone(); - } - - return null; - } - - /** - * Returns the extendedKeyUsage criterion. The X509Certificate - * must allow the specified key purposes in its extended key usage - * extension. If the keyPurposeSet returned is empty or - * null, no extendedKeyUsage check will be done. Note that - * an X509Certificate that has no extendedKeyUsage extension - * implicitly allows all key purposes. - * - * @return an immutable Set of key purpose OIDs in string - * format (or null) - * @see #setExtendedKeyUsage - */ - public Set getExtendedKeyUsage() - { - if (keyPurposeSet == null || keyPurposeSet.isEmpty()) - { - return keyPurposeSet; - } - - Set returnSet = new HashSet(); - Iterator iter = keyPurposeSet.iterator(); - while (iter.hasNext()) - { - returnSet.add(iter.next().toString()); - } - - return Collections.unmodifiableSet(returnSet); - } - - /** - * Indicates if the X509Certificate must contain all or at - * least one of the subjectAlternativeNames specified in the - * {@link #setSubjectAlternativeNames setSubjectAlternativeNames} or - * {@link #addSubjectAlternativeName addSubjectAlternativeName} methods. If - * true, the X509Certificate must contain all - * of the specified subject alternative names. If false, the - * X509Certificate must contain at least one of the specified - * subject alternative names. - * - * @return true if the flag is enabled; false - * if the flag is disabled. The flag is true by - * default. - * - * @see #setMatchAllSubjectAltNames - */ - public boolean getMatchAllSubjectAltNames() - { - return matchAllSubjectAltNames; - } - - /** - * Returns a copy of the subjectAlternativeNames criterion. The - * X509Certificate must contain all or at least one of the - * specified subjectAlternativeNames, depending on the value of the - * matchAllNames flag (see {@link #getMatchAllSubjectAltNames - * getMatchAllSubjectAltNames}). If the value returned is null, - * no subjectAlternativeNames check will be performed.
- *
- * If the value returned is not null, it is a - * Collection with one entry for each name to be included in - * the subject alternative name criterion. Each entry is a List - * whose first entry is an Integer (the name type, 0-8) and - * whose second entry is a String or a byte array (the name, - * in string or ASN.1 DER encoded form, respectively). There can be multiple - * names of the same type. Note that the Collection returned - * may contain duplicate names (same name and name type).
- *
- * Each subject alternative name in the Collection may be - * specified either as a String or as an ASN.1 encoded byte - * array. For more details about the formats used, see - * {@link #addSubjectAlternativeName(int type, String name) - * addSubjectAlternativeName(int type, String name)} and - * {@link #addSubjectAlternativeName(int type, byte [] name) - * addSubjectAlternativeName(int type, byte [] name)}.
- *
- * Note that a deep copy is performed on the Collection to - * protect against subsequent modifications. - * - * @return a Collection of names (or null) - * - * @see #setSubjectAlternativeNames - */ - public Collection getSubjectAlternativeNames() - { - if (subjectAltNames != null) - { - return null; - } - - Set returnAltNames = new HashSet(); - List returnList; - Iterator iter = subjectAltNames.iterator(); - List obj; - while (iter.hasNext()) - { - obj = (List)iter.next(); - returnList = new ArrayList(); - returnList.add(obj.get(0)); - if (obj.get(1) instanceof byte[]) - { - returnList.add(((byte[])obj.get(1)).clone()); - } - else - { - returnList.add(obj.get(1)); - } - returnAltNames.add(returnList); - } - - return returnAltNames; - } - - /** - * Returns the name constraints criterion. The X509Certificate - * must have subject and subject alternative names that meet the specified - * name constraints.
- *
- * The name constraints are returned as a byte array. This byte array - * contains the DER encoded form of the name constraints, as they would - * appear in the NameConstraints structure defined in RFC 2459 and X.509. - * The ASN.1 notation for this structure is supplied in the documentation - * for - * {@link #setNameConstraints(byte [] bytes) setNameConstraints(byte [] bytes)}.
- *
- * Note that the byte array returned is cloned to protect against subsequent - * modifications.
- *
- * TODO: implement this - * - * @return a byte array containing the ASN.1 DER encoding of a - * NameConstraints extension used for checking name constraints. - * null if no name constraints check will be - * performed. - * - * @exception UnsupportedOperationException - * because this method is not supported - * - * @see #setNameConstraints - */ - public byte[] getNameConstraints() - { - throw new UnsupportedOperationException(); - } - - /** - * Returns the basic constraints constraint. If the value is greater than or - * equal to zero, the X509Certificates must include a - * basicConstraints extension with a pathLen of at least this value. If the - * value is -2, only end-entity certificates are accepted. If the value is - * -1, no basicConstraints check is done. - * - * @return the value for the basic constraints constraint - * - * @see #setBasicConstraints - */ - public int getBasicConstraints() - { - return minMaxPathLen; - } - - /** - * Returns the policy criterion. The X509Certificate must - * include at least one of the specified policies in its certificate - * policies extension. If the Set returned is empty, then the - * X509Certificate must include at least some specified - * policy in its certificate policies extension. If the Set - * returned is null, no policy check will be performed. - * - * @return an immutable Set of certificate policy OIDs in - * string format (or null) - * - * @see #setPolicy - */ - public Set getPolicy() - { - if (policy == null) - { - return null; - } - - return Collections.unmodifiableSet(policy); - } - - /** - * Returns a copy of the pathToNames criterion. The - * X509Certificate must not include name constraints that - * would prohibit building a path to the specified names. If the value - * returned is null, no pathToNames check will be performed.
- *
- * If the value returned is not null, it is a - * Collection with one entry for each name to be included in - * the pathToNames criterion. Each entry is a List whose - * first entry is an Integer (the name type, 0-8) and whose - * second entry is a String or a byte array (the name, in - * string or ASN.1 DER encoded form, respectively). There can be multiple - * names of the same type. Note that the Collection returned - * may contain duplicate names (same name and name type).
- *
- * Each name in the Collection may be specified either as a - * String or as an ASN.1 encoded byte array. For more details - * about the formats used, see {@link #addPathToName(int type, String name) - * addPathToName(int type, String name)} and - * {@link #addPathToName(int type, byte [] name) addPathToName(int type, - * byte [] name)}.
- *
- * Note that a deep copy is performed on the Collection to - * protect against subsequent modifications. - * - * @return a Collection of names (or null) - * - * @see #setPathToNames - */ - public Collection getPathToNames() - { - if (pathToNames == null) - { - return null; - } - - Set returnPathToNames = new HashSet(); - List returnList; - Iterator iter = pathToNames.iterator(); - List obj; - - while (iter.hasNext()) - { - obj = (List)iter.next(); - returnList = new ArrayList(); - returnList.add(obj.get(0)); - if (obj.get(1) instanceof byte[]) - { - returnList.add(((byte[])obj.get(1)).clone()); - } - else - { - returnList.add(obj.get(1)); - } - returnPathToNames.add(returnList); - } - - return returnPathToNames; - } - - /** - * Return a printable representation of the CertSelector.
- *
- * TODO: implement output for currently unsupported options(name - * constraints)
- *
- * Uses {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Object ASN1Object}, - * {@link org.spongycastle.asn1.x509.KeyPurposeId KeyPurposeId} - * - * @return a String describing the contents of the - * CertSelector - */ - public String toString() - { - StringBuffer sb = new StringBuffer(); - sb.append("X509CertSelector: [\n"); - if (x509Cert != null) - { - sb.append(" Certificate: ").append(x509Cert).append('\n'); - } - if (serialNumber != null) - { - sb.append(" Serial Number: ").append(serialNumber).append('\n'); - } - if (issuerDN != null) - { - sb.append(" Issuer: ").append(getIssuerAsString()).append('\n'); - } - if (subjectDN != null) - { - sb.append(" Subject: ").append(getSubjectAsString()).append('\n'); - } - try - { - if (subjectKeyID != null) - { - ByteArrayInputStream inStream = new ByteArrayInputStream( - subjectKeyID); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); - sb.append(" Subject Key Identifier: ") - .append(ASN1Dump.dumpAsString(derObject)).append('\n'); - } - if (authorityKeyID != null) - { - ByteArrayInputStream inStream = new ByteArrayInputStream( - authorityKeyID); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); - sb.append(" Authority Key Identifier: ") - .append(ASN1Dump.dumpAsString(derObject)).append('\n'); - } - } - catch (IOException ex) - { - sb.append(ex.getMessage()).append('\n'); - } - if (certValid != null) - { - sb.append(" Certificate Valid: ").append(certValid).append('\n'); - } - if (privateKeyValid != null) - { - sb.append(" Private Key Valid: ").append(privateKeyValid) - .append('\n'); - } - if (subjectKeyAlgID != null) - { - sb.append(" Subject Public Key AlgID: ") - .append(subjectKeyAlgID).append('\n'); - } - if (subjectPublicKey != null) - { - sb.append(" Subject Public Key: ").append(subjectPublicKey) - .append('\n'); - } - if (keyUsage != null) - { - sb.append(" Key Usage: ").append(keyUsage).append('\n'); - } - if (keyPurposeSet != null) - { - sb.append(" Extended Key Usage: ").append(keyPurposeSet) - .append('\n'); - } - if (policy != null) - { - sb.append(" Policy: ").append(policy).append('\n'); - } - sb.append(" matchAllSubjectAltNames flag: ") - .append(matchAllSubjectAltNames).append('\n'); - if (subjectAltNamesByte != null) - { - sb.append(" SubjectAlternativNames: \n["); - Iterator iter = subjectAltNamesByte.iterator(); - List obj; - try - { - while (iter.hasNext()) - { - obj = (List)iter.next(); - ByteArrayInputStream inStream = new ByteArrayInputStream( - (byte[])obj.get(1)); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); - sb.append(" Type: ").append(obj.get(0)).append(" Data: ") - .append(ASN1Dump.dumpAsString(derObject)).append('\n'); - } - } - catch (IOException ex) - { - sb.append(ex.getMessage()).append('\n'); - } - sb.append("]\n"); - } - if (pathToNamesByte != null) - { - sb.append(" PathToNamesNames: \n["); - Iterator iter = pathToNamesByte.iterator(); - List obj; - try - { - while (iter.hasNext()) - { - obj = (List)iter.next(); - ByteArrayInputStream inStream = new ByteArrayInputStream( - (byte[])obj.get(1)); - ASN1InputStream derInStream = new ASN1InputStream(inStream); - ASN1Object derObject = derInStream.readObject(); - sb.append(" Type: ").append(obj.get(0)).append(" Data: ") - .append(ASN1Dump.dumpAsString(derObject)).append('\n'); - } - } - catch (IOException ex) - { - sb.append(ex.getMessage()).append('\n'); - } - sb.append("]\n"); - } - sb.append(']'); - return sb.toString(); - } - - /** - * Decides whether a Certificate should be selected.
- *
- * TODO: implement missing tests (name constraints and path to names)
- *
- * Uses {@link org.spongycastle.asn1.ASN1InputStream ASN1InputStream}, - * {@link org.spongycastle.asn1.ASN1Sequence ASN1Sequence}, - * {@link org.spongycastle.asn1.ASN1ObjectIdentifier ASN1ObjectIdentifier}, - * {@link org.spongycastle.asn1.ASN1Object ASN1Object}, - * {@link org.spongycastle.asn1.DERGeneralizedTime DERGeneralizedTime}, - * {@link org.spongycastle.asn1.x509.X509Name X509Name}, - * {@link org.spongycastle.asn1.x509.X509Extensions X509Extensions}, - * {@link org.spongycastle.asn1.x509.ExtendedKeyUsage ExtendedKeyUsage}, - * {@link org.spongycastle.asn1.x509.KeyPurposeId KeyPurposeId}, - * {@link org.spongycastle.asn1.x509.SubjectPublicKeyInfo SubjectPublicKeyInfo}, - * {@link org.spongycastle.asn1.x509.AlgorithmIdentifier AlgorithmIdentifier} - * to access X509 extensions - * - * @param cert - * the Certificate to be checked - * - * @return true if the Certificate should be - * selected, false otherwise - */ - public boolean match(Certificate cert) - { - boolean[] booleanArray; - List tempList; - Iterator tempIter; - - if (!(cert instanceof X509Certificate)) - { - return false; - } - X509Certificate certX509 = (X509Certificate)cert; - - if (x509Cert != null && !x509Cert.equals(certX509)) - { - return false; - } - if (serialNumber != null - && !serialNumber.equals(certX509.getSerialNumber())) - { - return false; - } - try - { - if (issuerDNX509 != null) - { - if (!issuerDNX509.equals(PrincipalUtil - .getIssuerX509Principal(certX509), true)) - { - return false; - } - } - if (subjectDNX509 != null) - { - if (!subjectDNX509.equals(PrincipalUtil - .getSubjectX509Principal(certX509), true)) - { - return false; - } - } - } - catch (Exception ex) - { - return false; - } - if (subjectKeyID != null) - { - byte[] data = certX509 - .getExtensionValue(X509Extensions.SubjectKeyIdentifier - .getId()); - if (data == null) - { - return false; - } - try - { - ByteArrayInputStream inStream = new ByteArrayInputStream(data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - byte[] testData = ((ASN1OctetString)derInputStream.readObject()) - .getOctets(); - if (!Arrays.equals(subjectKeyID, testData)) - { - return false; - } - } - catch (IOException ex) - { - return false; - } - } - if (authorityKeyID != null) - { - byte[] data = certX509 - .getExtensionValue(X509Extensions.AuthorityKeyIdentifier - .getId()); - if (data == null) - { - return false; - } - try - { - ByteArrayInputStream inStream = new ByteArrayInputStream(data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - byte[] testData = ((ASN1OctetString)derInputStream.readObject()) - .getOctets(); - if (!Arrays.equals(authorityKeyID, testData)) - { - return false; - } - } - catch (IOException ex) - { - return false; - } - } - if (certValid != null) - { - if (certX509.getNotAfter() != null - && certValid.after(certX509.getNotAfter())) - { - return false; - } - if (certX509.getNotBefore() != null - && certValid.before(certX509.getNotBefore())) - { - return false; - } - } - if (privateKeyValid != null) - { - try - { - byte[] data = certX509 - .getExtensionValue(X509Extensions.PrivateKeyUsagePeriod - .getId()); - if (data != null) - { - ByteArrayInputStream inStream = new ByteArrayInputStream( - data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - inStream = new ByteArrayInputStream( - ((ASN1OctetString)derInputStream.readObject()) - .getOctets()); - derInputStream = new ASN1InputStream(inStream); - // TODO fix this, Sequence contains tagged objects - ASN1Sequence derObject = (ASN1Sequence)derInputStream - .readObject(); - ASN1GeneralizedTime derDate = ASN1GeneralizedTime - .getInstance(derObject.getObjectAt(0)); - SimpleDateFormat dateF = new SimpleDateFormat( - "yyyyMMddHHmmssZ"); - if (privateKeyValid.before(dateF.parse(derDate.getTime()))) - { - return false; - } - derDate = ASN1GeneralizedTime.getInstance(derObject - .getObjectAt(1)); - if (privateKeyValid.after(dateF.parse(derDate.getTime()))) - { - return false; - } - } - } - catch (Exception ex) - { - return false; - } - } - if (subjectKeyAlgID != null) - { - try - { - ByteArrayInputStream inStream = new ByteArrayInputStream( - certX509.getPublicKey().getEncoded()); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo( - (ASN1Sequence)derInputStream.readObject()); - AlgorithmIdentifier algInfo = publicKeyInfo.getAlgorithmId(); - if (!algInfo.getObjectId().equals(subjectKeyAlgID)) - { - return false; - } - } - catch (Exception ex) - { - return false; - } - } - if (subjectPublicKeyByte != null) - { - if (!Arrays.equals(subjectPublicKeyByte, certX509.getPublicKey() - .getEncoded())) - { - return false; - } - } - if (subjectPublicKey != null) - { - if (!subjectPublicKey.equals(certX509.getPublicKey())) - { - return false; - } - } - if (keyUsage != null) - { - booleanArray = certX509.getKeyUsage(); - if (booleanArray != null) - { - for (int i = 0; i < keyUsage.length; i++) - { - if (keyUsage[i] - && (booleanArray.length <= i || !booleanArray[i])) - { - return false; - } - } - } - } - if (keyPurposeSet != null && !keyPurposeSet.isEmpty()) - { - try - { - byte[] data = certX509 - .getExtensionValue(X509Extensions.ExtendedKeyUsage - .getId()); - if (data != null) - { - ByteArrayInputStream inStream = new ByteArrayInputStream( - data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.getInstance( - derInputStream.readObject()); - tempIter = keyPurposeSet.iterator(); - while (tempIter.hasNext()) - { - if (!extendedKeyUsage - .hasKeyPurposeId((KeyPurposeId)tempIter.next())) - { - return false; - } - } - } - } - catch (Exception ex) - { - return false; - } - } - if (minMaxPathLen != -1) - { - if (minMaxPathLen == -2 && certX509.getBasicConstraints() != -1) - { - return false; - } - if (minMaxPathLen >= 0 - && certX509.getBasicConstraints() < minMaxPathLen) - { - return false; - } - } - if (policyOID != null) - { - try - { - byte[] data = certX509 - .getExtensionValue(X509Extensions.CertificatePolicies - .getId()); - if (data == null) - { - return false; - } - if (!policyOID.isEmpty()) - { - ByteArrayInputStream inStream = new ByteArrayInputStream( - data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - inStream = new ByteArrayInputStream( - ((ASN1OctetString)derInputStream.readObject()) - .getOctets()); - derInputStream = new ASN1InputStream(inStream); - Enumeration policySequence = ((ASN1Sequence)derInputStream - .readObject()).getObjects(); - ASN1Sequence policyObject; - boolean test = false; - while (policySequence.hasMoreElements() && !test) - { - policyObject = (ASN1Sequence)policySequence - .nextElement(); - if (policyOID.contains(policyObject.getObjectAt(0))) - { - test = true; - } - } - if (!test) - { - return false; - } - } - } - catch (Exception ex) - { - ex.printStackTrace(); - return false; - } - } - if (subjectAltNamesByte != null) - { - try - { - byte[] data = certX509 - .getExtensionValue(X509Extensions.SubjectAlternativeName - .getId()); - if (data == null) - { - return false; - } - ByteArrayInputStream inStream = new ByteArrayInputStream(data); - ASN1InputStream derInputStream = new ASN1InputStream(inStream); - inStream = new ByteArrayInputStream( - ((ASN1OctetString)derInputStream.readObject()) - .getOctets()); - derInputStream = new ASN1InputStream(inStream); - Enumeration altNamesSequence = ((ASN1Sequence)derInputStream - .readObject()).getObjects(); - ASN1TaggedObject altNameObject; - boolean test = false; - Set testSet = new HashSet(subjectAltNamesByte); - List testList; - ASN1Object derData; - ByteArrayOutputStream outStream; - DEROutputStream derOutStream; - while (altNamesSequence.hasMoreElements() && !test) - { - altNameObject = (ASN1TaggedObject)altNamesSequence - .nextElement(); - testList = new ArrayList(2); - testList.add(Integers.valueOf(altNameObject.getTagNo())); - derData = altNameObject.getObject(); - outStream = new ByteArrayOutputStream(); - derOutStream = new DEROutputStream(outStream); - derOutStream.writeObject(derData); - derOutStream.close(); - testList.add(outStream.toByteArray()); - - if (testSet.remove(testList)) - { - test = true; - } - - if (matchAllSubjectAltNames && !testSet.isEmpty()) - { - test = false; - } - } - if (!test) - { - return false; - } - } - catch (Exception ex) - { - ex.printStackTrace(); - return false; - } - } - - return true; - } - - /** - * Returns a copy of this object. - * - * @return the copy - */ - public Object clone() - { - try - { - X509CertSelector copy = (X509CertSelector)super.clone(); - if (issuerDN instanceof byte[]) - { - copy.issuerDN = ((byte[])issuerDN).clone(); - } - if (subjectDN instanceof byte[]) - { - copy.subjectDN = ((byte[])subjectDN).clone(); - } - if (subjectKeyID != null) - { - copy.subjectKeyID = (byte[])subjectKeyID.clone(); - } - if (authorityKeyID != null) - { - copy.authorityKeyID = (byte[])authorityKeyID.clone(); - } - if (subjectPublicKeyByte != null) - { - copy.subjectPublicKeyByte = (byte[])subjectPublicKeyByte - .clone(); - } - if (keyUsage != null) - { - copy.keyUsage = (boolean[])keyUsage.clone(); - } - if (keyPurposeSet != null) - { - copy.keyPurposeSet = new HashSet(keyPurposeSet); - } - if (policy != null) - { - copy.policy = new HashSet(policy); - copy.policyOID = new HashSet(); - Iterator iter = policyOID.iterator(); - while (iter.hasNext()) - { - copy.policyOID.add(new ASN1ObjectIdentifier( - ((ASN1ObjectIdentifier)iter.next()).getId())); - } - } - if (subjectAltNames != null) - { - copy.subjectAltNames = new HashSet(getSubjectAlternativeNames()); - Iterator iter = subjectAltNamesByte.iterator(); - List obj; - List cloneObj; - while (iter.hasNext()) - { - obj = (List)iter.next(); - cloneObj = new ArrayList(); - cloneObj.add(obj.get(0)); - cloneObj.add(((byte[])obj.get(1)).clone()); - copy.subjectAltNamesByte.add(cloneObj); - } - } - if (pathToNames != null) - { - copy.pathToNames = new HashSet(getPathToNames()); - Iterator iter = pathToNamesByte.iterator(); - List obj; - List cloneObj; - while (iter.hasNext()) - { - obj = (List)iter.next(); - cloneObj = new ArrayList(); - cloneObj.add(obj.get(0)); - cloneObj.add(((byte[])obj.get(1)).clone()); - copy.pathToNamesByte.add(cloneObj); - } - } - return copy; - } - catch (CloneNotSupportedException e) - { - /* Cannot happen */ - throw new InternalError(e.toString()); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/X509Extension.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/X509Extension.java deleted file mode 100644 index f2c7e1990..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/X509Extension.java +++ /dev/null @@ -1,12 +0,0 @@ - -package org.spongycastle.jce.cert; - -import java.util.Set; - -public interface X509Extension -{ - public abstract Set getCriticalExtensionOIDs(); - public abstract byte[] getExtensionValue(String oid); - public abstract Set getNonCriticalExtensionOIDs(); - public abstract boolean hasUnsupportedCriticalExtension(); -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/package.html b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/package.html deleted file mode 100644 index c5cd3f6ad..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/cert/package.html +++ /dev/null @@ -1,5 +0,0 @@ - - -Compatibility API for the JDK 1.4 CertPath API. - - diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/exception/ExtCertPathBuilderException.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/exception/ExtCertPathBuilderException.java deleted file mode 100644 index b238580f7..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/exception/ExtCertPathBuilderException.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.spongycastle.jce.exception; - -import org.spongycastle.jce.cert.CertPath; -import org.spongycastle.jce.cert.CertPathBuilderException; - -public class ExtCertPathBuilderException - extends CertPathBuilderException - implements ExtException -{ - private Throwable cause; - - public ExtCertPathBuilderException(String message, Throwable cause) - { - super(message); - this.cause = cause; - } - - public ExtCertPathBuilderException(String msg, Throwable cause, - CertPath certPath, int index) - { - super(msg, cause); - this.cause = cause; - } - - public Throwable getCause() - { - return cause; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/exception/ExtCertPathValidatorException.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/exception/ExtCertPathValidatorException.java deleted file mode 100644 index ec2b667d2..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/exception/ExtCertPathValidatorException.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.spongycastle.jce.exception; - -import org.spongycastle.jce.cert.CertPath; -import org.spongycastle.jce.cert.CertPathValidatorException; - -public class ExtCertPathValidatorException - extends CertPathValidatorException - implements ExtException -{ - - private Throwable cause; - - public ExtCertPathValidatorException(String message, Throwable cause) - { - super(message); - this.cause = cause; - } - - public ExtCertPathValidatorException(String msg, Throwable cause, - CertPath certPath, int index) - { - super(msg, cause, certPath, index); - this.cause = cause; - } - - public Throwable getCause() - { - return cause; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/CertPathValidatorUtilities.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/CertPathValidatorUtilities.java deleted file mode 100644 index 40bf81dab..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/CertPathValidatorUtilities.java +++ /dev/null @@ -1,1417 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.KeyFactory; -import java.security.PublicKey; -import java.security.cert.CRLException; -import org.spongycastle.jce.cert.CertPath; -import org.spongycastle.jce.cert.CertPathValidatorException; -import org.spongycastle.jce.cert.CertStore; -import org.spongycastle.jce.cert.CertStoreException; -import java.security.cert.Certificate; -import java.security.cert.CertificateParsingException; -import org.spongycastle.jce.cert.PKIXParameters; -import org.spongycastle.jce.cert.PolicyQualifierInfo; -import org.spongycastle.jce.cert.TrustAnchor; -import java.security.cert.X509CRL; -import java.security.cert.X509CRLEntry; -import org.spongycastle.jce.cert.X509CRLSelector; -import org.spongycastle.jce.cert.X509CertSelector; -import java.security.cert.X509Certificate; -import java.security.interfaces.DSAParams; -import java.security.interfaces.DSAPublicKey; -import java.security.spec.DSAPublicKeySpec; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.ASN1OutputStream; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1Enumerated; -import org.spongycastle.asn1.ASN1GeneralizedTime; -import org.spongycastle.asn1.DERIA5String; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.isismtt.ISISMTTObjectIdentifiers; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.CRLDistPoint; -import org.spongycastle.asn1.x509.CRLReason; -import org.spongycastle.asn1.x509.CertificateList; -import org.spongycastle.asn1.x509.DistributionPoint; -import org.spongycastle.asn1.x509.DistributionPointName; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.GeneralNames; -import org.spongycastle.asn1.x509.PolicyInformation; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x509.X509Extension; -import org.spongycastle.asn1.x509.X509Extensions; -import org.spongycastle.jce.exception.ExtCertPathValidatorException; -import org.spongycastle.jce.X509Principal; -import org.spongycastle.jce.PrincipalUtil; -import org.spongycastle.util.Selector; -import org.spongycastle.util.StoreException; -import org.spongycastle.x509.ExtendedPKIXBuilderParameters; -import org.spongycastle.x509.ExtendedPKIXParameters; -import org.spongycastle.x509.X509AttributeCertStoreSelector; -import org.spongycastle.x509.X509AttributeCertificate; -import org.spongycastle.x509.X509CRLStoreSelector; -import org.spongycastle.x509.X509CertStoreSelector; -import org.spongycastle.x509.X509Store; - -public class CertPathValidatorUtilities -{ - protected static final PKIXCRLUtil CRL_UTIL = new PKIXCRLUtil(); - - protected static final String CERTIFICATE_POLICIES = X509Extensions.CertificatePolicies.getId(); - protected static final String BASIC_CONSTRAINTS = X509Extensions.BasicConstraints.getId(); - protected static final String POLICY_MAPPINGS = X509Extensions.PolicyMappings.getId(); - protected static final String SUBJECT_ALTERNATIVE_NAME = X509Extensions.SubjectAlternativeName.getId(); - protected static final String NAME_CONSTRAINTS = X509Extensions.NameConstraints.getId(); - protected static final String KEY_USAGE = X509Extensions.KeyUsage.getId(); - protected static final String INHIBIT_ANY_POLICY = X509Extensions.InhibitAnyPolicy.getId(); - protected static final String ISSUING_DISTRIBUTION_POINT = X509Extensions.IssuingDistributionPoint.getId(); - protected static final String DELTA_CRL_INDICATOR = X509Extensions.DeltaCRLIndicator.getId(); - protected static final String POLICY_CONSTRAINTS = X509Extensions.PolicyConstraints.getId(); - protected static final String FRESHEST_CRL = X509Extensions.FreshestCRL.getId(); - protected static final String CRL_DISTRIBUTION_POINTS = X509Extensions.CRLDistributionPoints.getId(); - protected static final String AUTHORITY_KEY_IDENTIFIER = X509Extensions.AuthorityKeyIdentifier.getId(); - - protected static final String ANY_POLICY = "2.5.29.32.0"; - - protected static final String CRL_NUMBER = X509Extensions.CRLNumber.getId(); - - /* - * key usage bits - */ - protected static final int KEY_CERT_SIGN = 5; - protected static final int CRL_SIGN = 6; - - protected static final String[] crlReasons = new String[]{ - "unspecified", - "keyCompromise", - "cACompromise", - "affiliationChanged", - "superseded", - "cessationOfOperation", - "certificateHold", - "unknown", - "removeFromCRL", - "privilegeWithdrawn", - "aACompromise"}; - - /** - * Search the given Set of TrustAnchor's for one that is the - * issuer of the given X509 certificate. Uses the default provider - * for signature verification. - * - * @param cert the X509 certificate - * @param trustAnchors a Set of TrustAnchor's - * @return the TrustAnchor object if found or - * null if not. - * @throws AnnotatedException if a TrustAnchor was found but the signature verification - * on the given certificate has thrown an exception. - */ - protected static TrustAnchor findTrustAnchor( - X509Certificate cert, - Set trustAnchors) - throws AnnotatedException - { - return findTrustAnchor(cert, trustAnchors, null); - } - - /** - * Search the given Set of TrustAnchor's for one that is the - * issuer of the given X509 certificate. Uses the specified - * provider for signature verification, or the default provider - * if null. - * - * @param cert the X509 certificate - * @param trustAnchors a Set of TrustAnchor's - * @param sigProvider the provider to use for signature verification - * @return the TrustAnchor object if found or - * null if not. - * @throws AnnotatedException if a TrustAnchor was found but the signature verification - * on the given certificate has thrown an exception. - */ - protected static TrustAnchor findTrustAnchor( - X509Certificate cert, - Set trustAnchors, - String sigProvider) - throws AnnotatedException - { - TrustAnchor trust = null; - PublicKey trustPublicKey = null; - Exception invalidKeyEx = null; - - X509CertSelector certSelectX509 = new X509CertSelector(); - X509Principal certIssuer = getEncodedIssuerPrincipal(cert); - - try - { - certSelectX509.setSubject(certIssuer.getEncoded()); - } - catch (IOException ex) - { - throw new AnnotatedException("Cannot set subject search criteria for trust anchor.", ex); - } - - Iterator iter = trustAnchors.iterator(); - while (iter.hasNext() && trust == null) - { - trust = (TrustAnchor)iter.next(); - if (trust.getTrustedCert() != null) - { - if (certSelectX509.match(trust.getTrustedCert())) - { - trustPublicKey = trust.getTrustedCert().getPublicKey(); - } - else - { - trust = null; - } - } - else if (trust.getCAName() != null - && trust.getCAPublicKey() != null) - { - try - { - X509Principal caName = new X509Principal(trust.getCAName()); - if (certIssuer.equals(caName)) - { - trustPublicKey = trust.getCAPublicKey(); - } - else - { - trust = null; - } - } - catch (IllegalArgumentException ex) - { - trust = null; - } - } - else - { - trust = null; - } - - if (trustPublicKey != null) - { - try - { - verifyX509Certificate(cert, trustPublicKey, sigProvider); - } - catch (Exception ex) - { - invalidKeyEx = ex; - trust = null; - trustPublicKey = null; - } - } - } - - if (trust == null && invalidKeyEx != null) - { - throw new AnnotatedException("TrustAnchor found but certificate validation failed.", invalidKeyEx); - } - - return trust; - } - - protected static void addAdditionalStoresFromAltNames( - X509Certificate cert, - ExtendedPKIXParameters pkixParams) - throws CertificateParsingException - { - // if in the IssuerAltName extension an URI - // is given, add an additinal X.509 store -/* - if (cert.getIssuerAlternativeNames() != null) - { - Iterator it = cert.getIssuerAlternativeNames().iterator(); - while (it.hasNext()) - { - // look for URI - List list = (List)it.next(); - if (list.get(0).equals(new Integer(GeneralName.uniformResourceIdentifier))) - { - // found - String temp = (String)list.get(1); - CertPathValidatorUtilities.addAdditionalStoreFromLocation(temp, pkixParams); - } - } - } -*/ - } - - /** - * Returns the issuer of an attribute certificate or certificate. - * - * @param cert The attribute certificate or certificate. - * @return The issuer as X509Principal. - */ - protected static X509Principal getEncodedIssuerPrincipal( - Object cert) - { - if (cert instanceof X509Certificate) - { -try -{ - return PrincipalUtil.getIssuerX509Principal((X509Certificate)cert); -} -catch (Exception e) -{ -throw new IllegalStateException(e.toString()); -} - } - else - { - return (X509Principal)((X509AttributeCertificate)cert).getIssuer().getPrincipals()[0]; - } - } - - protected static Date getValidDate(PKIXParameters paramsPKIX) - { - Date validDate = paramsPKIX.getDate(); - - if (validDate == null) - { - validDate = new Date(); - } - - return validDate; - } - - protected static X509Principal getSubjectPrincipal(X509Certificate cert) - { -try -{ - return PrincipalUtil.getSubjectX509Principal(cert); -} -catch (Exception e) -{ -throw new IllegalStateException(e.toString()); -} - } - - protected static boolean isSelfIssued(X509Certificate cert) - { - return cert.getSubjectDN().equals(cert.getIssuerDN()); - } - - - /** - * Extract the value of the given extension, if it exists. - * - * @param ext The extension object. - * @param oid The object identifier to obtain. - * @throws AnnotatedException if the extension cannot be read. - */ - protected static ASN1Primitive getExtensionValue( - java.security.cert.X509Extension ext, - String oid) - throws AnnotatedException - { - byte[] bytes = ext.getExtensionValue(oid); - if (bytes == null) - { - return null; - } - - return getObject(oid, bytes); - } - - private static ASN1Primitive getObject( - String oid, - byte[] ext) - throws AnnotatedException - { - try - { - ASN1InputStream aIn = new ASN1InputStream(ext); - ASN1OctetString octs = (ASN1OctetString)aIn.readObject(); - - aIn = new ASN1InputStream(octs.getOctets()); - return aIn.readObject(); - } - catch (Exception e) - { - throw new AnnotatedException("exception processing extension " + oid, e); - } - } - - protected static X509Principal getIssuerPrincipal(X509CRL crl) - { -try -{ - return PrincipalUtil.getIssuerX509Principal(crl); -} -catch (Exception e) -{ - throw new IllegalStateException(e.toString()); -} - } - - protected static AlgorithmIdentifier getAlgorithmIdentifier( - PublicKey key) - throws CertPathValidatorException - { - try - { - ASN1InputStream aIn = new ASN1InputStream(key.getEncoded()); - - SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); - - return info.getAlgorithmId(); - } - catch (Exception e) - { - throw new ExtCertPathValidatorException("Subject public key cannot be decoded.", e); - } - } - - // crl checking - - - // - // policy checking - // - - protected static final Set getQualifierSet(ASN1Sequence qualifiers) - throws CertPathValidatorException - { - Set pq = new HashSet(); - - if (qualifiers == null) - { - return pq; - } - - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ASN1OutputStream aOut = new ASN1OutputStream(bOut); - - Enumeration e = qualifiers.getObjects(); - - while (e.hasMoreElements()) - { - try - { - aOut.writeObject((ASN1Encodable)e.nextElement()); - - pq.add(new PolicyQualifierInfo(bOut.toByteArray())); - } - catch (IOException ex) - { - throw new ExtCertPathValidatorException("Policy qualifier info cannot be decoded.", ex); - } - - bOut.reset(); - } - - return pq; - } - - protected static PKIXPolicyNode removePolicyNode( - PKIXPolicyNode validPolicyTree, - List[] policyNodes, - PKIXPolicyNode _node) - { - PKIXPolicyNode _parent = (PKIXPolicyNode)_node.getParent(); - - if (validPolicyTree == null) - { - return null; - } - - if (_parent == null) - { - for (int j = 0; j < policyNodes.length; j++) - { - policyNodes[j] = new ArrayList(); - } - - return null; - } - else - { - _parent.removeChild(_node); - removePolicyNodeRecurse(policyNodes, _node); - - return validPolicyTree; - } - } - - private static void removePolicyNodeRecurse( - List[] policyNodes, - PKIXPolicyNode _node) - { - policyNodes[_node.getDepth()].remove(_node); - - if (_node.hasChildren()) - { - Iterator _iter = _node.getChildren(); - while (_iter.hasNext()) - { - PKIXPolicyNode _child = (PKIXPolicyNode)_iter.next(); - removePolicyNodeRecurse(policyNodes, _child); - } - } - } - - - protected static boolean processCertD1i( - int index, - List[] policyNodes, - ASN1ObjectIdentifier pOid, - Set pq) - { - List policyNodeVec = policyNodes[index - 1]; - - for (int j = 0; j < policyNodeVec.size(); j++) - { - PKIXPolicyNode node = (PKIXPolicyNode)policyNodeVec.get(j); - Set expectedPolicies = node.getExpectedPolicies(); - - if (expectedPolicies.contains(pOid.getId())) - { - Set childExpectedPolicies = new HashSet(); - childExpectedPolicies.add(pOid.getId()); - - PKIXPolicyNode child = new PKIXPolicyNode(new ArrayList(), - index, - childExpectedPolicies, - node, - pq, - pOid.getId(), - false); - node.addChild(child); - policyNodes[index].add(child); - - return true; - } - } - - return false; - } - - protected static void processCertD1ii( - int index, - List[] policyNodes, - ASN1ObjectIdentifier _poid, - Set _pq) - { - List policyNodeVec = policyNodes[index - 1]; - - for (int j = 0; j < policyNodeVec.size(); j++) - { - PKIXPolicyNode _node = (PKIXPolicyNode)policyNodeVec.get(j); - - if (ANY_POLICY.equals(_node.getValidPolicy())) - { - Set _childExpectedPolicies = new HashSet(); - _childExpectedPolicies.add(_poid.getId()); - - PKIXPolicyNode _child = new PKIXPolicyNode(new ArrayList(), - index, - _childExpectedPolicies, - _node, - _pq, - _poid.getId(), - false); - _node.addChild(_child); - policyNodes[index].add(_child); - return; - } - } - } - - protected static void prepareNextCertB1( - int i, - List[] policyNodes, - String id_p, - Map m_idp, - X509Certificate cert - ) - throws AnnotatedException, CertPathValidatorException - { - boolean idp_found = false; - Iterator nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (node.getValidPolicy().equals(id_p)) - { - idp_found = true; - node.expectedPolicies = (Set)m_idp.get(id_p); - break; - } - } - - if (!idp_found) - { - nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (ANY_POLICY.equals(node.getValidPolicy())) - { - Set pq = null; - ASN1Sequence policies = null; - try - { - policies = DERSequence.getInstance(getExtensionValue(cert, CERTIFICATE_POLICIES)); - } - catch (Exception e) - { - throw new AnnotatedException("Certificate policies cannot be decoded.", e); - } - Enumeration e = policies.getObjects(); - while (e.hasMoreElements()) - { - PolicyInformation pinfo = null; - - try - { - pinfo = PolicyInformation.getInstance(e.nextElement()); - } - catch (Exception ex) - { - throw new AnnotatedException("Policy information cannot be decoded.", ex); - } - if (ANY_POLICY.equals(pinfo.getPolicyIdentifier().getId())) - { - try - { - pq = getQualifierSet(pinfo.getPolicyQualifiers()); - } - catch (CertPathValidatorException ex) - { - throw new ExtCertPathValidatorException( - "Policy qualifier info set could not be built.", ex); - } - break; - } - } - boolean ci = false; - if (cert.getCriticalExtensionOIDs() != null) - { - ci = cert.getCriticalExtensionOIDs().contains(CERTIFICATE_POLICIES); - } - - PKIXPolicyNode p_node = (PKIXPolicyNode)node.getParent(); - if (ANY_POLICY.equals(p_node.getValidPolicy())) - { - PKIXPolicyNode c_node = new PKIXPolicyNode( - new ArrayList(), i, - (Set)m_idp.get(id_p), - p_node, pq, id_p, ci); - p_node.addChild(c_node); - policyNodes[i].add(c_node); - } - break; - } - } - } - } - - protected static PKIXPolicyNode prepareNextCertB2( - int i, - List[] policyNodes, - String id_p, - PKIXPolicyNode validPolicyTree) - { - Iterator nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (node.getValidPolicy().equals(id_p)) - { - PKIXPolicyNode p_node = (PKIXPolicyNode)node.getParent(); - p_node.removeChild(node); - nodes_i.remove(); - for (int k = (i - 1); k >= 0; k--) - { - List nodes = policyNodes[k]; - for (int l = 0; l < nodes.size(); l++) - { - PKIXPolicyNode node2 = (PKIXPolicyNode)nodes.get(l); - if (!node2.hasChildren()) - { - validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, node2); - if (validPolicyTree == null) - { - break; - } - } - } - } - } - } - return validPolicyTree; - } - - protected static boolean isAnyPolicy( - Set policySet) - { - return policySet == null || policySet.contains(ANY_POLICY) || policySet.isEmpty(); - } - - protected static void addAdditionalStoreFromLocation(String location, - ExtendedPKIXParameters pkixParams) - { - } - - /** - * Return a Collection of all certificates or attribute certificates found - * in the X509Store's that are matching the certSelect criteriums. - * - * @param certSelect a {@link Selector} object that will be used to select - * the certificates - * @param certStores a List containing only {@link X509Store} objects. These - * are used to search for certificates. - * @return a Collection of all found {@link X509Certificate} or - * {@link org.spongycastle.x509.X509AttributeCertificate} objects. - * May be empty but never null. - */ - protected static Collection findCertificates(X509CertStoreSelector certSelect, - List certStores) - throws AnnotatedException - { - Set certs = new HashSet(); - Iterator iter = certStores.iterator(); - - while (iter.hasNext()) - { - Object obj = iter.next(); - - if (obj instanceof X509Store) - { - X509Store certStore = (X509Store)obj; - try - { - certs.addAll(certStore.getMatches(certSelect)); - } - catch (StoreException e) - { - throw new AnnotatedException( - "Problem while picking certificates from X.509 store.", e); - } - } - else - { - CertStore certStore = (CertStore)obj; - - try - { - certs.addAll(certStore.getCertificates(certSelect)); - } - catch (CertStoreException e) - { - throw new AnnotatedException( - "Problem while picking certificates from certificate store.", - e); - } - } - } - return certs; - } - - protected static Collection findCertificates(X509AttributeCertStoreSelector certSelect, - List certStores) - throws AnnotatedException - { - Set certs = new HashSet(); - Iterator iter = certStores.iterator(); - - while (iter.hasNext()) - { - Object obj = iter.next(); - - if (obj instanceof X509Store) - { - X509Store certStore = (X509Store)obj; - try - { - certs.addAll(certStore.getMatches(certSelect)); - } - catch (StoreException e) - { - throw new AnnotatedException( - "Problem while picking certificates from X.509 store.", e); - } - } - } - return certs; - } - - protected static void addAdditionalStoresFromCRLDistributionPoint( - CRLDistPoint crldp, ExtendedPKIXParameters pkixParams) - throws AnnotatedException - { - if (crldp != null) - { - DistributionPoint dps[] = null; - try - { - dps = crldp.getDistributionPoints(); - } - catch (Exception e) - { - throw new AnnotatedException( - "Distribution points could not be read.", e); - } - for (int i = 0; i < dps.length; i++) - { - DistributionPointName dpn = dps[i].getDistributionPoint(); - // look for URIs in fullName - if (dpn != null) - { - if (dpn.getType() == DistributionPointName.FULL_NAME) - { - GeneralName[] genNames = GeneralNames.getInstance( - dpn.getName()).getNames(); - // look for an URI - for (int j = 0; j < genNames.length; j++) - { - if (genNames[j].getTagNo() == GeneralName.uniformResourceIdentifier) - { - String location = DERIA5String.getInstance( - genNames[j].getName()).getString(); - CertPathValidatorUtilities - .addAdditionalStoreFromLocation(location, - pkixParams); - } - } - } - } - } - } - } - - /** - * Add the CRL issuers from the cRLIssuer field of the distribution point or - * from the certificate if not given to the issuer criterion of the - * selector. - *

- * The issuerPrincipals are a collection with a single - * X509Principal for X509Certificates. For - * {@link X509AttributeCertificate}s the issuer may contain more than one - * X509Principal. - * - * @param dp The distribution point. - * @param issuerPrincipals The issuers of the certificate or attribute - * certificate which contains the distribution point. - * @param selector The CRL selector. - * @param pkixParams The PKIX parameters containing the cert stores. - * @throws AnnotatedException if an exception occurs while processing. - * @throws ClassCastException if issuerPrincipals does not - * contain only X509Principals. - */ - protected static void getCRLIssuersFromDistributionPoint( - DistributionPoint dp, - Collection issuerPrincipals, - X509CRLSelector selector, - ExtendedPKIXParameters pkixParams) - throws AnnotatedException - { - List issuers = new ArrayList(); - // indirect CRL - if (dp.getCRLIssuer() != null) - { - GeneralName genNames[] = dp.getCRLIssuer().getNames(); - // look for a DN - for (int j = 0; j < genNames.length; j++) - { - if (genNames[j].getTagNo() == GeneralName.directoryName) - { - try - { - issuers.add(new X509Principal(genNames[j].getName() - .toASN1Primitive().getEncoded())); - } - catch (IOException e) - { - throw new AnnotatedException( - "CRL issuer information from distribution point cannot be decoded.", - e); - } - } - } - } - else - { - /* - * certificate issuer is CRL issuer, distributionPoint field MUST be - * present. - */ - if (dp.getDistributionPoint() == null) - { - throw new AnnotatedException( - "CRL issuer is omitted from distribution point but no distributionPoint field present."); - } - // add and check issuer principals - for (Iterator it = issuerPrincipals.iterator(); it.hasNext(); ) - { - issuers.add((X509Principal)it.next()); - } - } - // TODO: is not found although this should correctly add the rel name. selector of Sun is buggy here or PKI test case is invalid - // distributionPoint -// if (dp.getDistributionPoint() != null) -// { -// // look for nameRelativeToCRLIssuer -// if (dp.getDistributionPoint().getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER) -// { -// // append fragment to issuer, only one -// // issuer can be there, if this is given -// if (issuers.size() != 1) -// { -// throw new AnnotatedException( -// "nameRelativeToCRLIssuer field is given but more than one CRL issuer is given."); -// } -// ASN1Encodable relName = dp.getDistributionPoint().getName(); -// Iterator it = issuers.iterator(); -// List issuersTemp = new ArrayList(issuers.size()); -// while (it.hasNext()) -// { -// Enumeration e = null; -// try -// { -// e = ASN1Sequence.getInstance( -// new ASN1InputStream(((X500Principal) it.next()) -// .getEncoded()).readObject()).getObjects(); -// } -// catch (IOException ex) -// { -// throw new AnnotatedException( -// "Cannot decode CRL issuer information.", ex); -// } -// ASN1EncodableVector v = new ASN1EncodableVector(); -// while (e.hasMoreElements()) -// { -// v.add((ASN1Encodable) e.nextElement()); -// } -// v.add(relName); -// issuersTemp.add(new X500Principal(new DERSequence(v) -// .getDEREncoded())); -// } -// issuers.clear(); -// issuers.addAll(issuersTemp); -// } -// } - Iterator it = issuers.iterator(); - while (it.hasNext()) - { - try - { - selector.addIssuerName(((X509Principal)it.next()).getEncoded()); - } - catch (IOException ex) - { - throw new AnnotatedException( - "Cannot decode CRL issuer information.", ex); - } - } - } - - private static BigInteger getSerialNumber( - Object cert) - { - if (cert instanceof X509Certificate) - { - return ((X509Certificate)cert).getSerialNumber(); - } - else - { - return ((X509AttributeCertificate)cert).getSerialNumber(); - } - } - - protected static void getCertStatus( - Date validDate, - X509CRL crl, - Object cert, - CertStatus certStatus) - throws AnnotatedException - { - X509CRLEntry crl_entry = null; - - boolean isIndirect; - try - { - isIndirect = X509CRLObject.isIndirectCRL(crl); - } - catch (CRLException exception) - { - throw new AnnotatedException("Failed check for indirect CRL.", exception); - } - - if (isIndirect) - { - if (!(crl instanceof X509CRLObject)) - { - try - { - crl = new X509CRLObject(CertificateList.getInstance(crl.getEncoded())); - } - catch (CRLException exception) - { - throw new AnnotatedException("Failed to recode indirect CRL.", exception); - } - } - - crl_entry = crl.getRevokedCertificate(getSerialNumber(cert)); - - if (crl_entry == null) - { - return; - } - - X509Principal certIssuer = ((X509CRLEntryObject)crl_entry).getCertificateIssuer(); - - if (certIssuer == null) - { - certIssuer = getIssuerPrincipal(crl); - } - - if (!getEncodedIssuerPrincipal(cert).equals(certIssuer)) - { - return; - } - } - else if (!getEncodedIssuerPrincipal(cert).equals(getIssuerPrincipal(crl))) - { - return; // not for our issuer, ignore - } - else - { - crl_entry = crl.getRevokedCertificate(getSerialNumber(cert)); - - if (crl_entry == null) - { - return; - } - } - - ASN1Enumerated reasonCode = null; - if (crl_entry.hasExtensions()) - { - try - { - reasonCode = ASN1Enumerated - .getInstance(CertPathValidatorUtilities - .getExtensionValue(crl_entry, - X509Extension.reasonCode.getId())); - } - catch (Exception e) - { - throw new AnnotatedException( - "Reason code CRL entry extension could not be decoded.", - e); - } - } - - // for reason keyCompromise, caCompromise, aACompromise or - // unspecified - if (!(validDate.getTime() < crl_entry.getRevocationDate().getTime()) - || reasonCode == null - || reasonCode.getValue().intValue() == 0 - || reasonCode.getValue().intValue() == 1 - || reasonCode.getValue().intValue() == 2 - || reasonCode.getValue().intValue() == 8) - { - - // (i) or (j) (1) - if (reasonCode != null) - { - certStatus.setCertStatus(reasonCode.getValue().intValue()); - } - // (i) or (j) (2) - else - { - certStatus.setCertStatus(CRLReason.unspecified); - } - certStatus.setRevocationDate(crl_entry.getRevocationDate()); - } - } - - /** - * Fetches delta CRLs according to RFC 3280 section 5.2.4. - * - * @param currentDate The date for which the delta CRLs must be valid. - * @param paramsPKIX The extended PKIX parameters. - * @param completeCRL The complete CRL the delta CRL is for. - * @return A Set of X509CRLs with delta CRLs. - * @throws AnnotatedException if an exception occurs while picking the delta - * CRLs. - */ - protected static Set getDeltaCRLs(Date currentDate, - ExtendedPKIXParameters paramsPKIX, X509CRL completeCRL) - throws AnnotatedException - { - - X509CRLStoreSelector deltaSelect = new X509CRLStoreSelector(); - - // 5.2.4 (a) - try - { - deltaSelect.addIssuerName(CertPathValidatorUtilities - .getIssuerPrincipal(completeCRL).getEncoded()); - } - catch (IOException e) - { - throw new AnnotatedException("Cannot extract issuer from CRL.", e); - } - - BigInteger completeCRLNumber = null; - try - { - ASN1Primitive derObject = CertPathValidatorUtilities.getExtensionValue(completeCRL, - CRL_NUMBER); - if (derObject != null) - { - completeCRLNumber = ASN1Integer.getInstance(derObject).getPositiveValue(); - } - } - catch (Exception e) - { - throw new AnnotatedException( - "CRL number extension could not be extracted from CRL.", e); - } - - // 5.2.4 (b) - byte[] idp = null; - try - { - idp = completeCRL.getExtensionValue(ISSUING_DISTRIBUTION_POINT); - } - catch (Exception e) - { - throw new AnnotatedException( - "Issuing distribution point extension value could not be read.", - e); - } - - // 5.2.4 (d) - - deltaSelect.setMinCRLNumber(completeCRLNumber == null ? null : completeCRLNumber - .add(BigInteger.valueOf(1))); - - deltaSelect.setIssuingDistributionPoint(idp); - deltaSelect.setIssuingDistributionPointEnabled(true); - - // 5.2.4 (c) - deltaSelect.setMaxBaseCRLNumber(completeCRLNumber); - - // find delta CRLs - Set temp = CRL_UTIL.findCRLs(deltaSelect, paramsPKIX, currentDate); - - Set result = new HashSet(); - - for (Iterator it = temp.iterator(); it.hasNext(); ) - { - X509CRL crl = (X509CRL)it.next(); - - if (isDeltaCRL(crl)) - { - result.add(crl); - } - } - - return result; - } - - private static boolean isDeltaCRL(X509CRL crl) - { - Set critical = crl.getCriticalExtensionOIDs(); - - if (critical == null) - { - return false; - } - - return critical.contains(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR); - } - - /** - * Fetches complete CRLs according to RFC 3280. - * - * @param dp The distribution point for which the complete CRL - * @param cert The X509Certificate or - * {@link org.spongycastle.x509.X509AttributeCertificate} for - * which the CRL should be searched. - * @param currentDate The date for which the delta CRLs must be valid. - * @param paramsPKIX The extended PKIX parameters. - * @return A Set of X509CRLs with complete - * CRLs. - * @throws AnnotatedException if an exception occurs while picking the CRLs - * or no CRLs are found. - */ - protected static Set getCompleteCRLs(DistributionPoint dp, Object cert, - Date currentDate, ExtendedPKIXParameters paramsPKIX) - throws AnnotatedException - { - X509CRLStoreSelector crlselect = new X509CRLStoreSelector(); - try - { - Set issuers = new HashSet(); - if (cert instanceof X509AttributeCertificate) - { - issuers.add(((X509AttributeCertificate)cert) - .getIssuer().getPrincipals()[0]); - } - else - { - issuers.add(getEncodedIssuerPrincipal(cert)); - } - CertPathValidatorUtilities.getCRLIssuersFromDistributionPoint(dp, issuers, crlselect, paramsPKIX); - } - catch (AnnotatedException e) - { - throw new AnnotatedException( - "Could not get issuer information from distribution point.", e); - } - if (cert instanceof X509Certificate) - { - crlselect.setCertificateChecking((X509Certificate)cert); - } - else if (cert instanceof X509AttributeCertificate) - { - crlselect.setAttrCertificateChecking((X509AttributeCertificate)cert); - } - - - crlselect.setCompleteCRLEnabled(true); - - Set crls = CRL_UTIL.findCRLs(crlselect, paramsPKIX, currentDate); - - if (crls.isEmpty()) - { - if (cert instanceof X509AttributeCertificate) - { - X509AttributeCertificate aCert = (X509AttributeCertificate)cert; - - throw new AnnotatedException("No CRLs found for issuer \"" + aCert.getIssuer().getPrincipals()[0] + "\""); - } - else - { - X509Certificate xCert = (X509Certificate)cert; - - throw new AnnotatedException("No CRLs found for issuer \"" + xCert.getIssuerDN() + "\""); - } - } - return crls; - } - - protected static Date getValidCertDateFromValidityModel( - ExtendedPKIXParameters paramsPKIX, CertPath certPath, int index) - throws AnnotatedException - { - if (paramsPKIX.getValidityModel() == ExtendedPKIXParameters.CHAIN_VALIDITY_MODEL) - { - // if end cert use given signing/encryption/... time - if (index <= 0) - { - return CertPathValidatorUtilities.getValidDate(paramsPKIX); - // else use time when previous cert was created - } - else - { - if (index - 1 == 0) - { - ASN1GeneralizedTime dateOfCertgen = null; - try - { - byte[] extBytes = ((X509Certificate)certPath.getCertificates().get(index - 1)).getExtensionValue(ISISMTTObjectIdentifiers.id_isismtt_at_dateOfCertGen.getId()); - if (extBytes != null) - { - dateOfCertgen = ASN1GeneralizedTime.getInstance(ASN1Primitive.fromByteArray(extBytes)); - } - } - catch (IOException e) - { - throw new AnnotatedException( - "Date of cert gen extension could not be read."); - } - catch (IllegalArgumentException e) - { - throw new AnnotatedException( - "Date of cert gen extension could not be read."); - } - if (dateOfCertgen != null) - { - try - { - return dateOfCertgen.getDate(); - } - catch (ParseException e) - { - throw new AnnotatedException( - "Date from date of cert gen extension could not be parsed.", - e); - } - } - return ((X509Certificate)certPath.getCertificates().get( - index - 1)).getNotBefore(); - } - else - { - return ((X509Certificate)certPath.getCertificates().get( - index - 1)).getNotBefore(); - } - } - } - else - { - return getValidDate(paramsPKIX); - } - } - - /** - * Return the next working key inheriting DSA parameters if necessary. - *

- * This methods inherits DSA parameters from the indexed certificate or - * previous certificates in the certificate chain to the returned - * PublicKey. The list is searched upwards, meaning the end - * certificate is at position 0 and previous certificates are following. - *

- *

- * If the indexed certificate does not contain a DSA key this method simply - * returns the public key. If the DSA key already contains DSA parameters - * the key is also only returned. - *

- * - * @param certs The certification path. - * @param index The index of the certificate which contains the public key - * which should be extended with DSA parameters. - * @return The public key of the certificate in list position - * index extended with DSA parameters if applicable. - * @throws AnnotatedException if DSA parameters cannot be inherited. - */ - protected static PublicKey getNextWorkingKey(List certs, int index) - throws CertPathValidatorException - { - Certificate cert = (Certificate)certs.get(index); - PublicKey pubKey = cert.getPublicKey(); - if (!(pubKey instanceof DSAPublicKey)) - { - return pubKey; - } - DSAPublicKey dsaPubKey = (DSAPublicKey)pubKey; - if (dsaPubKey.getParams() != null) - { - return dsaPubKey; - } - for (int i = index + 1; i < certs.size(); i++) - { - X509Certificate parentCert = (X509Certificate)certs.get(i); - pubKey = parentCert.getPublicKey(); - if (!(pubKey instanceof DSAPublicKey)) - { - throw new CertPathValidatorException( - "DSA parameters cannot be inherited from previous certificate."); - } - DSAPublicKey prevDSAPubKey = (DSAPublicKey)pubKey; - if (prevDSAPubKey.getParams() == null) - { - continue; - } - DSAParams dsaParams = prevDSAPubKey.getParams(); - DSAPublicKeySpec dsaPubKeySpec = new DSAPublicKeySpec( - dsaPubKey.getY(), dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); - try - { - KeyFactory keyFactory = KeyFactory.getInstance("DSA", BouncyCastleProvider.PROVIDER_NAME); - return keyFactory.generatePublic(dsaPubKeySpec); - } - catch (Exception exception) - { - throw new RuntimeException(exception.getMessage()); - } - } - throw new CertPathValidatorException("DSA parameters cannot be inherited from previous certificate."); - } - - /** - * Find the issuer certificates of a given certificate. - * - * @param cert The certificate for which an issuer should be found. - * @param pkixParams - * @return A Collection object containing the issuer - * X509Certificates. Never null. - * @throws AnnotatedException if an error occurs. - */ - protected static Collection findIssuerCerts( - X509Certificate cert, - ExtendedPKIXBuilderParameters pkixParams) - throws AnnotatedException - { - X509CertStoreSelector certSelect = new X509CertStoreSelector(); - Set certs = new HashSet(); - try - { - certSelect.setSubject(PrincipalUtil.getSubjectX509Principal(cert).getEncoded()); - } - catch (Exception ex) - { - throw new AnnotatedException( - "Subject criteria for certificate selector to find issuer certificate could not be set.", ex); - } - - Iterator iter; - - try - { - List matches = new ArrayList(); - - matches.addAll(CertPathValidatorUtilities.findCertificates(certSelect, pkixParams.getCertStores())); - matches.addAll(CertPathValidatorUtilities.findCertificates(certSelect, pkixParams.getStores())); - matches.addAll(CertPathValidatorUtilities.findCertificates(certSelect, pkixParams.getAdditionalStores())); - - iter = matches.iterator(); - } - catch (AnnotatedException e) - { - throw new AnnotatedException("Issuer certificate cannot be searched.", e); - } - - X509Certificate issuer = null; - while (iter.hasNext()) - { - issuer = (X509Certificate)iter.next(); - // issuer cannot be verified because possible DSA inheritance - // parameters are missing - certs.add(issuer); - } - return certs; - } - - protected static void verifyX509Certificate(X509Certificate cert, PublicKey publicKey, - String sigProvider) - throws GeneralSecurityException - { - if (sigProvider == null) - { - cert.verify(publicKey); - } - else - { - cert.verify(publicKey, sigProvider); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/CertStoreCollectionSpi.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/CertStoreCollectionSpi.java deleted file mode 100644 index a894cf84d..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/CertStoreCollectionSpi.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.security.InvalidAlgorithmParameterException; -import java.security.cert.CRL; -import org.spongycastle.jce.cert.CRLSelector; -import org.spongycastle.jce.cert.CertSelector; -import org.spongycastle.jce.cert.CertStoreException; -import org.spongycastle.jce.cert.CertStoreParameters; -import org.spongycastle.jce.cert.CertStoreSpi; -import java.security.cert.Certificate; -import org.spongycastle.jce.cert.CollectionCertStoreParameters; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -public class CertStoreCollectionSpi extends CertStoreSpi -{ - private CollectionCertStoreParameters params; - - public CertStoreCollectionSpi(CertStoreParameters params) - throws InvalidAlgorithmParameterException - { - super(params); - - if (!(params instanceof CollectionCertStoreParameters)) - { - throw new InvalidAlgorithmParameterException("org.spongycastle.jce.provider.CertStoreCollectionSpi: parameter must be a CollectionCertStoreParameters object\n" + params.toString()); - } - - this.params = (CollectionCertStoreParameters)params; - } - - public Collection engineGetCertificates( - CertSelector selector) - throws CertStoreException - { - List col = new ArrayList(); - Iterator iter = params.getCollection().iterator(); - - if (selector == null) - { - while (iter.hasNext()) - { - Object obj = iter.next(); - - if (obj instanceof Certificate) - { - col.add(obj); - } - } - } - else - { - while (iter.hasNext()) - { - Object obj = iter.next(); - - if ((obj instanceof Certificate) && selector.match((Certificate)obj)) - { - col.add(obj); - } - } - } - - return col; - } - - - public Collection engineGetCRLs( - CRLSelector selector) - throws CertStoreException - { - List col = new ArrayList(); - Iterator iter = params.getCollection().iterator(); - - if (selector == null) - { - while (iter.hasNext()) - { - Object obj = iter.next(); - - if (obj instanceof CRL) - { - col.add(obj); - } - } - } - else - { - while (iter.hasNext()) - { - Object obj = iter.next(); - - if ((obj instanceof CRL) && selector.match((CRL)obj)) - { - col.add(obj); - } - } - } - - return col; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/JCEPBEKey.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/JCEPBEKey.java deleted file mode 100644 index 53c9d66e6..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/JCEPBEKey.java +++ /dev/null @@ -1,146 +0,0 @@ -package org.spongycastle.jce.provider; - -import javax.crypto.SecretKey; -import javax.crypto.spec.PBEKeySpec; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.crypto.CipherParameters; -import org.spongycastle.crypto.PBEParametersGenerator; -import org.spongycastle.crypto.params.KeyParameter; -import org.spongycastle.crypto.params.ParametersWithIV; -import org.spongycastle.jcajce.provider.symmetric.util.PBE; - -public class JCEPBEKey - implements SecretKey -{ - String algorithm; - ASN1ObjectIdentifier oid; - int type; - int digest; - int keySize; - int ivSize; - CipherParameters param; - PBEKeySpec pbeKeySpec; - boolean tryWrong = false; - - /** - * @param param - */ - public JCEPBEKey( - String algorithm, - ASN1ObjectIdentifier oid, - int type, - int digest, - int keySize, - int ivSize, - PBEKeySpec pbeKeySpec, - CipherParameters param) - { - this.algorithm = algorithm; - this.oid = oid; - this.type = type; - this.digest = digest; - this.keySize = keySize; - this.ivSize = ivSize; - this.pbeKeySpec = pbeKeySpec; - this.param = param; - } - - public String getAlgorithm() - { - return algorithm; - } - - public String getFormat() - { - return "RAW"; - } - - public byte[] getEncoded() - { - if (param != null) - { - KeyParameter kParam; - - if (param instanceof ParametersWithIV) - { - kParam = (KeyParameter)((ParametersWithIV)param).getParameters(); - } - else - { - kParam = (KeyParameter)param; - } - - return kParam.getKey(); - } - else - { - if (type == PBE.PKCS12) - { - return PBEParametersGenerator.PKCS12PasswordToBytes(pbeKeySpec.getPassword()); - } - else - { - return PBEParametersGenerator.PKCS5PasswordToBytes(pbeKeySpec.getPassword()); - } - } - } - - int getType() - { - return type; - } - - int getDigest() - { - return digest; - } - - int getKeySize() - { - return keySize; - } - - int getIvSize() - { - return ivSize; - } - - CipherParameters getParam() - { - return param; - } - - /** - * these should never be called. - */ - int getIterationCount() - { - return 0; - } - - byte[] getSalt() - { - return null; - } - - /** - * Return the object identifier associated with this algorithm - * - * @return the oid for this PBE key - */ - public ASN1ObjectIdentifier getOID() - { - return oid; - } - - void setTryWrongPKCS12Zero(boolean tryWrong) - { - this.tryWrong = tryWrong; - } - - boolean shouldTryWrongPKCS12() - { - return tryWrong; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/JCESecretKeyFactory.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/JCESecretKeyFactory.java deleted file mode 100644 index b1c358b93..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/JCESecretKeyFactory.java +++ /dev/null @@ -1,557 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.lang.reflect.Constructor; -import java.security.InvalidKeyException; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.KeySpec; - -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactorySpi; -import javax.crypto.spec.DESKeySpec; -import javax.crypto.spec.DESedeKeySpec; -import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.SecretKeySpec; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.crypto.CipherParameters; -import org.spongycastle.jcajce.provider.symmetric.util.BCPBEKey; -import org.spongycastle.jcajce.provider.symmetric.util.PBE; - -public class JCESecretKeyFactory - extends SecretKeyFactorySpi - implements PBE -{ - protected String algName; - protected ASN1ObjectIdentifier algOid; - - protected JCESecretKeyFactory( - String algName, - ASN1ObjectIdentifier algOid) - { - this.algName = algName; - this.algOid = algOid; - } - - protected SecretKey engineGenerateSecret( - KeySpec keySpec) - throws InvalidKeySpecException - { - if (keySpec instanceof SecretKeySpec) - { - return (SecretKey)keySpec; - } - - throw new InvalidKeySpecException("Invalid KeySpec"); - } - - protected KeySpec engineGetKeySpec( - SecretKey key, - Class keySpec) - throws InvalidKeySpecException - { - if (keySpec == null) - { - throw new InvalidKeySpecException("keySpec parameter is null"); - } - if (key == null) - { - throw new InvalidKeySpecException("key parameter is null"); - } - - if (SecretKeySpec.class.isAssignableFrom(keySpec)) - { - return new SecretKeySpec(key.getEncoded(), algName); - } - - try - { - Class[] parameters = { byte[].class }; - - Constructor c = keySpec.getConstructor(parameters); - Object[] p = new Object[1]; - - p[0] = key.getEncoded(); - - return (KeySpec)c.newInstance(p); - } - catch (Exception e) - { - throw new InvalidKeySpecException(e.toString()); - } - } - - protected SecretKey engineTranslateKey( - SecretKey key) - throws InvalidKeyException - { - if (key == null) - { - throw new InvalidKeyException("key parameter is null"); - } - - if (!key.getAlgorithm().equalsIgnoreCase(algName)) - { - throw new InvalidKeyException("Key not of type " + algName + "."); - } - - return new SecretKeySpec(key.getEncoded(), algName); - } - - /* - * classes that inherit from us - */ - - static public class PBEKeyFactory - extends JCESecretKeyFactory - { - private boolean forCipher; - private int scheme; - private int digest; - private int keySize; - private int ivSize; - - public PBEKeyFactory( - String algorithm, - ASN1ObjectIdentifier oid, - boolean forCipher, - int scheme, - int digest, - int keySize, - int ivSize) - { - super(algorithm, oid); - - this.forCipher = forCipher; - this.scheme = scheme; - this.digest = digest; - this.keySize = keySize; - this.ivSize = ivSize; - } - - protected SecretKey engineGenerateSecret( - KeySpec keySpec) - throws InvalidKeySpecException - { - if (keySpec instanceof PBEKeySpec) - { - PBEKeySpec pbeSpec = (PBEKeySpec)keySpec; - CipherParameters param; - - return new BCPBEKey(this.algName, this.algOid, scheme, digest, keySize, ivSize, pbeSpec, null); - } - - throw new InvalidKeySpecException("Invalid KeySpec"); - } - } - - static public class DESPBEKeyFactory - extends JCESecretKeyFactory - { - private boolean forCipher; - private int scheme; - private int digest; - private int keySize; - private int ivSize; - - public DESPBEKeyFactory( - String algorithm, - ASN1ObjectIdentifier oid, - boolean forCipher, - int scheme, - int digest, - int keySize, - int ivSize) - { - super(algorithm, oid); - - this.forCipher = forCipher; - this.scheme = scheme; - this.digest = digest; - this.keySize = keySize; - this.ivSize = ivSize; - } - - protected SecretKey engineGenerateSecret( - KeySpec keySpec) - throws InvalidKeySpecException - { - if (keySpec instanceof PBEKeySpec) - { - PBEKeySpec pbeSpec = (PBEKeySpec)keySpec; - CipherParameters param; - - return new BCPBEKey(this.algName, this.algOid, scheme, digest, keySize, ivSize, pbeSpec, null); - } - - throw new InvalidKeySpecException("Invalid KeySpec"); - } - } - - static public class DES - extends JCESecretKeyFactory - { - public DES() - { - super("DES", null); - } - - protected SecretKey engineGenerateSecret( - KeySpec keySpec) - throws InvalidKeySpecException - { - if (keySpec instanceof DESKeySpec) - { - DESKeySpec desKeySpec = (DESKeySpec)keySpec; - return new SecretKeySpec(desKeySpec.getKey(), "DES"); - } - - return super.engineGenerateSecret(keySpec); - } - } - - static public class DESede - extends JCESecretKeyFactory - { - public DESede() - { - super("DESede", null); - } - - protected KeySpec engineGetKeySpec( - SecretKey key, - Class keySpec) - throws InvalidKeySpecException - { - if (keySpec == null) - { - throw new InvalidKeySpecException("keySpec parameter is null"); - } - if (key == null) - { - throw new InvalidKeySpecException("key parameter is null"); - } - - if (SecretKeySpec.class.isAssignableFrom(keySpec)) - { - return new SecretKeySpec(key.getEncoded(), algName); - } - else if (DESedeKeySpec.class.isAssignableFrom(keySpec)) - { - byte[] bytes = key.getEncoded(); - - try - { - if (bytes.length == 16) - { - byte[] longKey = new byte[24]; - - System.arraycopy(bytes, 0, longKey, 0, 16); - System.arraycopy(bytes, 0, longKey, 16, 8); - - return new DESedeKeySpec(longKey); - } - else - { - return new DESedeKeySpec(bytes); - } - } - catch (Exception e) - { - throw new InvalidKeySpecException(e.toString()); - } - } - - throw new InvalidKeySpecException("Invalid KeySpec"); - } - - protected SecretKey engineGenerateSecret( - KeySpec keySpec) - throws InvalidKeySpecException - { - if (keySpec instanceof DESedeKeySpec) - { - DESedeKeySpec desKeySpec = (DESedeKeySpec)keySpec; - return new SecretKeySpec(desKeySpec.getKey(), "DESede"); - } - - return super.engineGenerateSecret(keySpec); - } - } - - /** - * PBEWithMD5AndDES - */ - static public class PBEWithMD5AndDES - extends DESPBEKeyFactory - { - public PBEWithMD5AndDES() - { - super("PBEwithMD5andDES", null, true, PKCS5S1, MD5, 64, 64); - } - } - - /** - * PBEWithMD5AndRC2 - */ - static public class PBEWithMD5AndRC2 - extends PBEKeyFactory - { - public PBEWithMD5AndRC2() - { - super("PBEwithMD5andRC2", null, true, PKCS5S1, MD5, 64, 64); - } - } - - /** - * PBEWithSHA1AndDES - */ - static public class PBEWithSHA1AndDES - extends PBEKeyFactory - { - public PBEWithSHA1AndDES() - { - super("PBEwithSHA1andDES", null, true, PKCS5S1, SHA1, 64, 64); - } - } - - /** - * PBEWithSHA1AndRC2 - */ - static public class PBEWithSHA1AndRC2 - extends PBEKeyFactory - { - public PBEWithSHA1AndRC2() - { - super("PBEwithSHA1andRC2", null, true, PKCS5S1, SHA1, 64, 64); - } - } - - /** - * PBEWithSHAAnd3-KeyTripleDES-CBC - */ - static public class PBEWithSHAAndDES3Key - extends PBEKeyFactory - { - public PBEWithSHAAndDES3Key() - { - super("PBEwithSHAandDES3Key-CBC", PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC, true, PKCS12, SHA1, 192, 64); - } - } - - /** - * PBEWithSHAAnd2-KeyTripleDES-CBC - */ - static public class PBEWithSHAAndDES2Key - extends PBEKeyFactory - { - public PBEWithSHAAndDES2Key() - { - super("PBEwithSHAandDES2Key-CBC", PKCSObjectIdentifiers.pbeWithSHAAnd2_KeyTripleDES_CBC, true, PKCS12, SHA1, 128, 64); - } - } - - /** - * PBEWithSHAAnd128BitRC2-CBC - */ - static public class PBEWithSHAAnd128BitRC2 - extends PBEKeyFactory - { - public PBEWithSHAAnd128BitRC2() - { - super("PBEwithSHAand128BitRC2-CBC", PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC, true, PKCS12, SHA1, 128, 64); - } - } - - /** - * PBEWithSHAAnd40BitRC2-CBC - */ - static public class PBEWithSHAAnd40BitRC2 - extends PBEKeyFactory - { - public PBEWithSHAAnd40BitRC2() - { - super("PBEwithSHAand40BitRC2-CBC", PKCSObjectIdentifiers.pbewithSHAAnd40BitRC2_CBC, true, PKCS12, SHA1, 40, 64); - } - } - - /** - * PBEWithSHAAndTwofish-CBC - */ - static public class PBEWithSHAAndTwofish - extends PBEKeyFactory - { - public PBEWithSHAAndTwofish() - { - super("PBEwithSHAandTwofish-CBC", null, true, PKCS12, SHA1, 256, 128); - } - } - - /** - * PBEWithSHAAnd128BitRC4 - */ - static public class PBEWithSHAAnd128BitRC4 - extends PBEKeyFactory - { - public PBEWithSHAAnd128BitRC4() - { - super("PBEWithSHAAnd128BitRC4", PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC4, true, PKCS12, SHA1, 128, 0); - } - } - - /** - * PBEWithSHAAnd40BitRC4 - */ - static public class PBEWithSHAAnd40BitRC4 - extends PBEKeyFactory - { - public PBEWithSHAAnd40BitRC4() - { - super("PBEWithSHAAnd128BitRC4", PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC4, true, PKCS12, SHA1, 40, 0); - } - } - - /** - * PBEWithHmacRIPEMD160 - */ - public static class PBEWithRIPEMD160 - extends PBEKeyFactory - { - public PBEWithRIPEMD160() - { - super("PBEwithHmacRIPEMD160", null, false, PKCS12, RIPEMD160, 160, 0); - } - } - - /** - * PBEWithHmacSHA - */ - public static class PBEWithSHA - extends PBEKeyFactory - { - public PBEWithSHA() - { - super("PBEwithHmacSHA", null, false, PKCS12, SHA1, 160, 0); - } - } - - /** - * PBEWithHmacTiger - */ - public static class PBEWithTiger - extends PBEKeyFactory - { - public PBEWithTiger() - { - super("PBEwithHmacTiger", null, false, PKCS12, TIGER, 192, 0); - } - } - - /** - * PBEWithSHA1And128BitAES-BC - */ - static public class PBEWithSHAAnd128BitAESBC - extends PBEKeyFactory - { - public PBEWithSHAAnd128BitAESBC() - { - super("PBEWithSHA1And128BitAES-CBC-BC", null, true, PKCS12, SHA1, 128, 128); - } - } - - /** - * PBEWithSHA1And192BitAES-BC - */ - static public class PBEWithSHAAnd192BitAESBC - extends PBEKeyFactory - { - public PBEWithSHAAnd192BitAESBC() - { - super("PBEWithSHA1And192BitAES-CBC-BC", null, true, PKCS12, SHA1, 192, 128); - } - } - - /** - * PBEWithSHA1And256BitAES-BC - */ - static public class PBEWithSHAAnd256BitAESBC - extends PBEKeyFactory - { - public PBEWithSHAAnd256BitAESBC() - { - super("PBEWithSHA1And256BitAES-CBC-BC", null, true, PKCS12, SHA1, 256, 128); - } - } - - /** - * PBEWithSHA256And128BitAES-BC - */ - static public class PBEWithSHA256And128BitAESBC - extends PBEKeyFactory - { - public PBEWithSHA256And128BitAESBC() - { - super("PBEWithSHA256And128BitAES-CBC-BC", null, true, PKCS12, SHA256, 128, 128); - } - } - - /** - * PBEWithSHA256And192BitAES-BC - */ - static public class PBEWithSHA256And192BitAESBC - extends PBEKeyFactory - { - public PBEWithSHA256And192BitAESBC() - { - super("PBEWithSHA256And192BitAES-CBC-BC", null, true, PKCS12, SHA256, 192, 128); - } - } - - /** - * PBEWithSHA256And256BitAES-BC - */ - static public class PBEWithSHA256And256BitAESBC - extends PBEKeyFactory - { - public PBEWithSHA256And256BitAESBC() - { - super("PBEWithSHA256And256BitAES-CBC-BC", null, true, PKCS12, SHA256, 256, 128); - } - } - - /** - * PBEWithMD5And128BitAES-OpenSSL - */ - static public class PBEWithMD5And128BitAESCBCOpenSSL - extends PBEKeyFactory - { - public PBEWithMD5And128BitAESCBCOpenSSL() - { - super("PBEWithMD5And128BitAES-CBC-OpenSSL", null, true, OPENSSL, MD5, 128, 128); - } - } - - /** - * PBEWithMD5And128BitAES-OpenSSL - */ - static public class PBEWithMD5And192BitAESCBCOpenSSL - extends PBEKeyFactory - { - public PBEWithMD5And192BitAESCBCOpenSSL() - { - super("PBEWithMD5And128BitAES-CBC-OpenSSL", null, true, OPENSSL, MD5, 192, 128); - } - } - - /** - * PBEWithMD5And128BitAES-OpenSSL - */ - static public class PBEWithMD5And256BitAESCBCOpenSSL - extends PBEKeyFactory - { - public PBEWithMD5And256BitAESCBCOpenSSL() - { - super("PBEWithMD5And128BitAES-CBC-OpenSSL", null, true, OPENSSL, MD5, 256, 128); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/JDKAlgorithmParameters.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/JDKAlgorithmParameters.java deleted file mode 100644 index 9b33841f2..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/JDKAlgorithmParameters.java +++ /dev/null @@ -1,643 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.security.AlgorithmParametersSpi; -import java.security.spec.AlgorithmParameterSpec; -import java.security.spec.InvalidParameterSpecException; - -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.PBEParameterSpec; -import javax.crypto.spec.RC2ParameterSpec; - -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.DEROutputStream; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.misc.CAST5CBCParameters; -import org.spongycastle.asn1.pkcs.PKCS12PBEParams; -import org.spongycastle.asn1.pkcs.RC2CBCParameter; -import org.spongycastle.jce.spec.IESParameterSpec; - -public abstract class JDKAlgorithmParameters - extends AlgorithmParametersSpi -{ - protected boolean isASN1FormatString(String format) - { - return format == null || format.equals("ASN.1"); - } - - protected AlgorithmParameterSpec engineGetParameterSpec( - Class paramSpec) - throws InvalidParameterSpecException - { - if (paramSpec == null) - { - throw new NullPointerException("argument to getParameterSpec must not be null"); - } - - return localEngineGetParameterSpec(paramSpec); - } - - protected abstract AlgorithmParameterSpec localEngineGetParameterSpec(Class paramSpec) - throws InvalidParameterSpecException; - - public static class IVAlgorithmParameters - extends JDKAlgorithmParameters - { - private byte[] iv; - - protected byte[] engineGetEncoded() - throws IOException - { - return engineGetEncoded("ASN.1"); - } - - protected byte[] engineGetEncoded( - String format) - throws IOException - { - if (this.isASN1FormatString(format)) - { - return new DEROctetString(engineGetEncoded("RAW")).getEncoded(); - } - - if (format.equals("RAW")) - { - byte[] tmp = new byte[iv.length]; - - System.arraycopy(iv, 0, tmp, 0, iv.length); - return tmp; - } - - return null; - } - - protected AlgorithmParameterSpec localEngineGetParameterSpec( - Class paramSpec) - throws InvalidParameterSpecException - { - if (paramSpec == IvParameterSpec.class) - { - return new IvParameterSpec(iv); - } - - throw new InvalidParameterSpecException("unknown parameter spec passed to IV parameters object."); - } - - protected void engineInit( - AlgorithmParameterSpec paramSpec) - throws InvalidParameterSpecException - { - if (!(paramSpec instanceof IvParameterSpec)) - { - throw new InvalidParameterSpecException("IvParameterSpec required to initialise a IV parameters algorithm parameters object"); - } - - this.iv = ((IvParameterSpec)paramSpec).getIV(); - } - - protected void engineInit( - byte[] params) - throws IOException - { - // - // check that we don't have a DER encoded octet string - // - if ((params.length % 8) != 0 - && params[0] == 0x04 && params[1] == params.length - 2) - { - ASN1InputStream aIn = new ASN1InputStream(params); - ASN1OctetString oct = (ASN1OctetString)aIn.readObject(); - - params = oct.getOctets(); - } - - this.iv = new byte[params.length]; - - System.arraycopy(params, 0, iv, 0, iv.length); - } - - protected void engineInit( - byte[] params, - String format) - throws IOException - { - if (this.isASN1FormatString(format)) - { - ASN1InputStream aIn = new ASN1InputStream(params); - - try - { - ASN1OctetString oct = (ASN1OctetString)aIn.readObject(); - - engineInit(oct.getOctets()); - } - catch (Exception e) - { - throw new IOException("Exception decoding: " + e); - } - - return; - } - - if (format.equals("RAW")) - { - engineInit(params); - return; - } - - throw new IOException("Unknown parameters format in IV parameters object"); - } - - protected String engineToString() - { - return "IV Parameters"; - } - } - - public static class RC2AlgorithmParameters - extends JDKAlgorithmParameters - { - private short[] table = { - 0xbd, 0x56, 0xea, 0xf2, 0xa2, 0xf1, 0xac, 0x2a, 0xb0, 0x93, 0xd1, 0x9c, 0x1b, 0x33, 0xfd, 0xd0, - 0x30, 0x04, 0xb6, 0xdc, 0x7d, 0xdf, 0x32, 0x4b, 0xf7, 0xcb, 0x45, 0x9b, 0x31, 0xbb, 0x21, 0x5a, - 0x41, 0x9f, 0xe1, 0xd9, 0x4a, 0x4d, 0x9e, 0xda, 0xa0, 0x68, 0x2c, 0xc3, 0x27, 0x5f, 0x80, 0x36, - 0x3e, 0xee, 0xfb, 0x95, 0x1a, 0xfe, 0xce, 0xa8, 0x34, 0xa9, 0x13, 0xf0, 0xa6, 0x3f, 0xd8, 0x0c, - 0x78, 0x24, 0xaf, 0x23, 0x52, 0xc1, 0x67, 0x17, 0xf5, 0x66, 0x90, 0xe7, 0xe8, 0x07, 0xb8, 0x60, - 0x48, 0xe6, 0x1e, 0x53, 0xf3, 0x92, 0xa4, 0x72, 0x8c, 0x08, 0x15, 0x6e, 0x86, 0x00, 0x84, 0xfa, - 0xf4, 0x7f, 0x8a, 0x42, 0x19, 0xf6, 0xdb, 0xcd, 0x14, 0x8d, 0x50, 0x12, 0xba, 0x3c, 0x06, 0x4e, - 0xec, 0xb3, 0x35, 0x11, 0xa1, 0x88, 0x8e, 0x2b, 0x94, 0x99, 0xb7, 0x71, 0x74, 0xd3, 0xe4, 0xbf, - 0x3a, 0xde, 0x96, 0x0e, 0xbc, 0x0a, 0xed, 0x77, 0xfc, 0x37, 0x6b, 0x03, 0x79, 0x89, 0x62, 0xc6, - 0xd7, 0xc0, 0xd2, 0x7c, 0x6a, 0x8b, 0x22, 0xa3, 0x5b, 0x05, 0x5d, 0x02, 0x75, 0xd5, 0x61, 0xe3, - 0x18, 0x8f, 0x55, 0x51, 0xad, 0x1f, 0x0b, 0x5e, 0x85, 0xe5, 0xc2, 0x57, 0x63, 0xca, 0x3d, 0x6c, - 0xb4, 0xc5, 0xcc, 0x70, 0xb2, 0x91, 0x59, 0x0d, 0x47, 0x20, 0xc8, 0x4f, 0x58, 0xe0, 0x01, 0xe2, - 0x16, 0x38, 0xc4, 0x6f, 0x3b, 0x0f, 0x65, 0x46, 0xbe, 0x7e, 0x2d, 0x7b, 0x82, 0xf9, 0x40, 0xb5, - 0x1d, 0x73, 0xf8, 0xeb, 0x26, 0xc7, 0x87, 0x97, 0x25, 0x54, 0xb1, 0x28, 0xaa, 0x98, 0x9d, 0xa5, - 0x64, 0x6d, 0x7a, 0xd4, 0x10, 0x81, 0x44, 0xef, 0x49, 0xd6, 0xae, 0x2e, 0xdd, 0x76, 0x5c, 0x2f, - 0xa7, 0x1c, 0xc9, 0x09, 0x69, 0x9a, 0x83, 0xcf, 0x29, 0x39, 0xb9, 0xe9, 0x4c, 0xff, 0x43, 0xab - }; - - private short[] ekb = { - 0x5d, 0xbe, 0x9b, 0x8b, 0x11, 0x99, 0x6e, 0x4d, 0x59, 0xf3, 0x85, 0xa6, 0x3f, 0xb7, 0x83, 0xc5, - 0xe4, 0x73, 0x6b, 0x3a, 0x68, 0x5a, 0xc0, 0x47, 0xa0, 0x64, 0x34, 0x0c, 0xf1, 0xd0, 0x52, 0xa5, - 0xb9, 0x1e, 0x96, 0x43, 0x41, 0xd8, 0xd4, 0x2c, 0xdb, 0xf8, 0x07, 0x77, 0x2a, 0xca, 0xeb, 0xef, - 0x10, 0x1c, 0x16, 0x0d, 0x38, 0x72, 0x2f, 0x89, 0xc1, 0xf9, 0x80, 0xc4, 0x6d, 0xae, 0x30, 0x3d, - 0xce, 0x20, 0x63, 0xfe, 0xe6, 0x1a, 0xc7, 0xb8, 0x50, 0xe8, 0x24, 0x17, 0xfc, 0x25, 0x6f, 0xbb, - 0x6a, 0xa3, 0x44, 0x53, 0xd9, 0xa2, 0x01, 0xab, 0xbc, 0xb6, 0x1f, 0x98, 0xee, 0x9a, 0xa7, 0x2d, - 0x4f, 0x9e, 0x8e, 0xac, 0xe0, 0xc6, 0x49, 0x46, 0x29, 0xf4, 0x94, 0x8a, 0xaf, 0xe1, 0x5b, 0xc3, - 0xb3, 0x7b, 0x57, 0xd1, 0x7c, 0x9c, 0xed, 0x87, 0x40, 0x8c, 0xe2, 0xcb, 0x93, 0x14, 0xc9, 0x61, - 0x2e, 0xe5, 0xcc, 0xf6, 0x5e, 0xa8, 0x5c, 0xd6, 0x75, 0x8d, 0x62, 0x95, 0x58, 0x69, 0x76, 0xa1, - 0x4a, 0xb5, 0x55, 0x09, 0x78, 0x33, 0x82, 0xd7, 0xdd, 0x79, 0xf5, 0x1b, 0x0b, 0xde, 0x26, 0x21, - 0x28, 0x74, 0x04, 0x97, 0x56, 0xdf, 0x3c, 0xf0, 0x37, 0x39, 0xdc, 0xff, 0x06, 0xa4, 0xea, 0x42, - 0x08, 0xda, 0xb4, 0x71, 0xb0, 0xcf, 0x12, 0x7a, 0x4e, 0xfa, 0x6c, 0x1d, 0x84, 0x00, 0xc8, 0x7f, - 0x91, 0x45, 0xaa, 0x2b, 0xc2, 0xb1, 0x8f, 0xd5, 0xba, 0xf2, 0xad, 0x19, 0xb2, 0x67, 0x36, 0xf7, - 0x0f, 0x0a, 0x92, 0x7d, 0xe3, 0x9d, 0xe9, 0x90, 0x3e, 0x23, 0x27, 0x66, 0x13, 0xec, 0x81, 0x15, - 0xbd, 0x22, 0xbf, 0x9f, 0x7e, 0xa9, 0x51, 0x4b, 0x4c, 0xfb, 0x02, 0xd3, 0x70, 0x86, 0x31, 0xe7, - 0x3b, 0x05, 0x03, 0x54, 0x60, 0x48, 0x65, 0x18, 0xd2, 0xcd, 0x5f, 0x32, 0x88, 0x0e, 0x35, 0xfd - }; - - private byte[] iv; - private int parameterVersion = 58; - - protected byte[] engineGetEncoded() - { - byte[] tmp = new byte[iv.length]; - - System.arraycopy(iv, 0, tmp, 0, iv.length); - return tmp; - } - - protected byte[] engineGetEncoded( - String format) - throws IOException - { - if (this.isASN1FormatString(format)) - { - if (parameterVersion == -1) - { - return new RC2CBCParameter(engineGetEncoded()).getEncoded(); - } - else - { - return new RC2CBCParameter(parameterVersion, engineGetEncoded()).getEncoded(); - } - } - - if (format.equals("RAW")) - { - return engineGetEncoded(); - } - - return null; - } - - protected AlgorithmParameterSpec localEngineGetParameterSpec( - Class paramSpec) - throws InvalidParameterSpecException - { - if (paramSpec == RC2ParameterSpec.class) - { - if (parameterVersion != -1) - { - if (parameterVersion < 256) - { - return new RC2ParameterSpec(ekb[parameterVersion], iv); - } - else - { - return new RC2ParameterSpec(parameterVersion, iv); - } - } - } - - if (paramSpec == IvParameterSpec.class) - { - return new IvParameterSpec(iv); - } - - throw new InvalidParameterSpecException("unknown parameter spec passed to RC2 parameters object."); - } - - protected void engineInit( - AlgorithmParameterSpec paramSpec) - throws InvalidParameterSpecException - { - if (paramSpec instanceof IvParameterSpec) - { - this.iv = ((IvParameterSpec)paramSpec).getIV(); - } - else if (paramSpec instanceof RC2ParameterSpec) - { - int effKeyBits = ((RC2ParameterSpec)paramSpec).getEffectiveKeyBits(); - if (effKeyBits != -1) - { - if (effKeyBits < 256) - { - parameterVersion = table[effKeyBits]; - } - else - { - parameterVersion = effKeyBits; - } - } - - this.iv = ((RC2ParameterSpec)paramSpec).getIV(); - } - else - { - throw new InvalidParameterSpecException("IvParameterSpec or RC2ParameterSpec required to initialise a RC2 parameters algorithm parameters object"); - } - } - - protected void engineInit( - byte[] params) - throws IOException - { - this.iv = new byte[params.length]; - - System.arraycopy(params, 0, iv, 0, iv.length); - } - - protected void engineInit( - byte[] params, - String format) - throws IOException - { - if (this.isASN1FormatString(format)) - { - ASN1InputStream aIn = new ASN1InputStream(params); - RC2CBCParameter p = RC2CBCParameter.getInstance(aIn.readObject()); - - if (p.getRC2ParameterVersion() != null) - { - parameterVersion = p.getRC2ParameterVersion().intValue(); - } - - iv = p.getIV(); - - return; - } - - if (format.equals("RAW")) - { - engineInit(params); - return; - } - - throw new IOException("Unknown parameters format in IV parameters object"); - } - - protected String engineToString() - { - return "RC2 Parameters"; - } - } - - public static class CAST5AlgorithmParameters - extends JDKAlgorithmParameters - { - private byte[] iv; - private int keyLength = 128; - - protected byte[] engineGetEncoded() - { - byte[] tmp = new byte[iv.length]; - - System.arraycopy(iv, 0, tmp, 0, iv.length); - return tmp; - } - - protected byte[] engineGetEncoded( - String format) - throws IOException - { - if (this.isASN1FormatString(format)) - { - return new CAST5CBCParameters(engineGetEncoded(), keyLength).getEncoded(); - } - - if (format.equals("RAW")) - { - return engineGetEncoded(); - } - - - return null; - } - - protected AlgorithmParameterSpec localEngineGetParameterSpec( - Class paramSpec) - throws InvalidParameterSpecException - { - if (paramSpec == IvParameterSpec.class) - { - return new IvParameterSpec(iv); - } - - throw new InvalidParameterSpecException("unknown parameter spec passed to CAST5 parameters object."); - } - - protected void engineInit( - AlgorithmParameterSpec paramSpec) - throws InvalidParameterSpecException - { - if (paramSpec instanceof IvParameterSpec) - { - this.iv = ((IvParameterSpec)paramSpec).getIV(); - } - else - { - throw new InvalidParameterSpecException("IvParameterSpec required to initialise a CAST5 parameters algorithm parameters object"); - } - } - - protected void engineInit( - byte[] params) - throws IOException - { - this.iv = new byte[params.length]; - - System.arraycopy(params, 0, iv, 0, iv.length); - } - - protected void engineInit( - byte[] params, - String format) - throws IOException - { - if (this.isASN1FormatString(format)) - { - ASN1InputStream aIn = new ASN1InputStream(params); - CAST5CBCParameters p = CAST5CBCParameters.getInstance(aIn.readObject()); - - keyLength = p.getKeyLength(); - - iv = p.getIV(); - - return; - } - - if (format.equals("RAW")) - { - engineInit(params); - return; - } - - throw new IOException("Unknown parameters format in IV parameters object"); - } - - protected String engineToString() - { - return "CAST5 Parameters"; - } - } - - public static class PKCS12PBE - extends JDKAlgorithmParameters - { - PKCS12PBEParams params; - - protected byte[] engineGetEncoded() - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - DEROutputStream dOut = new DEROutputStream(bOut); - - try - { - dOut.writeObject(params); - } - catch (IOException e) - { - throw new RuntimeException("Oooops! " + e.toString()); - } - - return bOut.toByteArray(); - } - - protected byte[] engineGetEncoded( - String format) - { - if (this.isASN1FormatString(format)) - { - return engineGetEncoded(); - } - - return null; - } - - protected AlgorithmParameterSpec localEngineGetParameterSpec( - Class paramSpec) - throws InvalidParameterSpecException - { - if (paramSpec == PBEParameterSpec.class) - { - return new PBEParameterSpec(params.getIV(), - params.getIterations().intValue()); - } - - throw new InvalidParameterSpecException("unknown parameter spec passed to PKCS12 PBE parameters object."); - } - - protected void engineInit( - AlgorithmParameterSpec paramSpec) - throws InvalidParameterSpecException - { - if (!(paramSpec instanceof PBEParameterSpec)) - { - throw new InvalidParameterSpecException("PBEParameterSpec required to initialise a PKCS12 PBE parameters algorithm parameters object"); - } - - PBEParameterSpec pbeSpec = (PBEParameterSpec)paramSpec; - - this.params = new PKCS12PBEParams(pbeSpec.getSalt(), - pbeSpec.getIterationCount()); - } - - protected void engineInit( - byte[] params) - throws IOException - { - ASN1InputStream aIn = new ASN1InputStream(params); - - this.params = PKCS12PBEParams.getInstance(aIn.readObject()); - } - - protected void engineInit( - byte[] params, - String format) - throws IOException - { - if (this.isASN1FormatString(format)) - { - engineInit(params); - return; - } - - throw new IOException("Unknown parameters format in PKCS12 PBE parameters object"); - } - - protected String engineToString() - { - return "PKCS12 PBE Parameters"; - } - } - - public static class IES - extends JDKAlgorithmParameters - { - IESParameterSpec currentSpec; - - /** - * in the abscence of a standard way of doing it this will do for - * now... - */ - protected byte[] engineGetEncoded() - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - DEROutputStream dOut = new DEROutputStream(bOut); - - try - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(new DEROctetString(currentSpec.getDerivationV())); - v.add(new DEROctetString(currentSpec.getEncodingV())); - v.add(new ASN1Integer(currentSpec.getMacKeySize())); - - dOut.writeObject(new DERSequence(v)); - dOut.close(); - } - catch (IOException e) - { - throw new RuntimeException("Error encoding IESParameters"); - } - - return bOut.toByteArray(); - } - - protected byte[] engineGetEncoded( - String format) - { - if (this.isASN1FormatString(format) || format.equalsIgnoreCase("X.509")) - { - return engineGetEncoded(); - } - - return null; - } - - protected AlgorithmParameterSpec localEngineGetParameterSpec( - Class paramSpec) - throws InvalidParameterSpecException - { - if (paramSpec == IESParameterSpec.class) - { - return currentSpec; - } - - throw new InvalidParameterSpecException("unknown parameter spec passed to ElGamal parameters object."); - } - - protected void engineInit( - AlgorithmParameterSpec paramSpec) - throws InvalidParameterSpecException - { - if (!(paramSpec instanceof IESParameterSpec)) - { - throw new InvalidParameterSpecException("IESParameterSpec required to initialise a IES algorithm parameters object"); - } - - this.currentSpec = (IESParameterSpec)paramSpec; - } - - protected void engineInit( - byte[] params) - throws IOException - { - ASN1InputStream aIn = new ASN1InputStream(params); - - try - { - ASN1Sequence s = (ASN1Sequence)aIn.readObject(); - - this.currentSpec = new IESParameterSpec( - ((ASN1OctetString)s.getObjectAt(0)).getOctets(), - ((ASN1OctetString)s.getObjectAt(0)).getOctets(), - ((ASN1Integer)s.getObjectAt(0)).getValue().intValue()); - } - catch (ClassCastException e) - { - throw new IOException("Not a valid IES Parameter encoding."); - } - catch (ArrayIndexOutOfBoundsException e) - { - throw new IOException("Not a valid IES Parameter encoding."); - } - } - - protected void engineInit( - byte[] params, - String format) - throws IOException - { - if (this.isASN1FormatString(format) || format.equalsIgnoreCase("X.509")) - { - engineInit(params); - } - else - { - throw new IOException("Unknown parameter format " + format); - } - } - - protected String engineToString() - { - return "IES Parameters"; - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/MultiCertStoreSpi.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/MultiCertStoreSpi.java deleted file mode 100644 index e3102c77d..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/MultiCertStoreSpi.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.spongycastle.jce.provider; - -import org.spongycastle.jce.MultiCertStoreParameters; - -import java.security.InvalidAlgorithmParameterException; -import org.spongycastle.jce.cert.CRLSelector; -import org.spongycastle.jce.cert.CertSelector; -import org.spongycastle.jce.cert.CertStore; -import org.spongycastle.jce.cert.CertStoreException; -import org.spongycastle.jce.cert.CertStoreParameters; -import org.spongycastle.jce.cert.CertStoreSpi; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -public class MultiCertStoreSpi - extends CertStoreSpi -{ - private MultiCertStoreParameters params; - - public MultiCertStoreSpi(CertStoreParameters params) - throws InvalidAlgorithmParameterException - { - super(params); - - if (!(params instanceof MultiCertStoreParameters)) - { - throw new InvalidAlgorithmParameterException("org.spongycastle.jce.provider.MultiCertStoreSpi: parameter must be a MultiCertStoreParameters object\n" + params.toString()); - } - - this.params = (MultiCertStoreParameters)params; - } - - public Collection engineGetCertificates(CertSelector certSelector) - throws CertStoreException - { - boolean searchAllStores = params.getSearchAllStores(); - Iterator iter = params.getCertStores().iterator(); - List allCerts = searchAllStores ? new ArrayList() : Collections.EMPTY_LIST; - - while (iter.hasNext()) - { - CertStore store = (CertStore)iter.next(); - Collection certs = store.getCertificates(certSelector); - - if (searchAllStores) - { - allCerts.addAll(certs); - } - else if (!certs.isEmpty()) - { - return certs; - } - } - - return allCerts; - } - - public Collection engineGetCRLs(CRLSelector crlSelector) - throws CertStoreException - { - boolean searchAllStores = params.getSearchAllStores(); - Iterator iter = params.getCertStores().iterator(); - List allCRLs = searchAllStores ? new ArrayList() : Collections.EMPTY_LIST; - - while (iter.hasNext()) - { - CertStore store = (CertStore)iter.next(); - Collection crls = store.getCRLs(crlSelector); - - if (searchAllStores) - { - allCRLs.addAll(crls); - } - else if (!crls.isEmpty()) - { - return crls; - } - } - - return allCRLs; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/PKIXCRLUtil.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/PKIXCRLUtil.java deleted file mode 100644 index 3e22d9f6c..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/PKIXCRLUtil.java +++ /dev/null @@ -1,155 +0,0 @@ -package org.spongycastle.jce.provider; - -import org.spongycastle.jce.cert.CertStore; -import org.spongycastle.jce.cert.CertStoreException; -import org.spongycastle.jce.cert.PKIXParameters; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.util.Collection; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.spongycastle.util.StoreException; -import org.spongycastle.x509.ExtendedPKIXParameters; -import org.spongycastle.x509.X509CRLStoreSelector; -import org.spongycastle.x509.X509Store; - -public class PKIXCRLUtil -{ - public Set findCRLs(X509CRLStoreSelector crlselect, ExtendedPKIXParameters paramsPKIX, Date currentDate) - throws AnnotatedException - { - Set initialSet = new HashSet(); - - // get complete CRL(s) - try - { - initialSet.addAll(findCRLs(crlselect, paramsPKIX.getAdditionalStores())); - initialSet.addAll(findCRLs(crlselect, paramsPKIX.getStores())); - initialSet.addAll(findCRLs(crlselect, paramsPKIX.getCertStores())); - } - catch (AnnotatedException e) - { - throw new AnnotatedException("Exception obtaining complete CRLs.", e); - } - - Set finalSet = new HashSet(); - Date validityDate = currentDate; - - if (paramsPKIX.getDate() != null) - { - validityDate = paramsPKIX.getDate(); - } - - // based on RFC 5280 6.3.3 - for (Iterator it = initialSet.iterator(); it.hasNext();) - { - X509CRL crl = (X509CRL)it.next(); - - if (crl.getNextUpdate().after(validityDate)) - { - X509Certificate cert = crlselect.getCertificateChecking(); - - if (cert != null) - { - if (crl.getThisUpdate().before(cert.getNotAfter())) - { - finalSet.add(crl); - } - } - else - { - finalSet.add(crl); - } - } - } - - return finalSet; - } - - public Set findCRLs(X509CRLStoreSelector crlselect, PKIXParameters paramsPKIX) - throws AnnotatedException - { - Set completeSet = new HashSet(); - - // get complete CRL(s) - try - { - completeSet.addAll(findCRLs(crlselect, paramsPKIX.getCertStores())); - } - catch (AnnotatedException e) - { - throw new AnnotatedException("Exception obtaining complete CRLs.", e); - } - - return completeSet; - } - -/** - * Return a Collection of all CRLs found in the X509Store's that are - * matching the crlSelect criteriums. - * - * @param crlSelect a {@link X509CRLStoreSelector} object that will be used - * to select the CRLs - * @param crlStores a List containing only - * {@link org.spongycastle.x509.X509Store X509Store} objects. - * These are used to search for CRLs - * - * @return a Collection of all found {@link java.security.cert.X509CRL X509CRL} objects. May be - * empty but never null. - */ - private final Collection findCRLs(X509CRLStoreSelector crlSelect, - List crlStores) throws AnnotatedException - { - Set crls = new HashSet(); - Iterator iter = crlStores.iterator(); - - AnnotatedException lastException = null; - boolean foundValidStore = false; - - while (iter.hasNext()) - { - Object obj = iter.next(); - - if (obj instanceof X509Store) - { - X509Store store = (X509Store)obj; - - try - { - crls.addAll(store.getMatches(crlSelect)); - foundValidStore = true; - } - catch (StoreException e) - { - lastException = new AnnotatedException( - "Exception searching in X.509 CRL store.", e); - } - } - else - { - CertStore store = (CertStore)obj; - - try - { - crls.addAll(store.getCRLs(crlSelect)); - foundValidStore = true; - } - catch (CertStoreException e) - { - lastException = new AnnotatedException( - "Exception searching in X.509 CRL store.", e); - } - } - } - if (!foundValidStore && lastException != null) - { - throw lastException; - } - return crls; - } - -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/PKIXCertPathBuilderSpi.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/PKIXCertPathBuilderSpi.java deleted file mode 100644 index d02dd511f..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/PKIXCertPathBuilderSpi.java +++ /dev/null @@ -1,395 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.io.IOException; -import java.security.InvalidAlgorithmParameterException; -import java.security.PublicKey; -import org.spongycastle.jce.cert.CertPath; -import org.spongycastle.jce.cert.CertPathBuilderException; -import org.spongycastle.jce.cert.CertPathBuilderResult; -import org.spongycastle.jce.cert.CertPathBuilderSpi; -import org.spongycastle.jce.cert.CertPathParameters; -import org.spongycastle.jce.cert.CertPathValidator; -import org.spongycastle.jce.cert.CertPathValidatorException; -import org.spongycastle.jce.cert.CertSelector; -import org.spongycastle.jce.cert.CertStore; -import org.spongycastle.jce.cert.CertStoreException; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import org.spongycastle.jce.cert.CertificateFactory; -import org.spongycastle.jce.cert.PKIXBuilderParameters; -import org.spongycastle.jce.cert.PKIXBuilderParameters; -import org.spongycastle.jce.cert.PKIXCertPathBuilderResult; -import org.spongycastle.jce.cert.PKIXCertPathValidatorResult; -import org.spongycastle.jce.cert.TrustAnchor; -import org.spongycastle.jce.cert.X509CertSelector; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.spongycastle.jce.X509Principal; -import org.spongycastle.x509.ExtendedPKIXBuilderParameters; -import org.spongycastle.jce.PrincipalUtil; - -/** - * Implements the PKIX CertPathBuilding algorithem for BouncyCastle. - *
- * MAYBE: implement more CertPath validation whil build path to omit invalid pathes - * - * @see CertPathBuilderSpi - **/ -public class PKIXCertPathBuilderSpi - extends CertPathBuilderSpi -{ - /** - * Build and validate a CertPath using the given parameter. - * - * @param params PKIXBuilderParameters object containing all - * information to build the CertPath - **/ - public CertPathBuilderResult engineBuild( - CertPathParameters params) - throws CertPathBuilderException, InvalidAlgorithmParameterException - { - if (!(params instanceof PKIXBuilderParameters) - && !(params instanceof ExtendedPKIXBuilderParameters)) - { - throw new InvalidAlgorithmParameterException( - "Parameters must be an instance of " - + PKIXBuilderParameters.class.getName() + " or " - + ExtendedPKIXBuilderParameters.class.getName() + "."); - } - - ExtendedPKIXBuilderParameters pkixParams = null; - if (params instanceof ExtendedPKIXBuilderParameters) - { - pkixParams = (ExtendedPKIXBuilderParameters) params; - } - else - { - pkixParams = (ExtendedPKIXBuilderParameters) ExtendedPKIXBuilderParameters - .getInstance((PKIXBuilderParameters) params); - } - - Collection targets; - Iterator targetIter; - List certPathList = new ArrayList(); - Set certPathSet = new HashSet(); - X509Certificate cert; - Collection certs; - CertPath certPath = null; - Exception certPathException = null; - - // search target certificates - CertSelector certSelect = pkixParams.getTargetCertConstraints(); - if (certSelect == null) - { - throw new CertPathBuilderException("targetCertConstraints must be non-null for CertPath building"); - } - - try - { - targets = findCertificates(certSelect, pkixParams.getCertStores()); - } - catch (CertStoreException e) - { - throw new CertPathBuilderException(e); - } - - if (targets.isEmpty()) - { - throw new CertPathBuilderException("no certificate found matching targetCertContraints"); - } - - CertificateFactory cFact; - CertPathValidator validator; - - try - { - cFact = CertificateFactory.getInstance("X.509", "SC"); - validator = CertPathValidator.getInstance("PKIX", "SC"); - } - catch (Exception e) - { - throw new CertPathBuilderException("exception creating support classes: " + e); - } - - // - // check all potential target certificates - targetIter = targets.iterator(); - while (targetIter.hasNext()) - { - cert = (X509Certificate)targetIter.next(); - certPathList.clear(); - certPathSet.clear(); - while (cert != null) - { - // add cert to the certpath - certPathList.add(cert); - certPathSet.add(cert); - - // check whether the issuer of is a TrustAnchor - if (findTrustAnchor(cert, pkixParams.getTrustAnchors()) != null) - { - try - { - certPath = cFact.generateCertPath(certPathList); - - PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult)validator.validate(certPath, pkixParams); - - return new PKIXCertPathBuilderResult(certPath, - result.getTrustAnchor(), - result.getPolicyTree(), - result.getPublicKey()); - } - catch (CertificateException ex) - { - certPathException = ex; - } - catch (CertPathValidatorException ex) - { - certPathException = ex; - } - // if validation failed go to next certificate - cert = null; - } - else - { - // try to get the issuer certificate from one - // of the CertStores - try - { - X509Certificate issuer = findIssuer(cert, pkixParams.getCertStores()); - if (issuer.equals(cert)) - { - cert = null; - } - else - { - cert = issuer; - // validation failed - circular path detected, go to next certificate - if (certPathSet.contains(cert)) - { - cert = null; - } - } - } - catch (CertPathValidatorException ex) - { - certPathException = ex; - cert = null; - } - } - } - } - - if (certPath != null) - { - throw new CertPathBuilderException("found certificate chain, but could not be validated", certPathException); - } - - throw new CertPathBuilderException("unable to find certificate chain"); - } - - /** - * Search the given Set of TrustAnchor's for one that is the - * issuer of the fiven X509 certificate. - * - * @param cert the X509 certificate - * @param trustAnchors a Set of TrustAnchor's - * - * @return the TrustAnchor object if found or - * null if not. - * - * @exception CertPathValidatorException if a TrustAnchor was - * found but the signature verificytion on the given certificate - * has thrown an exception. This Exception can be obtainted with - * getCause() method. - **/ - final TrustAnchor findTrustAnchor( - X509Certificate cert, - Set trustAnchors) - throws CertPathBuilderException - { - Iterator iter = trustAnchors.iterator(); - TrustAnchor trust = null; - PublicKey trustPublicKey = null; - Exception invalidKeyEx = null; - - X509CertSelector certSelectX509 = new X509CertSelector(); - - try - { - certSelectX509.setSubject(PrincipalUtil.getIssuerX509Principal(cert).getEncoded()); - } - catch (Exception ex) - { - throw new CertPathBuilderException("can't get trust anchor principal",null); - } - - while (iter.hasNext() && trust == null) - { - trust = (TrustAnchor)iter.next(); - if (trust.getTrustedCert() != null) - { - if (certSelectX509.match(trust.getTrustedCert())) - { - trustPublicKey = trust.getTrustedCert().getPublicKey(); - } - else - { - trust = null; - } - } - else if (trust.getCAName() != null - && trust.getCAPublicKey() != null) - { - try - { - X509Principal certIssuer = PrincipalUtil.getIssuerX509Principal(cert); - X509Principal caName = new X509Principal(trust.getCAName()); - if (certIssuer.equals(caName)) - { - trustPublicKey = trust.getCAPublicKey(); - } - else - { - trust = null; - } - } - catch (Exception ex) - { - trust = null; - } - } - else - { - trust = null; - } - - if (trustPublicKey != null) - { - try - { - cert.verify(trustPublicKey); - } - catch (Exception ex) - { - invalidKeyEx = ex; - trust = null; - } - } - } - - if (trust == null && invalidKeyEx != null) - { - throw new CertPathBuilderException("TrustAnchor found put certificate validation failed",invalidKeyEx); - } - - return trust; - } - - /** - * Return a Collection of all certificates found in the - * CertStore's that are matching the certSelect criteriums. - * - * @param certSelect a {@link CertSelector CertSelector} - * object that will be used to select the certificates - * @param certStores a List containing only {@link CertStore - * CertStore} objects. These are used to search for - * certificates - * - * @return a Collection of all found {@link Certificate Certificate} - * objects. May be empty but never null. - **/ - private Collection findCertificates( - CertSelector certSelect, - List certStores) - throws CertStoreException - { - Set certs = new HashSet(); - Iterator iter = certStores.iterator(); - - while (iter.hasNext()) - { - CertStore certStore = (CertStore)iter.next(); - - certs.addAll(certStore.getCertificates(certSelect)); - } - - return certs; - } - - /** - * Find the issuer certificate of the given certificate. - * - * @param cert the certificate hows issuer certificate should - * be found. - * @param certStores a list of CertStore object - * that will be searched - * - * @return then X509Certificate object containing - * the issuer certificate or null if not found - * - * @exception CertPathValidatorException if a TrustAnchor was - * found but the signature verificytion on the given certificate - * has thrown an exception. This Exception can be obtainted with - * getCause() method. - **/ - private X509Certificate findIssuer( - X509Certificate cert, - List certStores) - throws CertPathValidatorException - { - Exception invalidKeyEx = null; - X509CertSelector certSelect = new X509CertSelector(); - try - { - certSelect.setSubject(PrincipalUtil.getIssuerX509Principal(cert).getEncoded()); - } - catch (Exception ex) - { - throw new CertPathValidatorException("Issuer not found", null, null, -1); - } - - Iterator iter; - try - { - iter = findCertificates(certSelect, certStores).iterator(); - } - catch (CertStoreException e) - { - throw new CertPathValidatorException(e); - } - - X509Certificate issuer = null; - while (iter.hasNext() && issuer == null) - { - issuer = (X509Certificate)iter.next(); - try - { - cert.verify(issuer.getPublicKey()); - } - catch (Exception ex) - { - invalidKeyEx = ex; - issuer = null; - } - } - - if (issuer == null && invalidKeyEx == null) - { - throw new CertPathValidatorException("Issuer not found", null, null, -1); - } - - if (issuer == null && invalidKeyEx != null) - { - throw new CertPathValidatorException("issuer found but certificate validation failed",invalidKeyEx,null,-1); - } - - return issuer; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/PKIXCertPathValidatorSpi.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/PKIXCertPathValidatorSpi.java deleted file mode 100644 index 989d9c9a6..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/PKIXCertPathValidatorSpi.java +++ /dev/null @@ -1,431 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.security.InvalidAlgorithmParameterException; -import java.security.PublicKey; -import org.spongycastle.jce.cert.CertPath; -import org.spongycastle.jce.cert.CertPathParameters; -import org.spongycastle.jce.cert.CertPathValidatorException; -import org.spongycastle.jce.cert.CertPathValidatorResult; -import org.spongycastle.jce.cert.CertPathValidatorSpi; -import org.spongycastle.jce.cert.PKIXCertPathChecker; -import org.spongycastle.jce.cert.PKIXCertPathValidatorResult; -import org.spongycastle.jce.cert.PKIXParameters; -import org.spongycastle.jce.cert.TrustAnchor; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.spongycastle.jce.X509Principal; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.jce.exception.ExtCertPathValidatorException; -import org.spongycastle.x509.ExtendedPKIXParameters; - -/** - * CertPathValidatorSpi implementation for X.509 Certificate validation � la RFC - * 3280. - */ -public class PKIXCertPathValidatorSpi - extends CertPathValidatorSpi -{ - - public CertPathValidatorResult engineValidate( - CertPath certPath, - CertPathParameters params) - throws CertPathValidatorException, - InvalidAlgorithmParameterException - { - if (!(params instanceof PKIXParameters)) - { - throw new InvalidAlgorithmParameterException("Parameters must be a " + PKIXParameters.class.getName() - + " instance."); - } - - ExtendedPKIXParameters paramsPKIX; - if (params instanceof ExtendedPKIXParameters) - { - paramsPKIX = (ExtendedPKIXParameters)params; - } - else - { - paramsPKIX = ExtendedPKIXParameters.getInstance((PKIXParameters)params); - } - if (paramsPKIX.getTrustAnchors() == null) - { - throw new InvalidAlgorithmParameterException( - "trustAnchors is null, this is not allowed for certification path validation."); - } - - // - // 6.1.1 - inputs - // - - // - // (a) - // - List certs = certPath.getCertificates(); - int n = certs.size(); - - if (certs.isEmpty()) - { - throw new CertPathValidatorException("Certification path is empty.", null, certPath, 0); - } - - // - // (b) - // - // Date validDate = CertPathValidatorUtilities.getValidDate(paramsPKIX); - - // - // (c) - // - Set userInitialPolicySet = paramsPKIX.getInitialPolicies(); - - // - // (d) - // - TrustAnchor trust; - try - { - trust = CertPathValidatorUtilities.findTrustAnchor((X509Certificate) certs.get(certs.size() - 1), - paramsPKIX.getTrustAnchors(), paramsPKIX.getSigProvider()); - } - catch (AnnotatedException e) - { - throw new CertPathValidatorException(e.getMessage(), e, certPath, certs.size() - 1); - } - - if (trust == null) - { - throw new CertPathValidatorException("Trust anchor for certification path not found.", null, certPath, -1); - } - - // - // (e), (f), (g) are part of the paramsPKIX object. - // - Iterator certIter; - int index = 0; - int i; - // Certificate for each interation of the validation loop - // Signature information for each iteration of the validation loop - // - // 6.1.2 - setup - // - - // - // (a) - // - List[] policyNodes = new ArrayList[n + 1]; - for (int j = 0; j < policyNodes.length; j++) - { - policyNodes[j] = new ArrayList(); - } - - Set policySet = new HashSet(); - - policySet.add(RFC3280CertPathUtilities.ANY_POLICY); - - PKIXPolicyNode validPolicyTree = new PKIXPolicyNode(new ArrayList(), 0, policySet, null, new HashSet(), - RFC3280CertPathUtilities.ANY_POLICY, false); - - policyNodes[0].add(validPolicyTree); - - // - // (b) and (c) - // - PKIXNameConstraintValidator nameConstraintValidator = new PKIXNameConstraintValidator(); - - // (d) - // - int explicitPolicy; - Set acceptablePolicies = new HashSet(); - - if (paramsPKIX.isExplicitPolicyRequired()) - { - explicitPolicy = 0; - } - else - { - explicitPolicy = n + 1; - } - - // - // (e) - // - int inhibitAnyPolicy; - - if (paramsPKIX.isAnyPolicyInhibited()) - { - inhibitAnyPolicy = 0; - } - else - { - inhibitAnyPolicy = n + 1; - } - - // - // (f) - // - int policyMapping; - - if (paramsPKIX.isPolicyMappingInhibited()) - { - policyMapping = 0; - } - else - { - policyMapping = n + 1; - } - - // - // (g), (h), (i), (j) - // - PublicKey workingPublicKey; - X509Principal workingIssuerName; - - X509Certificate sign = trust.getTrustedCert(); - try - { - if (sign != null) - { - workingIssuerName = CertPathValidatorUtilities.getSubjectPrincipal(sign); - workingPublicKey = sign.getPublicKey(); - } - else - { - workingIssuerName = new X509Principal(trust.getCAName()); - workingPublicKey = trust.getCAPublicKey(); - } - } - catch (IllegalArgumentException ex) - { - throw new ExtCertPathValidatorException("Subject of trust anchor could not be (re)encoded.", ex, certPath, - -1); - } - - AlgorithmIdentifier workingAlgId = null; - try - { - workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey); - } - catch (CertPathValidatorException e) - { - throw new ExtCertPathValidatorException( - "Algorithm identifier of public key of trust anchor could not be read.", e, certPath, -1); - } - ASN1ObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.getObjectId(); - ASN1Encodable workingPublicKeyParameters = workingAlgId.getParameters(); - - // - // (k) - // - int maxPathLength = n; - - // - // 6.1.3 - // - - if (paramsPKIX.getTargetConstraints() != null - && !paramsPKIX.getTargetConstraints().match((X509Certificate) certs.get(0))) - { - throw new ExtCertPathValidatorException( - "Target certificate in certification path does not match targetConstraints.", null, certPath, 0); - } - - // - // initialize CertPathChecker's - // - List pathCheckers = paramsPKIX.getCertPathCheckers(); - certIter = pathCheckers.iterator(); - while (certIter.hasNext()) - { - ((PKIXCertPathChecker) certIter.next()).init(false); - } - - X509Certificate cert = null; - - for (index = certs.size() - 1; index >= 0; index--) - { - // try - // { - // - // i as defined in the algorithm description - // - i = n - index; - - // - // set certificate to be checked in this round - // sign and workingPublicKey and workingIssuerName are set - // at the end of the for loop and initialized the - // first time from the TrustAnchor - // - cert = (X509Certificate) certs.get(index); - boolean verificationAlreadyPerformed = (index == certs.size() - 1); - - // - // 6.1.3 - // - - RFC3280CertPathUtilities.processCertA(certPath, paramsPKIX, index, workingPublicKey, - verificationAlreadyPerformed, workingIssuerName, sign); - - RFC3280CertPathUtilities.processCertBC(certPath, index, nameConstraintValidator); - - validPolicyTree = RFC3280CertPathUtilities.processCertD(certPath, index, acceptablePolicies, - validPolicyTree, policyNodes, inhibitAnyPolicy); - - validPolicyTree = RFC3280CertPathUtilities.processCertE(certPath, index, validPolicyTree); - - RFC3280CertPathUtilities.processCertF(certPath, index, validPolicyTree, explicitPolicy); - - // - // 6.1.4 - // - - if (i != n) - { - if (cert != null && cert.getVersion() == 1) - { - throw new CertPathValidatorException("Version 1 certificates can't be used as CA ones.", null, - certPath, index); - } - - RFC3280CertPathUtilities.prepareNextCertA(certPath, index); - - validPolicyTree = RFC3280CertPathUtilities.prepareCertB(certPath, index, policyNodes, validPolicyTree, - policyMapping); - - RFC3280CertPathUtilities.prepareNextCertG(certPath, index, nameConstraintValidator); - - // (h) - explicitPolicy = RFC3280CertPathUtilities.prepareNextCertH1(certPath, index, explicitPolicy); - policyMapping = RFC3280CertPathUtilities.prepareNextCertH2(certPath, index, policyMapping); - inhibitAnyPolicy = RFC3280CertPathUtilities.prepareNextCertH3(certPath, index, inhibitAnyPolicy); - - // - // (i) - // - explicitPolicy = RFC3280CertPathUtilities.prepareNextCertI1(certPath, index, explicitPolicy); - policyMapping = RFC3280CertPathUtilities.prepareNextCertI2(certPath, index, policyMapping); - - // (j) - inhibitAnyPolicy = RFC3280CertPathUtilities.prepareNextCertJ(certPath, index, inhibitAnyPolicy); - - // (k) - RFC3280CertPathUtilities.prepareNextCertK(certPath, index); - - // (l) - maxPathLength = RFC3280CertPathUtilities.prepareNextCertL(certPath, index, maxPathLength); - - // (m) - maxPathLength = RFC3280CertPathUtilities.prepareNextCertM(certPath, index, maxPathLength); - - // (n) - RFC3280CertPathUtilities.prepareNextCertN(certPath, index); - - Set criticalExtensions = cert.getCriticalExtensionOIDs(); - if (criticalExtensions != null) - { - criticalExtensions = new HashSet(criticalExtensions); - - // these extensions are handled by the algorithm - criticalExtensions.remove(RFC3280CertPathUtilities.KEY_USAGE); - criticalExtensions.remove(RFC3280CertPathUtilities.CERTIFICATE_POLICIES); - criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_MAPPINGS); - criticalExtensions.remove(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY); - criticalExtensions.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT); - criticalExtensions.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR); - criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_CONSTRAINTS); - criticalExtensions.remove(RFC3280CertPathUtilities.BASIC_CONSTRAINTS); - criticalExtensions.remove(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME); - criticalExtensions.remove(RFC3280CertPathUtilities.NAME_CONSTRAINTS); - } - else - { - criticalExtensions = new HashSet(); - } - - // (o) - RFC3280CertPathUtilities.prepareNextCertO(certPath, index, criticalExtensions, pathCheckers); - - // set signing certificate for next round - sign = cert; - - // (c) - workingIssuerName = CertPathValidatorUtilities.getSubjectPrincipal(sign); - - // (d) - try - { - workingPublicKey = CertPathValidatorUtilities.getNextWorkingKey(certPath.getCertificates(), index); - } - catch (CertPathValidatorException e) - { - throw new CertPathValidatorException("Next working key could not be retrieved.", e, certPath, index); - } - - workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey); - // (f) - workingPublicKeyAlgorithm = workingAlgId.getObjectId(); - // (e) - workingPublicKeyParameters = workingAlgId.getParameters(); - } - } - - // - // 6.1.5 Wrap-up procedure - // - - explicitPolicy = RFC3280CertPathUtilities.wrapupCertA(explicitPolicy, cert); - - explicitPolicy = RFC3280CertPathUtilities.wrapupCertB(certPath, index + 1, explicitPolicy); - - // - // (c) (d) and (e) are already done - // - - // - // (f) - // - Set criticalExtensions = cert.getCriticalExtensionOIDs(); - - if (criticalExtensions != null) - { - criticalExtensions = new HashSet(criticalExtensions); - // these extensions are handled by the algorithm - criticalExtensions.remove(RFC3280CertPathUtilities.KEY_USAGE); - criticalExtensions.remove(RFC3280CertPathUtilities.CERTIFICATE_POLICIES); - criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_MAPPINGS); - criticalExtensions.remove(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY); - criticalExtensions.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT); - criticalExtensions.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR); - criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_CONSTRAINTS); - criticalExtensions.remove(RFC3280CertPathUtilities.BASIC_CONSTRAINTS); - criticalExtensions.remove(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME); - criticalExtensions.remove(RFC3280CertPathUtilities.NAME_CONSTRAINTS); - criticalExtensions.remove(RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS); - } - else - { - criticalExtensions = new HashSet(); - } - - RFC3280CertPathUtilities.wrapupCertF(certPath, index + 1, pathCheckers, criticalExtensions); - - PKIXPolicyNode intersection = RFC3280CertPathUtilities.wrapupCertG(certPath, paramsPKIX, userInitialPolicySet, - index + 1, policyNodes, validPolicyTree, acceptablePolicies); - - if ((explicitPolicy > 0) || (intersection != null)) - { - return new PKIXCertPathValidatorResult(trust, intersection, cert.getPublicKey()); - } - - throw new CertPathValidatorException("Path processing failed on policy.", null, certPath, index); - } - -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/PKIXPolicyNode.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/PKIXPolicyNode.java deleted file mode 100644 index 1a0b4e7b1..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/PKIXPolicyNode.java +++ /dev/null @@ -1,169 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.spongycastle.jce.cert.PolicyNode; - -public class PKIXPolicyNode - implements PolicyNode -{ - protected List children; - protected int depth; - protected Set expectedPolicies; - protected PolicyNode parent; - protected Set policyQualifiers; - protected String validPolicy; - protected boolean critical; - - /* - * - * CONSTRUCTORS - * - */ - - public PKIXPolicyNode( - List _children, - int _depth, - Set _expectedPolicies, - PolicyNode _parent, - Set _policyQualifiers, - String _validPolicy, - boolean _critical) - { - children = _children; - depth = _depth; - expectedPolicies = _expectedPolicies; - parent = _parent; - policyQualifiers = _policyQualifiers; - validPolicy = _validPolicy; - critical = _critical; - } - - public void addChild( - PKIXPolicyNode _child) - { - children.add(_child); - _child.setParent(this); - } - - public Iterator getChildren() - { - return children.iterator(); - } - - public int getDepth() - { - return depth; - } - - public Set getExpectedPolicies() - { - return expectedPolicies; - } - - public PolicyNode getParent() - { - return parent; - } - - public Set getPolicyQualifiers() - { - return policyQualifiers; - } - - public String getValidPolicy() - { - return validPolicy; - } - - public boolean hasChildren() - { - return !children.isEmpty(); - } - - public boolean isCritical() - { - return critical; - } - - public void removeChild(PKIXPolicyNode _child) - { - children.remove(_child); - } - - public void setCritical(boolean _critical) - { - critical = _critical; - } - - public void setParent(PKIXPolicyNode _parent) - { - parent = _parent; - } - - public String toString() - { - return toString(""); - } - - public String toString(String _indent) - { - StringBuffer _buf = new StringBuffer(); - _buf.append(_indent); - _buf.append(validPolicy); - _buf.append(" {\n"); - - for(int i = 0; i < children.size(); i++) - { - _buf.append(((PKIXPolicyNode)children.get(i)).toString(_indent + " ")); - } - - _buf.append(_indent); - _buf.append("}\n"); - return _buf.toString(); - } - - public Object clone() - { - return copy(); - } - - public PKIXPolicyNode copy() - { - Set _expectedPolicies = new HashSet(); - Iterator _iter = expectedPolicies.iterator(); - while (_iter.hasNext()) - { - _expectedPolicies.add(new String((String)_iter.next())); - } - - Set _policyQualifiers = new HashSet(); - _iter = policyQualifiers.iterator(); - while (_iter.hasNext()) - { - _policyQualifiers.add(new String((String)_iter.next())); - } - - PKIXPolicyNode _node = new PKIXPolicyNode(new ArrayList(), - depth, - _expectedPolicies, - null, - _policyQualifiers, - new String(validPolicy), - critical); - - _iter = children.iterator(); - while (_iter.hasNext()) - { - PKIXPolicyNode _child = ((PKIXPolicyNode)_iter.next()).copy(); - _child.setParent(_node); - _node.addChild(_child); - } - - return _node; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/ProviderUtil.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/ProviderUtil.java deleted file mode 100644 index 74efc9a99..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/ProviderUtil.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.Permission; - -import org.spongycastle.jcajce.provider.config.ConfigurableProvider; -import org.spongycastle.jcajce.provider.config.ProviderConfigurationPermission; -import org.spongycastle.jce.spec.ECParameterSpec; - -public class ProviderUtil -{ - private static Permission BC_EC_LOCAL_PERMISSION = new ProviderConfigurationPermission( - "SC", ConfigurableProvider.THREAD_LOCAL_EC_IMPLICITLY_CA); - private static Permission BC_EC_PERMISSION = new ProviderConfigurationPermission( - "SC", ConfigurableProvider.EC_IMPLICITLY_CA); - - private static ThreadLocal threadSpec = new ThreadLocal(); - private static volatile ECParameterSpec ecImplicitCaParams; - - static void setParameter(String parameterName, Object parameter) - { - SecurityManager securityManager = System.getSecurityManager(); - - if (parameterName.equals(ConfigurableProvider.THREAD_LOCAL_EC_IMPLICITLY_CA)) - { - ECParameterSpec curveSpec; - - if (securityManager != null) - { - securityManager.checkPermission(BC_EC_LOCAL_PERMISSION); - } - - curveSpec = (ECParameterSpec)parameter; - - threadSpec.set(curveSpec); - } - else if (parameterName.equals(ConfigurableProvider.EC_IMPLICITLY_CA)) - { - if (securityManager != null) - { - securityManager.checkPermission(BC_EC_PERMISSION); - } - - ecImplicitCaParams = (ECParameterSpec)parameter; - } - } - - public static ECParameterSpec getEcImplicitlyCa() - { - ECParameterSpec spec = (ECParameterSpec)threadSpec.get(); - - if (spec != null) - { - return spec; - } - - return ecImplicitCaParams; - } - - static int getReadLimit(InputStream in) - throws IOException - { - if (in instanceof ByteArrayInputStream) - { - return in.available(); - } - - return Integer.MAX_VALUE; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/RFC3280CertPathUtilities.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/RFC3280CertPathUtilities.java deleted file mode 100644 index 3f37d4c96..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/RFC3280CertPathUtilities.java +++ /dev/null @@ -1,2582 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.PublicKey; -import java.text.SimpleDateFormat; -import org.spongycastle.jce.cert.CertPath; -import org.spongycastle.jce.cert.CertPathBuilder; -import org.spongycastle.jce.cert.CertPathBuilderException; -import org.spongycastle.jce.cert.CertPathValidatorException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; -import org.spongycastle.jce.cert.PKIXCertPathChecker; -import java.security.cert.CRLException; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.security.cert.X509Extension; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TimeZone; -import java.util.Vector; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1TaggedObject; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.x509.BasicConstraints; -import org.spongycastle.asn1.x509.CRLDistPoint; -import org.spongycastle.asn1.x509.CRLReason; -import org.spongycastle.asn1.x509.DistributionPoint; -import org.spongycastle.asn1.x509.DistributionPointName; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.GeneralNames; -import org.spongycastle.asn1.x509.GeneralSubtree; -import org.spongycastle.asn1.x509.IssuingDistributionPoint; -import org.spongycastle.asn1.x509.NameConstraints; -import org.spongycastle.asn1.x509.PolicyInformation; -import org.spongycastle.asn1.x509.X509Extensions; -import org.spongycastle.asn1.x509.X509Name; -import org.spongycastle.jce.exception.ExtCertPathValidatorException; -import org.spongycastle.jce.X509Principal; -import org.spongycastle.jce.PrincipalUtil; -import org.spongycastle.util.Arrays; -import org.spongycastle.x509.ExtendedPKIXBuilderParameters; -import org.spongycastle.x509.ExtendedPKIXParameters; -import org.spongycastle.x509.X509CRLStoreSelector; -import org.spongycastle.x509.X509CertStoreSelector; - -public class RFC3280CertPathUtilities -{ - private static final PKIXCRLUtil CRL_UTIL = new PKIXCRLUtil(); - - /** - * If the complete CRL includes an issuing distribution point (IDP) CRL - * extension check the following: - *

- * (i) If the distribution point name is present in the IDP CRL extension - * and the distribution field is present in the DP, then verify that one of - * the names in the IDP matches one of the names in the DP. If the - * distribution point name is present in the IDP CRL extension and the - * distribution field is omitted from the DP, then verify that one of the - * names in the IDP matches one of the names in the cRLIssuer field of the - * DP. - *

- *

- * (ii) If the onlyContainsUserCerts boolean is asserted in the IDP CRL - * extension, verify that the certificate does not include the basic - * constraints extension with the cA boolean asserted. - *

- *

- * (iii) If the onlyContainsCACerts boolean is asserted in the IDP CRL - * extension, verify that the certificate includes the basic constraints - * extension with the cA boolean asserted. - *

- *

- * (iv) Verify that the onlyContainsAttributeCerts boolean is not asserted. - *

- * - * @param dp The distribution point. - * @param cert The certificate. - * @param crl The CRL. - * @throws AnnotatedException if one of the conditions is not met or an error occurs. - */ - protected static void processCRLB2( - DistributionPoint dp, - Object cert, - X509CRL crl) - throws AnnotatedException - { - IssuingDistributionPoint idp = null; - try - { - idp = IssuingDistributionPoint.getInstance(CertPathValidatorUtilities.getExtensionValue(crl, - RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT)); - } - catch (Exception e) - { - throw new AnnotatedException("Issuing distribution point extension could not be decoded.", e); - } - // (b) (2) (i) - // distribution point name is present - if (idp != null) - { - if (idp.getDistributionPoint() != null) - { - // make list of names - DistributionPointName dpName = IssuingDistributionPoint.getInstance(idp).getDistributionPoint(); - List names = new ArrayList(); - - if (dpName.getType() == DistributionPointName.FULL_NAME) - { - GeneralName[] genNames = GeneralNames.getInstance(dpName.getName()).getNames(); - for (int j = 0; j < genNames.length; j++) - { - names.add(genNames[j]); - } - } - if (dpName.getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER) - { - ASN1EncodableVector vec = new ASN1EncodableVector(); - try - { - Enumeration e = ASN1Sequence.getInstance( - ASN1Sequence.fromByteArray(CertPathValidatorUtilities.getIssuerPrincipal(crl) - .getEncoded())).getObjects(); - while (e.hasMoreElements()) - { - vec.add((ASN1Encodable)e.nextElement()); - } - } - catch (IOException e) - { - throw new AnnotatedException("Could not read CRL issuer.", e); - } - vec.add(dpName.getName()); - names.add(new GeneralName(X509Name.getInstance(new DERSequence(vec)))); - } - boolean matches = false; - // verify that one of the names in the IDP matches one - // of the names in the DP. - if (dp.getDistributionPoint() != null) - { - dpName = dp.getDistributionPoint(); - GeneralName[] genNames = null; - if (dpName.getType() == DistributionPointName.FULL_NAME) - { - genNames = GeneralNames.getInstance(dpName.getName()).getNames(); - } - if (dpName.getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER) - { - if (dp.getCRLIssuer() != null) - { - genNames = dp.getCRLIssuer().getNames(); - } - else - { - genNames = new GeneralName[1]; - try - { - genNames[0] = new GeneralName(new X509Name( - (ASN1Sequence)ASN1Sequence.fromByteArray(CertPathValidatorUtilities - .getEncodedIssuerPrincipal(cert).getEncoded()))); - } - catch (IOException e) - { - throw new AnnotatedException("Could not read certificate issuer.", e); - } - } - for (int j = 0; j < genNames.length; j++) - { - Enumeration e = ASN1Sequence.getInstance(genNames[j].getName().toASN1Primitive()).getObjects(); - ASN1EncodableVector vec = new ASN1EncodableVector(); - while (e.hasMoreElements()) - { - vec.add((ASN1Encodable)e.nextElement()); - } - vec.add(dpName.getName()); - genNames[j] = new GeneralName(new X509Name(new DERSequence(vec))); - } - } - if (genNames != null) - { - for (int j = 0; j < genNames.length; j++) - { - if (names.contains(genNames[j])) - { - matches = true; - break; - } - } - } - if (!matches) - { - throw new AnnotatedException( - "No match for certificate CRL issuing distribution point name to cRLIssuer CRL distribution point."); - } - } - // verify that one of the names in - // the IDP matches one of the names in the cRLIssuer field of - // the DP - else - { - if (dp.getCRLIssuer() == null) - { - throw new AnnotatedException("Either the cRLIssuer or the distributionPoint field must " - + "be contained in DistributionPoint."); - } - GeneralName[] genNames = dp.getCRLIssuer().getNames(); - for (int j = 0; j < genNames.length; j++) - { - if (names.contains(genNames[j])) - { - matches = true; - break; - } - } - if (!matches) - { - throw new AnnotatedException( - "No match for certificate CRL issuing distribution point name to cRLIssuer CRL distribution point."); - } - } - } - BasicConstraints bc = null; - try - { - bc = BasicConstraints.getInstance(CertPathValidatorUtilities.getExtensionValue((X509Extension)cert, - BASIC_CONSTRAINTS)); - } - catch (Exception e) - { - throw new AnnotatedException("Basic constraints extension could not be decoded.", e); - } - - if (cert instanceof X509Certificate) - { - // (b) (2) (ii) - if (idp.onlyContainsUserCerts() && (bc != null && bc.isCA())) - { - throw new AnnotatedException("CA Cert CRL only contains user certificates."); - } - - // (b) (2) (iii) - if (idp.onlyContainsCACerts() && (bc == null || !bc.isCA())) - { - throw new AnnotatedException("End CRL only contains CA certificates."); - } - } - - // (b) (2) (iv) - if (idp.onlyContainsAttributeCerts()) - { - throw new AnnotatedException("onlyContainsAttributeCerts boolean is asserted."); - } - } - } - - /** - * If the DP includes cRLIssuer, then verify that the issuer field in the - * complete CRL matches cRLIssuer in the DP and that the complete CRL - * contains an issuing distribution point extension with the indirectCRL - * boolean asserted. Otherwise, verify that the CRL issuer matches the - * certificate issuer. - * - * @param dp The distribution point. - * @param cert The certificate ot attribute certificate. - * @param crl The CRL for cert. - * @throws AnnotatedException if one of the above conditions does not apply or an error - * occurs. - */ - protected static void processCRLB1( - DistributionPoint dp, - Object cert, - X509CRL crl) - throws AnnotatedException - { - ASN1Primitive idp = CertPathValidatorUtilities.getExtensionValue(crl, ISSUING_DISTRIBUTION_POINT); - boolean isIndirect = false; - if (idp != null) - { - if (IssuingDistributionPoint.getInstance(idp).isIndirectCRL()) - { - isIndirect = true; - } - } - byte[] issuerBytes = CertPathValidatorUtilities.getIssuerPrincipal(crl).getEncoded(); - - boolean matchIssuer = false; - if (dp.getCRLIssuer() != null) - { - GeneralName genNames[] = dp.getCRLIssuer().getNames(); - for (int j = 0; j < genNames.length; j++) - { - if (genNames[j].getTagNo() == GeneralName.directoryName) - { - try - { - if (Arrays.areEqual(genNames[j].getName().toASN1Primitive().getEncoded(), issuerBytes)) - { - matchIssuer = true; - } - } - catch (IOException e) - { - throw new AnnotatedException( - "CRL issuer information from distribution point cannot be decoded.", e); - } - } - } - if (matchIssuer && !isIndirect) - { - throw new AnnotatedException("Distribution point contains cRLIssuer field but CRL is not indirect."); - } - if (!matchIssuer) - { - throw new AnnotatedException("CRL issuer of CRL does not match CRL issuer of distribution point."); - } - } - else - { - if (CertPathValidatorUtilities.getIssuerPrincipal(crl).equals( - CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert))) - { - matchIssuer = true; - } - } - if (!matchIssuer) - { - throw new AnnotatedException("Cannot find matching CRL issuer for certificate."); - } - } - - protected static ReasonsMask processCRLD( - X509CRL crl, - DistributionPoint dp) - throws AnnotatedException - { - IssuingDistributionPoint idp = null; - try - { - idp = IssuingDistributionPoint.getInstance(CertPathValidatorUtilities.getExtensionValue(crl, - RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT)); - } - catch (Exception e) - { - throw new AnnotatedException("Issuing distribution point extension could not be decoded.", e); - } - // (d) (1) - if (idp != null && idp.getOnlySomeReasons() != null && dp.getReasons() != null) - { - return new ReasonsMask(dp.getReasons()).intersect(new ReasonsMask(idp.getOnlySomeReasons())); - } - // (d) (4) - if ((idp == null || idp.getOnlySomeReasons() == null) && dp.getReasons() == null) - { - return ReasonsMask.allReasons; - } - // (d) (2) and (d)(3) - return (dp.getReasons() == null - ? ReasonsMask.allReasons - : new ReasonsMask(dp.getReasons())).intersect(idp == null - ? ReasonsMask.allReasons - : new ReasonsMask(idp.getOnlySomeReasons())); - - } - - public static final String CERTIFICATE_POLICIES = X509Extensions.CertificatePolicies.getId(); - - public static final String POLICY_MAPPINGS = X509Extensions.PolicyMappings.getId(); - - public static final String INHIBIT_ANY_POLICY = X509Extensions.InhibitAnyPolicy.getId(); - - public static final String ISSUING_DISTRIBUTION_POINT = X509Extensions.IssuingDistributionPoint.getId(); - - public static final String FRESHEST_CRL = X509Extensions.FreshestCRL.getId(); - - public static final String DELTA_CRL_INDICATOR = X509Extensions.DeltaCRLIndicator.getId(); - - public static final String POLICY_CONSTRAINTS = X509Extensions.PolicyConstraints.getId(); - - public static final String BASIC_CONSTRAINTS = X509Extensions.BasicConstraints.getId(); - - public static final String CRL_DISTRIBUTION_POINTS = X509Extensions.CRLDistributionPoints.getId(); - - public static final String SUBJECT_ALTERNATIVE_NAME = X509Extensions.SubjectAlternativeName.getId(); - - public static final String NAME_CONSTRAINTS = X509Extensions.NameConstraints.getId(); - - public static final String AUTHORITY_KEY_IDENTIFIER = X509Extensions.AuthorityKeyIdentifier.getId(); - - public static final String KEY_USAGE = X509Extensions.KeyUsage.getId(); - - public static final String CRL_NUMBER = X509Extensions.CRLNumber.getId(); - - public static final String ANY_POLICY = "2.5.29.32.0"; - - /* - * key usage bits - */ - protected static final int KEY_CERT_SIGN = 5; - - protected static final int CRL_SIGN = 6; - - /** - * Obtain and validate the certification path for the complete CRL issuer. - * If a key usage extension is present in the CRL issuer's certificate, - * verify that the cRLSign bit is set. - * - * @param crl CRL which contains revocation information for the certificate - * cert. - * @param cert The attribute certificate or certificate to check if it is - * revoked. - * @param defaultCRLSignCert The issuer certificate of the certificate cert. - * @param defaultCRLSignKey The public key of the issuer certificate - * defaultCRLSignCert. - * @param paramsPKIX paramsPKIX PKIX parameters. - * @param certPathCerts The certificates on the certification path. - * @return A Set with all keys of possible CRL issuer - * certificates. - * @throws AnnotatedException if the CRL is not valid or the status cannot be checked or - * some error occurs. - */ - protected static Set processCRLF( - X509CRL crl, - Object cert, - X509Certificate defaultCRLSignCert, - PublicKey defaultCRLSignKey, - ExtendedPKIXParameters paramsPKIX, - List certPathCerts) - throws AnnotatedException - { - // (f) - - // get issuer from CRL - X509CertStoreSelector selector = new X509CertStoreSelector(); - try - { - byte[] issuerPrincipal = CertPathValidatorUtilities.getIssuerPrincipal(crl).getEncoded(); - selector.setSubject(issuerPrincipal); - } - catch (IOException e) - { - throw new AnnotatedException( - "Subject criteria for certificate selector to find issuer certificate for CRL could not be set.", e); - } - - // get CRL signing certs - Collection coll; - try - { - coll = CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getStores()); - coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getAdditionalStores())); - coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getCertStores())); - } - catch (AnnotatedException e) - { - throw new AnnotatedException("Issuer certificate for CRL cannot be searched.", e); - } - - coll.add(defaultCRLSignCert); - - Iterator cert_it = coll.iterator(); - - List validCerts = new ArrayList(); - List validKeys = new ArrayList(); - - while (cert_it.hasNext()) - { - X509Certificate signingCert = (X509Certificate)cert_it.next(); - - /* - * CA of the certificate, for which this CRL is checked, has also - * signed CRL, so skip the path validation, because is already done - */ - if (signingCert.equals(defaultCRLSignCert)) - { - validCerts.add(signingCert); - validKeys.add(defaultCRLSignKey); - continue; - } - try - { - CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME); - selector = new X509CertStoreSelector(); - selector.setCertificate(signingCert); - ExtendedPKIXParameters temp = (ExtendedPKIXParameters)paramsPKIX.clone(); - temp.setTargetCertConstraints(selector); - ExtendedPKIXBuilderParameters params = (ExtendedPKIXBuilderParameters)ExtendedPKIXBuilderParameters - .getInstance(temp); - /* - * if signingCert is placed not higher on the cert path a - * dependency loop results. CRL for cert is checked, but - * signingCert is needed for checking the CRL which is dependent - * on checking cert because it is higher in the cert path and so - * signing signingCert transitively. so, revocation is disabled, - * forgery attacks of the CRL are detected in this outer loop - * for all other it must be enabled to prevent forgery attacks - */ - if (certPathCerts.contains(signingCert)) - { - params.setRevocationEnabled(false); - } - else - { - params.setRevocationEnabled(true); - } - List certs = builder.build(params).getCertPath().getCertificates(); - validCerts.add(signingCert); - validKeys.add(CertPathValidatorUtilities.getNextWorkingKey(certs, 0)); - } - catch (CertPathBuilderException e) - { - throw new AnnotatedException("Internal error.", e); - } - catch (CertPathValidatorException e) - { - throw new AnnotatedException("Public key of issuer certificate of CRL could not be retrieved.", e); - } - catch (Exception e) - { - throw new RuntimeException(e.getMessage()); - } - } - - Set checkKeys = new HashSet(); - - AnnotatedException lastException = null; - for (int i = 0; i < validCerts.size(); i++) - { - X509Certificate signCert = (X509Certificate)validCerts.get(i); - boolean[] keyusage = signCert.getKeyUsage(); - - if (keyusage != null && (keyusage.length < 7 || !keyusage[CRL_SIGN])) - { - lastException = new AnnotatedException( - "Issuer certificate key usage extension does not permit CRL signing."); - } - else - { - checkKeys.add(validKeys.get(i)); - } - } - - if (checkKeys.isEmpty() && lastException == null) - { - throw new AnnotatedException("Cannot find a valid issuer certificate."); - } - if (checkKeys.isEmpty() && lastException != null) - { - throw lastException; - } - - return checkKeys; - } - - protected static PublicKey processCRLG( - X509CRL crl, - Set keys) - throws AnnotatedException - { - Exception lastException = null; - for (Iterator it = keys.iterator(); it.hasNext();) - { - PublicKey key = (PublicKey)it.next(); - try - { - crl.verify(key); - return key; - } - catch (Exception e) - { - lastException = e; - } - } - throw new AnnotatedException("Cannot verify CRL.", lastException); - } - - protected static X509CRL processCRLH( - Set deltacrls, - PublicKey key) - throws AnnotatedException - { - Exception lastException = null; - - for (Iterator it = deltacrls.iterator(); it.hasNext();) - { - X509CRL crl = (X509CRL)it.next(); - try - { - crl.verify(key); - return crl; - } - catch (Exception e) - { - lastException = e; - } - } - - if (lastException != null) - { - throw new AnnotatedException("Cannot verify delta CRL.", lastException); - } - return null; - } - - protected static Set processCRLA1i( - Date currentDate, - ExtendedPKIXParameters paramsPKIX, - X509Certificate cert, - X509CRL crl) - throws AnnotatedException - { - Set set = new HashSet(); - if (paramsPKIX.isUseDeltasEnabled()) - { - CRLDistPoint freshestCRL = null; - try - { - freshestCRL = CRLDistPoint - .getInstance(CertPathValidatorUtilities.getExtensionValue(cert, FRESHEST_CRL)); - } - catch (AnnotatedException e) - { - throw new AnnotatedException("Freshest CRL extension could not be decoded from certificate.", e); - } - if (freshestCRL == null) - { - try - { - freshestCRL = CRLDistPoint.getInstance(CertPathValidatorUtilities.getExtensionValue(crl, - FRESHEST_CRL)); - } - catch (AnnotatedException e) - { - throw new AnnotatedException("Freshest CRL extension could not be decoded from CRL.", e); - } - } - if (freshestCRL != null) - { - try - { - CertPathValidatorUtilities.addAdditionalStoresFromCRLDistributionPoint(freshestCRL, paramsPKIX); - } - catch (AnnotatedException e) - { - throw new AnnotatedException( - "No new delta CRL locations could be added from Freshest CRL extension.", e); - } - // get delta CRL(s) - try - { - set.addAll(CertPathValidatorUtilities.getDeltaCRLs(currentDate, paramsPKIX, crl)); - } - catch (AnnotatedException e) - { - throw new AnnotatedException("Exception obtaining delta CRLs.", e); - } - } - } - return set; - } - - protected static Set[] processCRLA1ii( - Date currentDate, - ExtendedPKIXParameters paramsPKIX, - X509Certificate cert, - X509CRL crl) - throws AnnotatedException - { - Set deltaSet = new HashSet(); - X509CRLStoreSelector crlselect = new X509CRLStoreSelector(); - crlselect.setCertificateChecking(cert); - - try - { - crlselect.addIssuerName(PrincipalUtil.getIssuerX509Principal(crl).getEncoded()); - } - catch (CRLException e) - { - throw new AnnotatedException("Cannot extract issuer from CRL." + e, e); - } - catch (IOException e) - { - throw new AnnotatedException("Cannot extract issuer from CRL." + e, e); - } - - crlselect.setCompleteCRLEnabled(true); - Set completeSet = CRL_UTIL.findCRLs(crlselect, paramsPKIX, currentDate); - - if (paramsPKIX.isUseDeltasEnabled()) - { - // get delta CRL(s) - try - { - deltaSet.addAll(CertPathValidatorUtilities.getDeltaCRLs(currentDate, paramsPKIX, crl)); - } - catch (AnnotatedException e) - { - throw new AnnotatedException("Exception obtaining delta CRLs.", e); - } - } - return new Set[] - { - completeSet, - deltaSet}; - } - - - - /** - * If use-deltas is set, verify the issuer and scope of the delta CRL. - * - * @param deltaCRL The delta CRL. - * @param completeCRL The complete CRL. - * @param pkixParams The PKIX paramaters. - * @throws AnnotatedException if an exception occurs. - */ - protected static void processCRLC( - X509CRL deltaCRL, - X509CRL completeCRL, - ExtendedPKIXParameters pkixParams) - throws AnnotatedException - { - if (deltaCRL == null) - { - return; - } - IssuingDistributionPoint completeidp = null; - try - { - completeidp = IssuingDistributionPoint.getInstance(CertPathValidatorUtilities.getExtensionValue( - completeCRL, RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT)); - } - catch (Exception e) - { - throw new AnnotatedException("Issuing distribution point extension could not be decoded.", e); - } - - if (pkixParams.isUseDeltasEnabled()) - { - // (c) (1) - try - { - if (!PrincipalUtil.getIssuerX509Principal(deltaCRL).equals(PrincipalUtil.getIssuerX509Principal(completeCRL))) - { - throw new AnnotatedException("Complete CRL issuer does not match delta CRL issuer."); - } - } - catch (CRLException e) - { - throw new AnnotatedException( - "Cannot extract issuer from CRL.", e); - } - - // (c) (2) - IssuingDistributionPoint deltaidp = null; - try - { - deltaidp = IssuingDistributionPoint.getInstance(CertPathValidatorUtilities.getExtensionValue( - deltaCRL, ISSUING_DISTRIBUTION_POINT)); - } - catch (Exception e) - { - throw new AnnotatedException( - "Issuing distribution point extension from delta CRL could not be decoded.", e); - } - - boolean match = false; - if (completeidp == null) - { - if (deltaidp == null) - { - match = true; - } - } - else - { - if (completeidp.equals(deltaidp)) - { - match = true; - } - } - if (!match) - { - throw new AnnotatedException( - "Issuing distribution point extension from delta CRL and complete CRL does not match."); - } - - // (c) (3) - ASN1Primitive completeKeyIdentifier = null; - try - { - completeKeyIdentifier = CertPathValidatorUtilities.getExtensionValue( - completeCRL, AUTHORITY_KEY_IDENTIFIER); - } - catch (AnnotatedException e) - { - throw new AnnotatedException( - "Authority key identifier extension could not be extracted from complete CRL.", e); - } - - ASN1Primitive deltaKeyIdentifier = null; - try - { - deltaKeyIdentifier = CertPathValidatorUtilities.getExtensionValue( - deltaCRL, AUTHORITY_KEY_IDENTIFIER); - } - catch (AnnotatedException e) - { - throw new AnnotatedException( - "Authority key identifier extension could not be extracted from delta CRL.", e); - } - - if (completeKeyIdentifier == null) - { - throw new AnnotatedException("CRL authority key identifier is null."); - } - - if (deltaKeyIdentifier == null) - { - throw new AnnotatedException("Delta CRL authority key identifier is null."); - } - - if (!completeKeyIdentifier.equals(deltaKeyIdentifier)) - { - throw new AnnotatedException( - "Delta CRL authority key identifier does not match complete CRL authority key identifier."); - } - } - } - - protected static void processCRLI( - Date validDate, - X509CRL deltacrl, - Object cert, - CertStatus certStatus, - ExtendedPKIXParameters pkixParams) - throws AnnotatedException - { - if (pkixParams.isUseDeltasEnabled() && deltacrl != null) - { - CertPathValidatorUtilities.getCertStatus(validDate, deltacrl, cert, certStatus); - } - } - - protected static void processCRLJ( - Date validDate, - X509CRL completecrl, - Object cert, - CertStatus certStatus) - throws AnnotatedException - { - if (certStatus.getCertStatus() == CertStatus.UNREVOKED) - { - CertPathValidatorUtilities.getCertStatus(validDate, completecrl, cert, certStatus); - } - } - - protected static PKIXPolicyNode prepareCertB( - CertPath certPath, - int index, - List[] policyNodes, - PKIXPolicyNode validPolicyTree, - int policyMapping) - throws CertPathValidatorException - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - int n = certs.size(); - // i as defined in the algorithm description - int i = n - index; - // (b) - // - ASN1Sequence pm = null; - try - { - pm = DERSequence.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, - RFC3280CertPathUtilities.POLICY_MAPPINGS)); - } - catch (AnnotatedException ex) - { - throw new ExtCertPathValidatorException("Policy mappings extension could not be decoded.", ex, certPath, - index); - } - PKIXPolicyNode _validPolicyTree = validPolicyTree; - if (pm != null) - { - ASN1Sequence mappings = (ASN1Sequence)pm; - Map m_idp = new HashMap(); - Set s_idp = new HashSet(); - - for (int j = 0; j < mappings.size(); j++) - { - ASN1Sequence mapping = (ASN1Sequence)mappings.getObjectAt(j); - String id_p = ((ASN1ObjectIdentifier)mapping.getObjectAt(0)).getId(); - String sd_p = ((ASN1ObjectIdentifier)mapping.getObjectAt(1)).getId(); - Set tmp; - - if (!m_idp.containsKey(id_p)) - { - tmp = new HashSet(); - tmp.add(sd_p); - m_idp.put(id_p, tmp); - s_idp.add(id_p); - } - else - { - tmp = (Set)m_idp.get(id_p); - tmp.add(sd_p); - } - } - - Iterator it_idp = s_idp.iterator(); - while (it_idp.hasNext()) - { - String id_p = (String)it_idp.next(); - - // - // (1) - // - if (policyMapping > 0) - { - boolean idp_found = false; - Iterator nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (node.getValidPolicy().equals(id_p)) - { - idp_found = true; - node.expectedPolicies = (Set)m_idp.get(id_p); - break; - } - } - - if (!idp_found) - { - nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (RFC3280CertPathUtilities.ANY_POLICY.equals(node.getValidPolicy())) - { - Set pq = null; - ASN1Sequence policies = null; - try - { - policies = (ASN1Sequence)CertPathValidatorUtilities.getExtensionValue(cert, - RFC3280CertPathUtilities.CERTIFICATE_POLICIES); - } - catch (AnnotatedException e) - { - throw new ExtCertPathValidatorException( - "Certificate policies extension could not be decoded.", e, certPath, index); - } - Enumeration e = policies.getObjects(); - while (e.hasMoreElements()) - { - PolicyInformation pinfo = null; - try - { - pinfo = PolicyInformation.getInstance(e.nextElement()); - } - catch (Exception ex) - { - throw new CertPathValidatorException( - "Policy information could not be decoded.", ex, certPath, index); - } - if (RFC3280CertPathUtilities.ANY_POLICY.equals(pinfo.getPolicyIdentifier().getId())) - { - try - { - pq = CertPathValidatorUtilities - .getQualifierSet(pinfo.getPolicyQualifiers()); - } - catch (CertPathValidatorException ex) - { - - throw new ExtCertPathValidatorException( - "Policy qualifier info set could not be decoded.", ex, certPath, - index); - } - break; - } - } - boolean ci = false; - if (cert.getCriticalExtensionOIDs() != null) - { - ci = cert.getCriticalExtensionOIDs().contains( - RFC3280CertPathUtilities.CERTIFICATE_POLICIES); - } - - PKIXPolicyNode p_node = (PKIXPolicyNode)node.getParent(); - if (RFC3280CertPathUtilities.ANY_POLICY.equals(p_node.getValidPolicy())) - { - PKIXPolicyNode c_node = new PKIXPolicyNode(new ArrayList(), i, (Set)m_idp - .get(id_p), p_node, pq, id_p, ci); - p_node.addChild(c_node); - policyNodes[i].add(c_node); - } - break; - } - } - } - - // - // (2) - // - } - else if (policyMapping <= 0) - { - Iterator nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (node.getValidPolicy().equals(id_p)) - { - PKIXPolicyNode p_node = (PKIXPolicyNode)node.getParent(); - p_node.removeChild(node); - nodes_i.remove(); - for (int k = (i - 1); k >= 0; k--) - { - List nodes = policyNodes[k]; - for (int l = 0; l < nodes.size(); l++) - { - PKIXPolicyNode node2 = (PKIXPolicyNode)nodes.get(l); - if (!node2.hasChildren()) - { - _validPolicyTree = CertPathValidatorUtilities.removePolicyNode( - _validPolicyTree, policyNodes, node2); - if (_validPolicyTree == null) - { - break; - } - } - } - } - } - } - } - } - } - return _validPolicyTree; - } - - protected static void prepareNextCertA( - CertPath certPath, - int index) - throws CertPathValidatorException - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - // - // - // (a) check the policy mappings - // - ASN1Sequence pm = null; - try - { - pm = DERSequence.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, - RFC3280CertPathUtilities.POLICY_MAPPINGS)); - } - catch (AnnotatedException ex) - { - throw new ExtCertPathValidatorException("Policy mappings extension could not be decoded.", ex, certPath, - index); - } - if (pm != null) - { - ASN1Sequence mappings = pm; - - for (int j = 0; j < mappings.size(); j++) - { - ASN1ObjectIdentifier issuerDomainPolicy = null; - ASN1ObjectIdentifier subjectDomainPolicy = null; - try - { - ASN1Sequence mapping = DERSequence.getInstance(mappings.getObjectAt(j)); - - issuerDomainPolicy = ASN1ObjectIdentifier.getInstance(mapping.getObjectAt(0)); - subjectDomainPolicy = ASN1ObjectIdentifier.getInstance(mapping.getObjectAt(1)); - } - catch (Exception e) - { - throw new ExtCertPathValidatorException("Policy mappings extension contents could not be decoded.", - e, certPath, index); - } - - if (RFC3280CertPathUtilities.ANY_POLICY.equals(issuerDomainPolicy.getId())) - { - - throw new CertPathValidatorException("IssuerDomainPolicy is anyPolicy", null, certPath, index); - } - - if (RFC3280CertPathUtilities.ANY_POLICY.equals(subjectDomainPolicy.getId())) - { - - throw new CertPathValidatorException("SubjectDomainPolicy is anyPolicy,", null, certPath, index); - } - } - } - } - - protected static void processCertF( - CertPath certPath, - int index, - PKIXPolicyNode validPolicyTree, - int explicitPolicy) - throws CertPathValidatorException - { - // - // (f) - // - if (explicitPolicy <= 0 && validPolicyTree == null) - { - throw new ExtCertPathValidatorException("No valid policy tree found when one expected.", null, certPath, - index); - } - } - - protected static PKIXPolicyNode processCertE( - CertPath certPath, - int index, - PKIXPolicyNode validPolicyTree) - throws CertPathValidatorException - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - // - // (e) - // - ASN1Sequence certPolicies = null; - try - { - certPolicies = DERSequence.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, - RFC3280CertPathUtilities.CERTIFICATE_POLICIES)); - } - catch (AnnotatedException e) - { - throw new ExtCertPathValidatorException("Could not read certificate policies extension from certificate.", - e, certPath, index); - } - if (certPolicies == null) - { - validPolicyTree = null; - } - return validPolicyTree; - } - - protected static void processCertBC( - CertPath certPath, - int index, - PKIXNameConstraintValidator nameConstraintValidator) - throws CertPathValidatorException - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - int n = certs.size(); - // i as defined in the algorithm description - int i = n - index; - // - // (b), (c) permitted and excluded subtree checking. - // - if (!(CertPathValidatorUtilities.isSelfIssued(cert) && (i < n))) - { - X509Principal principal = CertPathValidatorUtilities.getSubjectPrincipal(cert); - ASN1InputStream aIn = new ASN1InputStream(principal.getEncoded()); - ASN1Sequence dns; - - try - { - dns = DERSequence.getInstance(aIn.readObject()); - } - catch (Exception e) - { - throw new CertPathValidatorException("Exception extracting subject name when checking subtrees.", e, - certPath, index); - } - - try - { - nameConstraintValidator.checkPermittedDN(dns); - nameConstraintValidator.checkExcludedDN(dns); - } - catch (PKIXNameConstraintValidatorException e) - { - throw new CertPathValidatorException("Subtree check for certificate subject failed.", e, certPath, - index); - } - - GeneralNames altName = null; - try - { - altName = GeneralNames.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, - RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME)); - } - catch (Exception e) - { - throw new CertPathValidatorException("Subject alternative name extension could not be decoded.", e, - certPath, index); - } - Vector emails = new X509Name(dns).getValues(X509Name.EmailAddress); - for (Enumeration e = emails.elements(); e.hasMoreElements();) - { - String email = (String)e.nextElement(); - GeneralName emailAsGeneralName = new GeneralName(GeneralName.rfc822Name, email); - try - { - nameConstraintValidator.checkPermitted(emailAsGeneralName); - nameConstraintValidator.checkExcluded(emailAsGeneralName); - } - catch (PKIXNameConstraintValidatorException ex) - { - throw new CertPathValidatorException( - "Subtree check for certificate subject alternative email failed.", ex, certPath, index); - } - } - if (altName != null) - { - GeneralName[] genNames = null; - try - { - genNames = altName.getNames(); - } - catch (Exception e) - { - throw new CertPathValidatorException("Subject alternative name contents could not be decoded.", e, - certPath, index); - } - for (int j = 0; j < genNames.length; j++) - { - - try - { - nameConstraintValidator.checkPermitted(genNames[j]); - nameConstraintValidator.checkExcluded(genNames[j]); - } - catch (PKIXNameConstraintValidatorException e) - { - throw new CertPathValidatorException( - "Subtree check for certificate subject alternative name failed.", e, certPath, index); - } - } - } - } - } - - protected static PKIXPolicyNode processCertD( - CertPath certPath, - int index, - Set acceptablePolicies, - PKIXPolicyNode validPolicyTree, - List[] policyNodes, - int inhibitAnyPolicy) - throws CertPathValidatorException - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - int n = certs.size(); - // i as defined in the algorithm description - int i = n - index; - // - // (d) policy Information checking against initial policy and - // policy mapping - // - ASN1Sequence certPolicies = null; - try - { - certPolicies = DERSequence.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, - RFC3280CertPathUtilities.CERTIFICATE_POLICIES)); - } - catch (AnnotatedException e) - { - throw new ExtCertPathValidatorException("Could not read certificate policies extension from certificate.", - e, certPath, index); - } - if (certPolicies != null && validPolicyTree != null) - { - // - // (d) (1) - // - Enumeration e = certPolicies.getObjects(); - Set pols = new HashSet(); - - while (e.hasMoreElements()) - { - PolicyInformation pInfo = PolicyInformation.getInstance(e.nextElement()); - ASN1ObjectIdentifier pOid = pInfo.getPolicyIdentifier(); - - pols.add(pOid.getId()); - - if (!RFC3280CertPathUtilities.ANY_POLICY.equals(pOid.getId())) - { - Set pq = null; - try - { - pq = CertPathValidatorUtilities.getQualifierSet(pInfo.getPolicyQualifiers()); - } - catch (CertPathValidatorException ex) - { - throw new ExtCertPathValidatorException("Policy qualifier info set could not be build.", ex, - certPath, index); - } - - boolean match = CertPathValidatorUtilities.processCertD1i(i, policyNodes, pOid, pq); - - if (!match) - { - CertPathValidatorUtilities.processCertD1ii(i, policyNodes, pOid, pq); - } - } - } - - if (acceptablePolicies.isEmpty() || acceptablePolicies.contains(RFC3280CertPathUtilities.ANY_POLICY)) - { - acceptablePolicies.clear(); - acceptablePolicies.addAll(pols); - } - else - { - Iterator it = acceptablePolicies.iterator(); - Set t1 = new HashSet(); - - while (it.hasNext()) - { - Object o = it.next(); - - if (pols.contains(o)) - { - t1.add(o); - } - } - acceptablePolicies.clear(); - acceptablePolicies.addAll(t1); - } - - // - // (d) (2) - // - if ((inhibitAnyPolicy > 0) || ((i < n) && CertPathValidatorUtilities.isSelfIssued(cert))) - { - e = certPolicies.getObjects(); - - while (e.hasMoreElements()) - { - PolicyInformation pInfo = PolicyInformation.getInstance(e.nextElement()); - - if (RFC3280CertPathUtilities.ANY_POLICY.equals(pInfo.getPolicyIdentifier().getId())) - { - Set _apq = CertPathValidatorUtilities.getQualifierSet(pInfo.getPolicyQualifiers()); - List _nodes = policyNodes[i - 1]; - - for (int k = 0; k < _nodes.size(); k++) - { - PKIXPolicyNode _node = (PKIXPolicyNode)_nodes.get(k); - - Iterator _policySetIter = _node.getExpectedPolicies().iterator(); - while (_policySetIter.hasNext()) - { - Object _tmp = _policySetIter.next(); - - String _policy; - if (_tmp instanceof String) - { - _policy = (String)_tmp; - } - else if (_tmp instanceof ASN1ObjectIdentifier) - { - _policy = ((ASN1ObjectIdentifier)_tmp).getId(); - } - else - { - continue; - } - - boolean _found = false; - Iterator _childrenIter = _node.getChildren(); - - while (_childrenIter.hasNext()) - { - PKIXPolicyNode _child = (PKIXPolicyNode)_childrenIter.next(); - - if (_policy.equals(_child.getValidPolicy())) - { - _found = true; - } - } - - if (!_found) - { - Set _newChildExpectedPolicies = new HashSet(); - _newChildExpectedPolicies.add(_policy); - - PKIXPolicyNode _newChild = new PKIXPolicyNode(new ArrayList(), i, - _newChildExpectedPolicies, _node, _apq, _policy, false); - _node.addChild(_newChild); - policyNodes[i].add(_newChild); - } - } - } - break; - } - } - } - - PKIXPolicyNode _validPolicyTree = validPolicyTree; - // - // (d) (3) - // - for (int j = (i - 1); j >= 0; j--) - { - List nodes = policyNodes[j]; - - for (int k = 0; k < nodes.size(); k++) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes.get(k); - if (!node.hasChildren()) - { - _validPolicyTree = CertPathValidatorUtilities.removePolicyNode(_validPolicyTree, policyNodes, - node); - if (_validPolicyTree == null) - { - break; - } - } - } - } - - // - // d (4) - // - Set criticalExtensionOids = cert.getCriticalExtensionOIDs(); - - if (criticalExtensionOids != null) - { - boolean critical = criticalExtensionOids.contains(RFC3280CertPathUtilities.CERTIFICATE_POLICIES); - - List nodes = policyNodes[i]; - for (int j = 0; j < nodes.size(); j++) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes.get(j); - node.setCritical(critical); - } - } - return _validPolicyTree; - } - return null; - } - - protected static void processCertA( - CertPath certPath, - ExtendedPKIXParameters paramsPKIX, - int index, - PublicKey workingPublicKey, - boolean verificationAlreadyPerformed, - X509Principal workingIssuerName, - X509Certificate sign) - throws ExtCertPathValidatorException - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - // - // (a) verify - // - if (!verificationAlreadyPerformed) - { - try - { - // (a) (1) - // - CertPathValidatorUtilities.verifyX509Certificate(cert, workingPublicKey, - paramsPKIX.getSigProvider()); - } - catch (GeneralSecurityException e) - { - throw new ExtCertPathValidatorException("Could not validate certificate signature.", e, certPath, index); - } - } - - try - { - // (a) (2) - // - cert.checkValidity(CertPathValidatorUtilities - .getValidCertDateFromValidityModel(paramsPKIX, certPath, index)); - } - catch (CertificateExpiredException e) - { - throw new ExtCertPathValidatorException("Could not validate certificate: " + e.getMessage(), e, certPath, index); - } - catch (CertificateNotYetValidException e) - { - throw new ExtCertPathValidatorException("Could not validate certificate: " + e.getMessage(), e, certPath, index); - } - catch (AnnotatedException e) - { - throw new ExtCertPathValidatorException("Could not validate time of certificate.", e, certPath, index); - } - - // - // (a) (3) - // - if (paramsPKIX.isRevocationEnabled()) - { - try - { - checkCRLs(paramsPKIX, cert, CertPathValidatorUtilities.getValidCertDateFromValidityModel(paramsPKIX, - certPath, index), sign, workingPublicKey, certs); - } - catch (AnnotatedException e) - { - Throwable cause = e; - if (null != e.getCause()) - { - cause = e.getCause(); - } - throw new ExtCertPathValidatorException(e.getMessage(), cause, certPath, index); - } - } - - // - // (a) (4) name chaining - // - if (!CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert).equals(workingIssuerName)) - { - throw new ExtCertPathValidatorException("IssuerName(" + CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert) - + ") does not match SubjectName(" + workingIssuerName + ") of signing certificate.", null, - certPath, index); - } - } - - protected static int prepareNextCertI1( - CertPath certPath, - int index, - int explicitPolicy) - throws CertPathValidatorException - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - // - // (i) - // - ASN1Sequence pc = null; - try - { - pc = DERSequence.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, - RFC3280CertPathUtilities.POLICY_CONSTRAINTS)); - } - catch (Exception e) - { - throw new ExtCertPathValidatorException("Policy constraints extension cannot be decoded.", e, certPath, - index); - } - - int tmpInt; - - if (pc != null) - { - Enumeration policyConstraints = pc.getObjects(); - - while (policyConstraints.hasMoreElements()) - { - try - { - - ASN1TaggedObject constraint = ASN1TaggedObject.getInstance(policyConstraints.nextElement()); - if (constraint.getTagNo() == 0) - { - tmpInt = ASN1Integer.getInstance(constraint, false).getValue().intValue(); - if (tmpInt < explicitPolicy) - { - return tmpInt; - } - break; - } - } - catch (IllegalArgumentException e) - { - throw new ExtCertPathValidatorException("Policy constraints extension contents cannot be decoded.", - e, certPath, index); - } - } - } - return explicitPolicy; - } - - protected static int prepareNextCertI2( - CertPath certPath, - int index, - int policyMapping) - throws CertPathValidatorException - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - // - // (i) - // - ASN1Sequence pc = null; - try - { - pc = DERSequence.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, - RFC3280CertPathUtilities.POLICY_CONSTRAINTS)); - } - catch (Exception e) - { - throw new ExtCertPathValidatorException("Policy constraints extension cannot be decoded.", e, certPath, - index); - } - - int tmpInt; - - if (pc != null) - { - Enumeration policyConstraints = pc.getObjects(); - - while (policyConstraints.hasMoreElements()) - { - try - { - ASN1TaggedObject constraint = ASN1TaggedObject.getInstance(policyConstraints.nextElement()); - if (constraint.getTagNo() == 1) - { - tmpInt = ASN1Integer.getInstance(constraint, false).getValue().intValue(); - if (tmpInt < policyMapping) - { - return tmpInt; - } - break; - } - } - catch (IllegalArgumentException e) - { - throw new ExtCertPathValidatorException("Policy constraints extension contents cannot be decoded.", - e, certPath, index); - } - } - } - return policyMapping; - } - - protected static void prepareNextCertG( - CertPath certPath, - int index, - PKIXNameConstraintValidator nameConstraintValidator) - throws CertPathValidatorException - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - // - // (g) handle the name constraints extension - // - NameConstraints nc = null; - try - { - ASN1Sequence ncSeq = DERSequence.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, - RFC3280CertPathUtilities.NAME_CONSTRAINTS)); - if (ncSeq != null) - { - nc = NameConstraints.getInstance(ncSeq); - } - } - catch (Exception e) - { - throw new ExtCertPathValidatorException("Name constraints extension could not be decoded.", e, certPath, - index); - } - if (nc != null) - { - - // - // (g) (1) permitted subtrees - // - GeneralSubtree[] permitted = nc.getPermittedSubtrees(); - if (permitted != null) - { - try - { - nameConstraintValidator.intersectPermittedSubtree(permitted); - } - catch (Exception ex) - { - throw new ExtCertPathValidatorException( - "Permitted subtrees cannot be build from name constraints extension.", ex, certPath, index); - } - } - - // - // (g) (2) excluded subtrees - // - GeneralSubtree[] excluded = nc.getExcludedSubtrees(); - if (excluded != null) - { - for (int i = 0; i != excluded.length; i++) - try - { - nameConstraintValidator.addExcludedSubtree(excluded[i]); - } - catch (Exception ex) - { - throw new ExtCertPathValidatorException( - "Excluded subtrees cannot be build from name constraints extension.", ex, certPath, index); - } - } - } - } - - /** - * Checks a distribution point for revocation information for the - * certificate cert. - * - * @param dp The distribution point to consider. - * @param paramsPKIX PKIX parameters. - * @param cert Certificate to check if it is revoked. - * @param validDate The date when the certificate revocation status should be - * checked. - * @param defaultCRLSignCert The issuer certificate of the certificate cert. - * @param defaultCRLSignKey The public key of the issuer certificate - * defaultCRLSignCert. - * @param certStatus The current certificate revocation status. - * @param reasonMask The reasons mask which is already checked. - * @param certPathCerts The certificates of the certification path. - * @throws AnnotatedException if the certificate is revoked or the status cannot be checked - * or some error occurs. - */ - private static void checkCRL( - DistributionPoint dp, - ExtendedPKIXParameters paramsPKIX, - X509Certificate cert, - Date validDate, - X509Certificate defaultCRLSignCert, - PublicKey defaultCRLSignKey, - CertStatus certStatus, - ReasonsMask reasonMask, - List certPathCerts) - throws AnnotatedException - { - Date currentDate = new Date(System.currentTimeMillis()); - if (validDate.getTime() > currentDate.getTime()) - { - throw new AnnotatedException("Validation time is in future."); - } - - // (a) - /* - * We always get timely valid CRLs, so there is no step (a) (1). - * "locally cached" CRLs are assumed to be in getStore(), additional - * CRLs must be enabled in the ExtendedPKIXParameters and are in - * getAdditionalStore() - */ - - Set crls = CertPathValidatorUtilities.getCompleteCRLs(dp, cert, currentDate, paramsPKIX); - boolean validCrlFound = false; - AnnotatedException lastException = null; - Iterator crl_iter = crls.iterator(); - - while (crl_iter.hasNext() && certStatus.getCertStatus() == CertStatus.UNREVOKED && !reasonMask.isAllReasons()) - { - try - { - X509CRL crl = (X509CRL)crl_iter.next(); - - // (d) - ReasonsMask interimReasonsMask = RFC3280CertPathUtilities.processCRLD(crl, dp); - - // (e) - /* - * The reasons mask is updated at the end, so only valid CRLs - * can update it. If this CRL does not contain new reasons it - * must be ignored. - */ - if (!interimReasonsMask.hasNewReasons(reasonMask)) - { - continue; - } - - // (f) - Set keys = RFC3280CertPathUtilities.processCRLF(crl, cert, defaultCRLSignCert, defaultCRLSignKey, - paramsPKIX, certPathCerts); - // (g) - PublicKey key = RFC3280CertPathUtilities.processCRLG(crl, keys); - - X509CRL deltaCRL = null; - - if (paramsPKIX.isUseDeltasEnabled()) - { - // get delta CRLs - Set deltaCRLs = CertPathValidatorUtilities.getDeltaCRLs(currentDate, paramsPKIX, crl); - // we only want one valid delta CRL - // (h) - deltaCRL = RFC3280CertPathUtilities.processCRLH(deltaCRLs, key); - } - - /* - * CRL must be be valid at the current time, not the validation - * time. If a certificate is revoked with reason keyCompromise, - * cACompromise, it can be used for forgery, also for the past. - * This reason may not be contained in older CRLs. - */ - - /* - * in the chain model signatures stay valid also after the - * certificate has been expired, so they do not have to be in - * the CRL validity time - */ - - if (paramsPKIX.getValidityModel() != ExtendedPKIXParameters.CHAIN_VALIDITY_MODEL) - { - /* - * if a certificate has expired, but was revoked, it is not - * more in the CRL, so it would be regarded as valid if the - * first check is not done - */ - if (cert.getNotAfter().getTime() < crl.getThisUpdate().getTime()) - { - throw new AnnotatedException("No valid CRL for current time found."); - } - } - - RFC3280CertPathUtilities.processCRLB1(dp, cert, crl); - - // (b) (2) - RFC3280CertPathUtilities.processCRLB2(dp, cert, crl); - - // (c) - RFC3280CertPathUtilities.processCRLC(deltaCRL, crl, paramsPKIX); - - // (i) - RFC3280CertPathUtilities.processCRLI(validDate, deltaCRL, cert, certStatus, paramsPKIX); - - // (j) - RFC3280CertPathUtilities.processCRLJ(validDate, crl, cert, certStatus); - - // (k) - if (certStatus.getCertStatus() == CRLReason.removeFromCRL) - { - certStatus.setCertStatus(CertStatus.UNREVOKED); - } - - // update reasons mask - reasonMask.addReasons(interimReasonsMask); - - Set criticalExtensions = crl.getCriticalExtensionOIDs(); - if (criticalExtensions != null) - { - criticalExtensions = new HashSet(criticalExtensions); - criticalExtensions.remove(X509Extensions.IssuingDistributionPoint.getId()); - criticalExtensions.remove(X509Extensions.DeltaCRLIndicator.getId()); - - if (!criticalExtensions.isEmpty()) - { - throw new AnnotatedException("CRL contains unsupported critical extensions."); - } - } - - if (deltaCRL != null) - { - criticalExtensions = deltaCRL.getCriticalExtensionOIDs(); - if (criticalExtensions != null) - { - criticalExtensions = new HashSet(criticalExtensions); - criticalExtensions.remove(X509Extensions.IssuingDistributionPoint.getId()); - criticalExtensions.remove(X509Extensions.DeltaCRLIndicator.getId()); - if (!criticalExtensions.isEmpty()) - { - throw new AnnotatedException("Delta CRL contains unsupported critical extension."); - } - } - } - - validCrlFound = true; - } - catch (AnnotatedException e) - { - lastException = e; - } - } - if (!validCrlFound) - { - throw lastException; - } - } - - /** - * Checks a certificate if it is revoked. - * - * @param paramsPKIX PKIX parameters. - * @param cert Certificate to check if it is revoked. - * @param validDate The date when the certificate revocation status should be - * checked. - * @param sign The issuer certificate of the certificate cert. - * @param workingPublicKey The public key of the issuer certificate sign. - * @param certPathCerts The certificates of the certification path. - * @throws AnnotatedException if the certificate is revoked or the status cannot be checked - * or some error occurs. - */ - protected static void checkCRLs( - ExtendedPKIXParameters paramsPKIX, - X509Certificate cert, - Date validDate, - X509Certificate sign, - PublicKey workingPublicKey, - List certPathCerts) - throws AnnotatedException - { - AnnotatedException lastException = null; - CRLDistPoint crldp = null; - try - { - crldp = CRLDistPoint.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, - RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS)); - } - catch (Exception e) - { - throw new AnnotatedException("CRL distribution point extension could not be read.", e); - } - try - { - CertPathValidatorUtilities.addAdditionalStoresFromCRLDistributionPoint(crldp, paramsPKIX); - } - catch (AnnotatedException e) - { - throw new AnnotatedException( - "No additional CRL locations could be decoded from CRL distribution point extension.", e); - } - CertStatus certStatus = new CertStatus(); - ReasonsMask reasonsMask = new ReasonsMask(); - - boolean validCrlFound = false; - // for each distribution point - if (crldp != null) - { - DistributionPoint dps[] = null; - try - { - dps = crldp.getDistributionPoints(); - } - catch (Exception e) - { - throw new AnnotatedException("Distribution points could not be read.", e); - } - if (dps != null) - { - for (int i = 0; i < dps.length && certStatus.getCertStatus() == CertStatus.UNREVOKED && !reasonsMask.isAllReasons(); i++) - { - ExtendedPKIXParameters paramsPKIXClone = (ExtendedPKIXParameters)paramsPKIX.clone(); - try - { - checkCRL(dps[i], paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask, certPathCerts); - validCrlFound = true; - } - catch (AnnotatedException e) - { - lastException = e; - } - } - } - } - - /* - * If the revocation status has not been determined, repeat the process - * above with any available CRLs not specified in a distribution point - * but issued by the certificate issuer. - */ - - if (certStatus.getCertStatus() == CertStatus.UNREVOKED && !reasonsMask.isAllReasons()) - { - try - { - /* - * assume a DP with both the reasons and the cRLIssuer fields - * omitted and a distribution point name of the certificate - * issuer. - */ - ASN1Primitive issuer = null; - try - { - issuer = new ASN1InputStream(CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert).getEncoded()) - .readObject(); - } - catch (Exception e) - { - throw new AnnotatedException("Issuer from certificate for CRL could not be reencoded.", e); - } - DistributionPoint dp = new DistributionPoint(new DistributionPointName(0, new GeneralNames( - new GeneralName(GeneralName.directoryName, issuer))), null, null); - ExtendedPKIXParameters paramsPKIXClone = (ExtendedPKIXParameters)paramsPKIX.clone(); - checkCRL(dp, paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask, - certPathCerts); - validCrlFound = true; - } - catch (AnnotatedException e) - { - lastException = e; - } - } - - if (!validCrlFound) - { - if (lastException instanceof AnnotatedException) - { - throw lastException; - } - - throw new AnnotatedException("No valid CRL found.", lastException); - } - if (certStatus.getCertStatus() != CertStatus.UNREVOKED) - { - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss +0000"); - df.setTimeZone(TimeZone.getTimeZone("UTC")); - String message = "Certificate revocation after " + df.format(certStatus.getRevocationDate()); - message += ", reason: " + crlReasons[certStatus.getCertStatus()]; - throw new AnnotatedException(message); - } - if (!reasonsMask.isAllReasons() && certStatus.getCertStatus() == CertStatus.UNREVOKED) - { - certStatus.setCertStatus(CertStatus.UNDETERMINED); - } - if (certStatus.getCertStatus() == CertStatus.UNDETERMINED) - { - throw new AnnotatedException("Certificate status could not be determined."); - } - } - - protected static int prepareNextCertJ( - CertPath certPath, - int index, - int inhibitAnyPolicy) - throws CertPathValidatorException - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - // - // (j) - // - ASN1Integer iap = null; - try - { - iap = ASN1Integer.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, - RFC3280CertPathUtilities.INHIBIT_ANY_POLICY)); - } - catch (Exception e) - { - throw new ExtCertPathValidatorException("Inhibit any-policy extension cannot be decoded.", e, certPath, - index); - } - - if (iap != null) - { - int _inhibitAnyPolicy = iap.getValue().intValue(); - - if (_inhibitAnyPolicy < inhibitAnyPolicy) - { - return _inhibitAnyPolicy; - } - } - return inhibitAnyPolicy; - } - - protected static void prepareNextCertK( - CertPath certPath, - int index) - throws CertPathValidatorException - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - // - // (k) - // - BasicConstraints bc = null; - try - { - bc = BasicConstraints.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, - RFC3280CertPathUtilities.BASIC_CONSTRAINTS)); - } - catch (Exception e) - { - throw new ExtCertPathValidatorException("Basic constraints extension cannot be decoded.", e, certPath, - index); - } - if (bc != null) - { - if (!(bc.isCA())) - { - throw new CertPathValidatorException("Not a CA certificate"); - } - } - else - { - throw new CertPathValidatorException("Intermediate certificate lacks BasicConstraints"); - } - } - - protected static int prepareNextCertL( - CertPath certPath, - int index, - int maxPathLength) - throws CertPathValidatorException - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - // - // (l) - // - if (!CertPathValidatorUtilities.isSelfIssued(cert)) - { - if (maxPathLength <= 0) - { - throw new ExtCertPathValidatorException("Max path length not greater than zero", null, certPath, index); - } - - return maxPathLength - 1; - } - return maxPathLength; - } - - protected static int prepareNextCertM( - CertPath certPath, - int index, - int maxPathLength) - throws CertPathValidatorException - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - - // - // (m) - // - BasicConstraints bc = null; - try - { - bc = BasicConstraints.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, - RFC3280CertPathUtilities.BASIC_CONSTRAINTS)); - } - catch (Exception e) - { - throw new ExtCertPathValidatorException("Basic constraints extension cannot be decoded.", e, certPath, - index); - } - if (bc != null) - { - BigInteger _pathLengthConstraint = bc.getPathLenConstraint(); - - if (_pathLengthConstraint != null) - { - int _plc = _pathLengthConstraint.intValue(); - - if (_plc < maxPathLength) - { - return _plc; - } - } - } - return maxPathLength; - } - - protected static void prepareNextCertN( - CertPath certPath, - int index) - throws CertPathValidatorException - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - - // - // (n) - // - boolean[] _usage = cert.getKeyUsage(); - - if ((_usage != null) && !_usage[RFC3280CertPathUtilities.KEY_CERT_SIGN]) - { - throw new ExtCertPathValidatorException( - "Issuer certificate keyusage extension is critical and does not permit key signing.", null, - certPath, index); - } - } - - protected static void prepareNextCertO( - CertPath certPath, - int index, - Set criticalExtensions, - List pathCheckers) - throws CertPathValidatorException - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - // - // (o) - // - - Iterator tmpIter; - tmpIter = pathCheckers.iterator(); - while (tmpIter.hasNext()) - { - try - { - ((PKIXCertPathChecker)tmpIter.next()).check(cert, criticalExtensions); - } - catch (CertPathValidatorException e) - { - throw new CertPathValidatorException(e.getMessage(), e.getCause(), certPath, index); - } - } - if (!criticalExtensions.isEmpty()) - { - throw new ExtCertPathValidatorException("Certificate has unsupported critical extension: " + criticalExtensions, null, certPath, - index); - } - } - - protected static int prepareNextCertH1( - CertPath certPath, - int index, - int explicitPolicy) - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - // - // (h) - // - if (!CertPathValidatorUtilities.isSelfIssued(cert)) - { - // - // (1) - // - if (explicitPolicy != 0) - { - return explicitPolicy - 1; - } - } - return explicitPolicy; - } - - protected static int prepareNextCertH2( - CertPath certPath, - int index, - int policyMapping) - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - // - // (h) - // - if (!CertPathValidatorUtilities.isSelfIssued(cert)) - { - // - // (2) - // - if (policyMapping != 0) - { - return policyMapping - 1; - } - } - return policyMapping; - } - - protected static int prepareNextCertH3( - CertPath certPath, - int index, - int inhibitAnyPolicy) - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - // - // (h) - // - if (!CertPathValidatorUtilities.isSelfIssued(cert)) - { - // - // (3) - // - if (inhibitAnyPolicy != 0) - { - return inhibitAnyPolicy - 1; - } - } - return inhibitAnyPolicy; - } - - protected static final String[] crlReasons = new String[] - { - "unspecified", - "keyCompromise", - "cACompromise", - "affiliationChanged", - "superseded", - "cessationOfOperation", - "certificateHold", - "unknown", - "removeFromCRL", - "privilegeWithdrawn", - "aACompromise"}; - - protected static int wrapupCertA( - int explicitPolicy, - X509Certificate cert) - { - // - // (a) - // - if (!CertPathValidatorUtilities.isSelfIssued(cert) && (explicitPolicy != 0)) - { - explicitPolicy--; - } - return explicitPolicy; - } - - protected static int wrapupCertB( - CertPath certPath, - int index, - int explicitPolicy) - throws CertPathValidatorException - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - // - // (b) - // - int tmpInt; - ASN1Sequence pc = null; - try - { - pc = DERSequence.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, - RFC3280CertPathUtilities.POLICY_CONSTRAINTS)); - } - catch (AnnotatedException e) - { - throw new ExtCertPathValidatorException("Policy constraints could not be decoded.", e, certPath, index); - } - if (pc != null) - { - Enumeration policyConstraints = pc.getObjects(); - - while (policyConstraints.hasMoreElements()) - { - ASN1TaggedObject constraint = (ASN1TaggedObject)policyConstraints.nextElement(); - switch (constraint.getTagNo()) - { - case 0: - try - { - tmpInt = ASN1Integer.getInstance(constraint, false).getValue().intValue(); - } - catch (Exception e) - { - throw new ExtCertPathValidatorException( - "Policy constraints requireExplicitPolicy field could not be decoded.", e, certPath, - index); - } - if (tmpInt == 0) - { - return 0; - } - break; - } - } - } - return explicitPolicy; - } - - protected static void wrapupCertF( - CertPath certPath, - int index, - List pathCheckers, - Set criticalExtensions) - throws CertPathValidatorException - { - List certs = certPath.getCertificates(); - X509Certificate cert = (X509Certificate)certs.get(index); - Iterator tmpIter; - tmpIter = pathCheckers.iterator(); - while (tmpIter.hasNext()) - { - try - { - ((PKIXCertPathChecker)tmpIter.next()).check(cert, criticalExtensions); - } - catch (CertPathValidatorException e) - { - throw new ExtCertPathValidatorException("Additional certificate path checker failed.", e, certPath, - index); - } - } - - if (!criticalExtensions.isEmpty()) - { - throw new ExtCertPathValidatorException("Certificate has unsupported critical extension: " + criticalExtensions, null, certPath, - index); - } - } - - protected static PKIXPolicyNode wrapupCertG( - CertPath certPath, - ExtendedPKIXParameters paramsPKIX, - Set userInitialPolicySet, - int index, - List[] policyNodes, - PKIXPolicyNode validPolicyTree, - Set acceptablePolicies) - throws CertPathValidatorException - { - int n = certPath.getCertificates().size(); - // - // (g) - // - PKIXPolicyNode intersection; - - // - // (g) (i) - // - if (validPolicyTree == null) - { - if (paramsPKIX.isExplicitPolicyRequired()) - { - throw new ExtCertPathValidatorException("Explicit policy requested but none available.", null, - certPath, index); - } - intersection = null; - } - else if (CertPathValidatorUtilities.isAnyPolicy(userInitialPolicySet)) // (g) - // (ii) - { - if (paramsPKIX.isExplicitPolicyRequired()) - { - if (acceptablePolicies.isEmpty()) - { - throw new ExtCertPathValidatorException("Explicit policy requested but none available.", null, - certPath, index); - } - else - { - Set _validPolicyNodeSet = new HashSet(); - - for (int j = 0; j < policyNodes.length; j++) - { - List _nodeDepth = policyNodes[j]; - - for (int k = 0; k < _nodeDepth.size(); k++) - { - PKIXPolicyNode _node = (PKIXPolicyNode)_nodeDepth.get(k); - - if (RFC3280CertPathUtilities.ANY_POLICY.equals(_node.getValidPolicy())) - { - Iterator _iter = _node.getChildren(); - while (_iter.hasNext()) - { - _validPolicyNodeSet.add(_iter.next()); - } - } - } - } - - Iterator _vpnsIter = _validPolicyNodeSet.iterator(); - while (_vpnsIter.hasNext()) - { - PKIXPolicyNode _node = (PKIXPolicyNode)_vpnsIter.next(); - String _validPolicy = _node.getValidPolicy(); - - if (!acceptablePolicies.contains(_validPolicy)) - { - // validPolicyTree = - // removePolicyNode(validPolicyTree, policyNodes, - // _node); - } - } - if (validPolicyTree != null) - { - for (int j = (n - 1); j >= 0; j--) - { - List nodes = policyNodes[j]; - - for (int k = 0; k < nodes.size(); k++) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes.get(k); - if (!node.hasChildren()) - { - validPolicyTree = CertPathValidatorUtilities.removePolicyNode(validPolicyTree, - policyNodes, node); - } - } - } - } - } - } - - intersection = validPolicyTree; - } - else - { - // - // (g) (iii) - // - // This implementation is not exactly same as the one described in - // RFC3280. - // However, as far as the validation result is concerned, both - // produce - // adequate result. The only difference is whether AnyPolicy is - // remain - // in the policy tree or not. - // - // (g) (iii) 1 - // - Set _validPolicyNodeSet = new HashSet(); - - for (int j = 0; j < policyNodes.length; j++) - { - List _nodeDepth = policyNodes[j]; - - for (int k = 0; k < _nodeDepth.size(); k++) - { - PKIXPolicyNode _node = (PKIXPolicyNode)_nodeDepth.get(k); - - if (RFC3280CertPathUtilities.ANY_POLICY.equals(_node.getValidPolicy())) - { - Iterator _iter = _node.getChildren(); - while (_iter.hasNext()) - { - PKIXPolicyNode _c_node = (PKIXPolicyNode)_iter.next(); - if (!RFC3280CertPathUtilities.ANY_POLICY.equals(_c_node.getValidPolicy())) - { - _validPolicyNodeSet.add(_c_node); - } - } - } - } - } - - // - // (g) (iii) 2 - // - Iterator _vpnsIter = _validPolicyNodeSet.iterator(); - while (_vpnsIter.hasNext()) - { - PKIXPolicyNode _node = (PKIXPolicyNode)_vpnsIter.next(); - String _validPolicy = _node.getValidPolicy(); - - if (!userInitialPolicySet.contains(_validPolicy)) - { - validPolicyTree = CertPathValidatorUtilities.removePolicyNode(validPolicyTree, policyNodes, _node); - } - } - - // - // (g) (iii) 4 - // - if (validPolicyTree != null) - { - for (int j = (n - 1); j >= 0; j--) - { - List nodes = policyNodes[j]; - - for (int k = 0; k < nodes.size(); k++) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes.get(k); - if (!node.hasChildren()) - { - validPolicyTree = CertPathValidatorUtilities.removePolicyNode(validPolicyTree, policyNodes, - node); - } - } - } - } - - intersection = validPolicyTree; - } - return intersection; - } - -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/X509CRLEntryObject.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/X509CRLEntryObject.java deleted file mode 100644 index dd0a32c96..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/X509CRLEntryObject.java +++ /dev/null @@ -1,293 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.cert.CRLException; -import java.security.cert.X509CRLEntry; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Set; - -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Enumerated; -import org.spongycastle.asn1.util.ASN1Dump; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x509.CRLReason; -import org.spongycastle.asn1.x509.Extension; -import org.spongycastle.asn1.x509.Extensions; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.GeneralNames; -import org.spongycastle.asn1.x509.TBSCertList; -import org.spongycastle.asn1.x509.X509Extension; -import org.spongycastle.x509.extension.X509ExtensionUtil; -import org.spongycastle.jce.X509Principal; - -/** - * The following extensions are listed in RFC 2459 as relevant to CRL Entries - * - * ReasonCode Hode Instruction Code Invalidity Date Certificate Issuer - * (critical) - */ -public class X509CRLEntryObject extends X509CRLEntry -{ - private TBSCertList.CRLEntry c; - - private X500Name certificateIssuer; - private int hashValue; - private boolean isHashValueSet; - - public X509CRLEntryObject(TBSCertList.CRLEntry c) - { - this.c = c; - this.certificateIssuer = null; - } - - /** - * Constructor for CRLEntries of indirect CRLs. If isIndirect - * is false {@link #getCertificateIssuer()} will always - * return null, previousCertificateIssuer is - * ignored. If this isIndirect is specified and this CRLEntry - * has no certificate issuer CRL entry extension - * previousCertificateIssuer is returned by - * {@link #getCertificateIssuer()}. - * - * @param c - * TBSCertList.CRLEntry object. - * @param isIndirect - * true if the corresponding CRL is a indirect - * CRL. - * @param previousCertificateIssuer - * Certificate issuer of the previous CRLEntry. - */ - public X509CRLEntryObject( - TBSCertList.CRLEntry c, - boolean isIndirect, - X500Name previousCertificateIssuer) - { - this.c = c; - this.certificateIssuer = loadCertificateIssuer(isIndirect, previousCertificateIssuer); - } - - /** - * Will return true if any extensions are present and marked as critical as - * we currently don't handle any extensions! - */ - public boolean hasUnsupportedCriticalExtension() - { - Set extns = getCriticalExtensionOIDs(); - - return extns != null && !extns.isEmpty(); - } - - private X500Name loadCertificateIssuer(boolean isIndirect, X500Name previousCertificateIssuer) - { - if (!isIndirect) - { - return null; - } - - byte[] ext = getExtensionValue(X509Extension.certificateIssuer.getId()); - if (ext == null) - { - return previousCertificateIssuer; - } - - try - { - GeneralName[] names = GeneralNames.getInstance( - X509ExtensionUtil.fromExtensionValue(ext)).getNames(); - for (int i = 0; i < names.length; i++) - { - if (names[i].getTagNo() == GeneralName.directoryName) - { - return X500Name.getInstance(names[i].getName()); - } - } - return null; - } - catch (IOException e) - { - return null; - } - } - - X509Principal getCertificateIssuer() - { - if (certificateIssuer == null) - { - return null; - } - try - { - return new X509Principal(certificateIssuer.getEncoded()); - } - catch (Exception e) - { - throw new IllegalStateException(e.toString()); - } - } - private Set getExtensionOIDs(boolean critical) - { - Extensions extensions = c.getExtensions(); - - if (extensions != null) - { - Set set = new HashSet(); - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (critical == ext.isCritical()) - { - set.add(oid.getId()); - } - } - - return set; - } - - return null; - } - - public Set getCriticalExtensionOIDs() - { - return getExtensionOIDs(true); - } - - public Set getNonCriticalExtensionOIDs() - { - return getExtensionOIDs(false); - } - - public byte[] getExtensionValue(String oid) - { - Extensions exts = c.getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new RuntimeException("error encoding " + e.toString()); - } - } - } - - return null; - } - - /** - * Cache the hashCode value - calculating it with the standard method. - * @return calculated hashCode. - */ - public int hashCode() - { - if (!isHashValueSet) - { - hashValue = super.hashCode(); - isHashValueSet = true; - } - - return hashValue; - } - - public byte[] getEncoded() - throws CRLException - { - try - { - return c.getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CRLException(e.toString()); - } - } - - public BigInteger getSerialNumber() - { - return c.getUserCertificate().getValue(); - } - - public Date getRevocationDate() - { - return c.getRevocationDate().getDate(); - } - - public boolean hasExtensions() - { - return c.getExtensions() != null; - } - - public String toString() - { - StringBuffer buf = new StringBuffer(); - String nl = System.getProperty("line.separator"); - - buf.append(" userCertificate: ").append(this.getSerialNumber()).append(nl); - buf.append(" revocationDate: ").append(this.getRevocationDate()).append(nl); - - Extensions extensions = c.getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - if (e.hasMoreElements()) - { - buf.append(" crlEntryExtensions:").append(nl); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - if (ext.getExtnValue() != null) - { - byte[] octs = ext.getExtnValue().getOctets(); - ASN1InputStream dIn = new ASN1InputStream(octs); - buf.append(" critical(").append(ext.isCritical()).append(") "); - try - { - if (oid.equals(X509Extension.reasonCode)) - { - buf.append(CRLReason.getInstance(ASN1Enumerated.getInstance(dIn.readObject()))).append(nl); - } - else if (oid.equals(X509Extension.certificateIssuer)) - { - buf.append("Certificate issuer: ").append(GeneralNames.getInstance(dIn.readObject())).append(nl); - } - else - { - buf.append(oid.getId()); - buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl); - } - } - catch (Exception ex) - { - buf.append(oid.getId()); - buf.append(" value = ").append("*****").append(nl); - } - } - else - { - buf.append(nl); - } - } - } - } - - return buf.toString(); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/X509CRLObject.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/X509CRLObject.java deleted file mode 100644 index 46f9dab5b..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/X509CRLObject.java +++ /dev/null @@ -1,556 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Principal; -import java.security.PublicKey; -import java.security.Signature; -import java.security.SignatureException; -import java.security.cert.CRLException; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509CRL; -import java.security.cert.X509CRLEntry; -import java.security.cert.X509Certificate; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.util.ASN1Dump; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x509.CRLDistPoint; -import org.spongycastle.asn1.x509.CRLNumber; -import org.spongycastle.asn1.x509.CertificateList; -import org.spongycastle.asn1.x509.Extension; -import org.spongycastle.asn1.x509.Extensions; -import org.spongycastle.asn1.x509.GeneralNames; -import org.spongycastle.asn1.x509.IssuingDistributionPoint; -import org.spongycastle.asn1.x509.TBSCertList; -import org.spongycastle.jce.X509Principal; -import org.spongycastle.jce.provider.RFC3280CertPathUtilities; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.util.encoders.Hex; -import org.spongycastle.x509.extension.X509ExtensionUtil; - -/** - * The following extensions are listed in RFC 2459 as relevant to CRLs - * - * Authority Key Identifier - * Issuer Alternative Name - * CRL Number - * Delta CRL Indicator (critical) - * Issuing Distribution Point (critical) - */ -public class X509CRLObject - extends X509CRL -{ - private CertificateList c; - private String sigAlgName; - private byte[] sigAlgParams; - private boolean isIndirect; - - static boolean isIndirectCRL(X509CRL crl) - throws CRLException - { - try - { - byte[] idp = crl.getExtensionValue(Extension.issuingDistributionPoint.getId()); - return idp != null - && IssuingDistributionPoint.getInstance(X509ExtensionUtil.fromExtensionValue(idp)).isIndirectCRL(); - } - catch (Exception e) - { - throw new ExtCRLException( - "Exception reading IssuingDistributionPoint", e); - } - } - - public X509CRLObject( - CertificateList c) - throws CRLException - { - this.c = c; - - try - { - this.sigAlgName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm()); - - if (c.getSignatureAlgorithm().getParameters() != null) - { - this.sigAlgParams = ((ASN1Encodable)c.getSignatureAlgorithm().getParameters()).toASN1Primitive().getEncoded(ASN1Encoding.DER); - } - else - { - this.sigAlgParams = null; - } - - this.isIndirect = isIndirectCRL(this); - } - catch (Exception e) - { - throw new CRLException("CRL contents invalid: " + e); - } - } - - /** - * Will return true if any extensions are present and marked - * as critical as we currently dont handle any extensions! - */ - public boolean hasUnsupportedCriticalExtension() - { - Set extns = getCriticalExtensionOIDs(); - - if (extns == null) - { - return false; - } - - extns.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT); - extns.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR); - - return !extns.isEmpty(); - } - - private Set getExtensionOIDs(boolean critical) - { - if (this.getVersion() == 2) - { - Extensions extensions = c.getTBSCertList().getExtensions(); - - if (extensions != null) - { - Set set = new HashSet(); - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (critical == ext.isCritical()) - { - set.add(oid.getId()); - } - } - - return set; - } - } - - return null; - } - - public Set getCriticalExtensionOIDs() - { - return getExtensionOIDs(true); - } - - public Set getNonCriticalExtensionOIDs() - { - return getExtensionOIDs(false); - } - - public byte[] getExtensionValue(String oid) - { - Extensions exts = c.getTBSCertList().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - } - - return null; - } - - public byte[] getEncoded() - throws CRLException - { - try - { - return c.getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CRLException(e.toString()); - } - } - - public void verify(PublicKey key) - throws CRLException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - verify(key, BouncyCastleProvider.PROVIDER_NAME); - } - - public void verify(PublicKey key, String sigProvider) - throws CRLException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - if (!c.getSignatureAlgorithm().equals(c.getTBSCertList().getSignature())) - { - throw new CRLException("Signature algorithm on CertificateList does not match TBSCertList."); - } - - Signature sig; - - if (sigProvider != null) - { - sig = Signature.getInstance(getSigAlgName(), sigProvider); - } - else - { - sig = Signature.getInstance(getSigAlgName()); - } - - sig.initVerify(key); - sig.update(this.getTBSCertList()); - - if (!sig.verify(this.getSignature())) - { - throw new SignatureException("CRL does not verify with supplied public key."); - } - } - - public int getVersion() - { - return c.getVersionNumber(); - } - - public Principal getIssuerDN() - { - return new X509Principal(X500Name.getInstance(c.getIssuer().toASN1Primitive())); - } - - public Date getThisUpdate() - { - return c.getThisUpdate().getDate(); - } - - public Date getNextUpdate() - { - if (c.getNextUpdate() != null) - { - return c.getNextUpdate().getDate(); - } - - return null; - } - - private Set loadCRLEntries() - { - Set entrySet = new HashSet(); - Enumeration certs = c.getRevokedCertificateEnumeration(); - - X500Name previousCertificateIssuer = c.getIssuer(); - while (certs.hasMoreElements()) - { - TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)certs.nextElement(); - X509CRLEntryObject crlEntry = new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer); - entrySet.add(crlEntry); - if (isIndirect && entry.hasExtensions()) - { - Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); - - if (currentCaName != null) - { - previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); - } - } - } - - return entrySet; - } - - public X509CRLEntry getRevokedCertificate(BigInteger serialNumber) - { - Enumeration certs = c.getRevokedCertificateEnumeration(); - - X500Name previousCertificateIssuer = c.getIssuer(); - while (certs.hasMoreElements()) - { - TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)certs.nextElement(); - - if (serialNumber.equals(entry.getUserCertificate().getValue())) - { - return new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer); - } - - if (isIndirect && entry.hasExtensions()) - { - Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); - - if (currentCaName != null) - { - previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); - } - } - } - - return null; - } - - public Set getRevokedCertificates() - { - Set entrySet = loadCRLEntries(); - - if (!entrySet.isEmpty()) - { - return Collections.unmodifiableSet(entrySet); - } - - return null; - } - - public byte[] getTBSCertList() - throws CRLException - { - try - { - return c.getTBSCertList().getEncoded("DER"); - } - catch (IOException e) - { - throw new CRLException(e.toString()); - } - } - - public byte[] getSignature() - { - return c.getSignature().getBytes(); - } - - public String getSigAlgName() - { - return sigAlgName; - } - - public String getSigAlgOID() - { - return c.getSignatureAlgorithm().getAlgorithm().getId(); - } - - public byte[] getSigAlgParams() - { - if (sigAlgParams != null) - { - byte[] tmp = new byte[sigAlgParams.length]; - - System.arraycopy(sigAlgParams, 0, tmp, 0, tmp.length); - - return tmp; - } - - return null; - } - - /** - * Returns a string representation of this CRL. - * - * @return a string representation of this CRL. - */ - public String toString() - { - StringBuffer buf = new StringBuffer(); - String nl = System.getProperty("line.separator"); - - buf.append(" Version: ").append(this.getVersion()).append( - nl); - buf.append(" IssuerDN: ").append(this.getIssuerDN()) - .append(nl); - buf.append(" This update: ").append(this.getThisUpdate()) - .append(nl); - buf.append(" Next update: ").append(this.getNextUpdate()) - .append(nl); - buf.append(" Signature Algorithm: ").append(this.getSigAlgName()) - .append(nl); - - byte[] sig = this.getSignature(); - - buf.append(" Signature: ").append( - new String(Hex.encode(sig, 0, 20))).append(nl); - for (int i = 20; i < sig.length; i += 20) - { - if (i < sig.length - 20) - { - buf.append(" ").append( - new String(Hex.encode(sig, i, 20))).append(nl); - } - else - { - buf.append(" ").append( - new String(Hex.encode(sig, i, sig.length - i))).append(nl); - } - } - - Extensions extensions = c.getTBSCertList().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - if (e.hasMoreElements()) - { - buf.append(" Extensions: ").append(nl); - } - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (ext.getExtnValue() != null) - { - byte[] octs = ext.getExtnValue().getOctets(); - ASN1InputStream dIn = new ASN1InputStream(octs); - buf.append(" critical(").append( - ext.isCritical()).append(") "); - try - { - if (oid.equals(Extension.cRLNumber)) - { - buf.append( - new CRLNumber(ASN1Integer.getInstance( - dIn.readObject()).getPositiveValue())) - .append(nl); - } - else if (oid.equals(Extension.deltaCRLIndicator)) - { - buf.append( - "Base CRL: " - + new CRLNumber(ASN1Integer.getInstance( - dIn.readObject()).getPositiveValue())) - .append(nl); - } - else if (oid - .equals(Extension.issuingDistributionPoint)) - { - buf.append( - IssuingDistributionPoint.getInstance(dIn.readObject())).append(nl); - } - else if (oid - .equals(Extension.cRLDistributionPoints)) - { - buf.append( - CRLDistPoint.getInstance(dIn.readObject())).append(nl); - } - else if (oid.equals(Extension.freshestCRL)) - { - buf.append( - CRLDistPoint.getInstance(dIn.readObject())).append(nl); - } - else - { - buf.append(oid.getId()); - buf.append(" value = ").append( - ASN1Dump.dumpAsString(dIn.readObject())) - .append(nl); - } - } - catch (Exception ex) - { - buf.append(oid.getId()); - buf.append(" value = ").append("*****").append(nl); - } - } - else - { - buf.append(nl); - } - } - } - Set set = getRevokedCertificates(); - if (set != null) - { - Iterator it = set.iterator(); - while (it.hasNext()) - { - buf.append(it.next()); - buf.append(nl); - } - } - return buf.toString(); - } - - /** - * Checks whether the given certificate is on this CRL. - * - * @param cert the certificate to check for. - * @return true if the given certificate is on this CRL, - * false otherwise. - */ - public boolean isRevoked(Certificate cert) - { - if (!cert.getType().equals("X.509")) - { - throw new RuntimeException("X.509 CRL used with non X.509 Cert"); - } - - TBSCertList.CRLEntry[] certs = c.getRevokedCertificates(); - - X500Name caName = c.getIssuer(); - - if (certs != null) - { - BigInteger serial = ((X509Certificate)cert).getSerialNumber(); - - for (int i = 0; i < certs.length; i++) - { - if (isIndirect && certs[i].hasExtensions()) - { - Extension currentCaName = certs[i].getExtensions().getExtension(Extension.certificateIssuer); - - if (currentCaName != null) - { - caName = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); - } - } - - if (certs[i].getUserCertificate().getValue().equals(serial)) - { - X500Name issuer; - - try - { - issuer = org.spongycastle.asn1.x509.Certificate.getInstance(cert.getEncoded()).getIssuer(); - } - catch (CertificateEncodingException e) - { - throw new RuntimeException("Cannot process certificate"); - } - - if (!caName.equals(issuer)) - { - return false; - } - - return true; - } - } - } - - return false; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/X509CertificateObject.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/X509CertificateObject.java deleted file mode 100644 index 74b9c6115..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/provider/X509CertificateObject.java +++ /dev/null @@ -1,858 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.Principal; -import java.security.Provider; -import java.security.PublicKey; -import java.security.Security; -import java.security.Signature; -import java.security.SignatureException; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1OutputStream; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1String; -import org.spongycastle.asn1.DERBitString; -import org.spongycastle.asn1.DERIA5String; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.misc.MiscObjectIdentifiers; -import org.spongycastle.asn1.misc.NetscapeCertType; -import org.spongycastle.asn1.misc.NetscapeRevocationURL; -import org.spongycastle.asn1.misc.VerisignCzagExtension; -import org.spongycastle.asn1.util.ASN1Dump; -import org.spongycastle.asn1.x500.X500Name; -import org.spongycastle.asn1.x500.style.RFC4519Style; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.BasicConstraints; -import org.spongycastle.asn1.x509.Extension; -import org.spongycastle.asn1.x509.Extensions; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.KeyUsage; -import org.spongycastle.jcajce.provider.asymmetric.util.PKCS12BagAttributeCarrierImpl; -import org.spongycastle.jce.X509Principal; -import org.spongycastle.jce.provider.RFC3280CertPathUtilities; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.jce.interfaces.PKCS12BagAttributeCarrier; -import org.spongycastle.util.Arrays; -import org.spongycastle.util.Integers; -import org.spongycastle.util.encoders.Hex; - -public class X509CertificateObject - extends X509Certificate - implements PKCS12BagAttributeCarrier -{ - private org.spongycastle.asn1.x509.Certificate c; - private BasicConstraints basicConstraints; - private boolean[] keyUsage; - private boolean hashValueSet; - private int hashValue; - - private PKCS12BagAttributeCarrier attrCarrier = new PKCS12BagAttributeCarrierImpl(); - - public X509CertificateObject( - org.spongycastle.asn1.x509.Certificate c) - throws CertificateParsingException - { - this.c = c; - - try - { - byte[] bytes = this.getExtensionBytes("2.5.29.19"); - - if (bytes != null) - { - basicConstraints = BasicConstraints.getInstance(ASN1Primitive.fromByteArray(bytes)); - } - } - catch (Exception e) - { - throw new CertificateParsingException("cannot construct BasicConstraints: " + e); - } - - try - { - byte[] bytes = this.getExtensionBytes("2.5.29.15"); - if (bytes != null) - { - DERBitString bits = DERBitString.getInstance(ASN1Primitive.fromByteArray(bytes)); - - bytes = bits.getBytes(); - int length = (bytes.length * 8) - bits.getPadBits(); - - keyUsage = new boolean[(length < 9) ? 9 : length]; - - for (int i = 0; i != length; i++) - { - keyUsage[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0; - } - } - else - { - keyUsage = null; - } - } - catch (Exception e) - { - throw new CertificateParsingException("cannot construct KeyUsage: " + e); - } - } - - public void checkValidity() - throws CertificateExpiredException, CertificateNotYetValidException - { - this.checkValidity(new Date()); - } - - public void checkValidity( - Date date) - throws CertificateExpiredException, CertificateNotYetValidException - { - if (date.getTime() > this.getNotAfter().getTime()) // for other VM compatibility - { - throw new CertificateExpiredException("certificate expired on " + c.getEndDate().getTime()); - } - - if (date.getTime() < this.getNotBefore().getTime()) - { - throw new CertificateNotYetValidException("certificate not valid till " + c.getStartDate().getTime()); - } - } - - public int getVersion() - { - return c.getVersionNumber(); - } - - public BigInteger getSerialNumber() - { - return c.getSerialNumber().getValue(); - } - - public Principal getIssuerDN() - { - try - { - return new X509Principal(X500Name.getInstance(c.getIssuer().getEncoded())); - } - catch (IOException e) - { - return null; - } - } - - public Principal getSubjectDN() - { - return new X509Principal(X500Name.getInstance(c.getSubject().toASN1Primitive())); - } - - public Date getNotBefore() - { - return c.getStartDate().getDate(); - } - - public Date getNotAfter() - { - return c.getEndDate().getDate(); - } - - public byte[] getTBSCertificate() - throws CertificateEncodingException - { - try - { - return c.getTBSCertificate().getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CertificateEncodingException(e.toString()); - } - } - - public byte[] getSignature() - { - return c.getSignature().getBytes(); - } - - /** - * return a more "meaningful" representation for the signature algorithm used in - * the certficate. - */ - public String getSigAlgName() - { - Provider prov = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME); - - if (prov != null) - { - String algName = prov.getProperty("Alg.Alias.Signature." + this.getSigAlgOID()); - - if (algName != null) - { - return algName; - } - } - - Provider[] provs = Security.getProviders(); - - // - // search every provider looking for a real algorithm - // - for (int i = 0; i != provs.length; i++) - { - String algName = provs[i].getProperty("Alg.Alias.Signature." + this.getSigAlgOID()); - if (algName != null) - { - return algName; - } - } - - return this.getSigAlgOID(); - } - - /** - * return the object identifier for the signature. - */ - public String getSigAlgOID() - { - return c.getSignatureAlgorithm().getAlgorithm().getId(); - } - - /** - * return the signature parameters, or null if there aren't any. - */ - public byte[] getSigAlgParams() - { - if (c.getSignatureAlgorithm().getParameters() != null) - { - try - { - return c.getSignatureAlgorithm().getParameters().toASN1Primitive().getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - return null; - } - } - else - { - return null; - } - } - - public boolean[] getIssuerUniqueID() - { - DERBitString id = c.getTBSCertificate().getIssuerUniqueId(); - - if (id != null) - { - byte[] bytes = id.getBytes(); - boolean[] boolId = new boolean[bytes.length * 8 - id.getPadBits()]; - - for (int i = 0; i != boolId.length; i++) - { - boolId[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0; - } - - return boolId; - } - - return null; - } - - public boolean[] getSubjectUniqueID() - { - DERBitString id = c.getTBSCertificate().getSubjectUniqueId(); - - if (id != null) - { - byte[] bytes = id.getBytes(); - boolean[] boolId = new boolean[bytes.length * 8 - id.getPadBits()]; - - for (int i = 0; i != boolId.length; i++) - { - boolId[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0; - } - - return boolId; - } - - return null; - } - - public boolean[] getKeyUsage() - { - return keyUsage; - } - - public List getExtendedKeyUsage() - throws CertificateParsingException - { - byte[] bytes = this.getExtensionBytes("2.5.29.37"); - - if (bytes != null) - { - try - { - ASN1InputStream dIn = new ASN1InputStream(bytes); - ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); - List list = new ArrayList(); - - for (int i = 0; i != seq.size(); i++) - { - list.add(((ASN1ObjectIdentifier)seq.getObjectAt(i)).getId()); - } - - return Collections.unmodifiableList(list); - } - catch (Exception e) - { - throw new CertificateParsingException("error processing extended key usage extension"); - } - } - - return null; - } - - public int getBasicConstraints() - { - if (basicConstraints != null) - { - if (basicConstraints.isCA()) - { - if (basicConstraints.getPathLenConstraint() == null) - { - return Integer.MAX_VALUE; - } - else - { - return basicConstraints.getPathLenConstraint().intValue(); - } - } - else - { - return -1; - } - } - - return -1; - } - - public Collection getSubjectAlternativeNames() - throws CertificateParsingException - { - return getAlternativeNames(getExtensionBytes(Extension.subjectAlternativeName.getId())); - } - - public Collection getIssuerAlternativeNames() - throws CertificateParsingException - { - return getAlternativeNames(getExtensionBytes(Extension.issuerAlternativeName.getId())); - } - - public Set getCriticalExtensionOIDs() - { - if (this.getVersion() == 3) - { - Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (ext.isCritical()) - { - set.add(oid.getId()); - } - } - - return set; - } - } - - return null; - } - - private byte[] getExtensionBytes(String oid) - { - Extensions exts = c.getTBSCertificate().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - if (ext != null) - { - return ext.getExtnValue().getOctets(); - } - } - - return null; - } - - public byte[] getExtensionValue(String oid) - { - Extensions exts = c.getTBSCertificate().getExtensions(); - - if (exts != null) - { - Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); - - if (ext != null) - { - try - { - return ext.getExtnValue().getEncoded(); - } - catch (Exception e) - { - throw new IllegalStateException("error parsing " + e.toString()); - } - } - } - - return null; - } - - public Set getNonCriticalExtensionOIDs() - { - if (this.getVersion() == 3) - { - Set set = new HashSet(); - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (!ext.isCritical()) - { - set.add(oid.getId()); - } - } - - return set; - } - } - - return null; - } - - public boolean hasUnsupportedCriticalExtension() - { - if (this.getVersion() == 3) - { - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - String oidId = oid.getId(); - - if (oidId.equals(RFC3280CertPathUtilities.KEY_USAGE) - || oidId.equals(RFC3280CertPathUtilities.CERTIFICATE_POLICIES) - || oidId.equals(RFC3280CertPathUtilities.POLICY_MAPPINGS) - || oidId.equals(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY) - || oidId.equals(RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS) - || oidId.equals(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT) - || oidId.equals(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR) - || oidId.equals(RFC3280CertPathUtilities.POLICY_CONSTRAINTS) - || oidId.equals(RFC3280CertPathUtilities.BASIC_CONSTRAINTS) - || oidId.equals(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME) - || oidId.equals(RFC3280CertPathUtilities.NAME_CONSTRAINTS)) - { - continue; - } - - Extension ext = extensions.getExtension(oid); - - if (ext.isCritical()) - { - return true; - } - } - } - } - - return false; - } - - public PublicKey getPublicKey() - { - try - { - return BouncyCastleProvider.getPublicKey(c.getSubjectPublicKeyInfo()); - } - catch (IOException e) - { - return null; // should never happen... - } - } - - public byte[] getEncoded() - throws CertificateEncodingException - { - try - { - return c.getEncoded(ASN1Encoding.DER); - } - catch (IOException e) - { - throw new CertificateEncodingException(e.toString()); - } - } - - public boolean equals( - Object o) - { - if (o == this) - { - return true; - } - - if (!(o instanceof Certificate)) - { - return false; - } - - Certificate other = (Certificate)o; - - try - { - byte[] b1 = this.getEncoded(); - byte[] b2 = other.getEncoded(); - - return Arrays.areEqual(b1, b2); - } - catch (CertificateEncodingException e) - { - return false; - } - } - - public synchronized int hashCode() - { - if (!hashValueSet) - { - hashValue = calculateHashCode(); - hashValueSet = true; - } - - return hashValue; - } - - private int calculateHashCode() - { - try - { - int hashCode = 0; - byte[] certData = this.getEncoded(); - for (int i = 1; i < certData.length; i++) - { - hashCode += certData[i] * i; - } - return hashCode; - } - catch (CertificateEncodingException e) - { - return 0; - } - } - - public void setBagAttribute( - ASN1ObjectIdentifier oid, - ASN1Encodable attribute) - { - attrCarrier.setBagAttribute(oid, attribute); - } - - public ASN1Encodable getBagAttribute( - ASN1ObjectIdentifier oid) - { - return attrCarrier.getBagAttribute(oid); - } - - public Enumeration getBagAttributeKeys() - { - return attrCarrier.getBagAttributeKeys(); - } - - public String toString() - { - StringBuffer buf = new StringBuffer(); - String nl = System.getProperty("line.separator"); - - buf.append(" [0] Version: ").append(this.getVersion()).append(nl); - buf.append(" SerialNumber: ").append(this.getSerialNumber()).append(nl); - buf.append(" IssuerDN: ").append(this.getIssuerDN()).append(nl); - buf.append(" Start Date: ").append(this.getNotBefore()).append(nl); - buf.append(" Final Date: ").append(this.getNotAfter()).append(nl); - buf.append(" SubjectDN: ").append(this.getSubjectDN()).append(nl); - buf.append(" Public Key: ").append(this.getPublicKey()).append(nl); - buf.append(" Signature Algorithm: ").append(this.getSigAlgName()).append(nl); - - byte[] sig = this.getSignature(); - - buf.append(" Signature: ").append(new String(Hex.encode(sig, 0, 20))).append(nl); - for (int i = 20; i < sig.length; i += 20) - { - if (i < sig.length - 20) - { - buf.append(" ").append(new String(Hex.encode(sig, i, 20))).append(nl); - } - else - { - buf.append(" ").append(new String(Hex.encode(sig, i, sig.length - i))).append(nl); - } - } - - Extensions extensions = c.getTBSCertificate().getExtensions(); - - if (extensions != null) - { - Enumeration e = extensions.oids(); - - if (e.hasMoreElements()) - { - buf.append(" Extensions: \n"); - } - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - Extension ext = extensions.getExtension(oid); - - if (ext.getExtnValue() != null) - { - byte[] octs = ext.getExtnValue().getOctets(); - ASN1InputStream dIn = new ASN1InputStream(octs); - buf.append(" critical(").append(ext.isCritical()).append(") "); - try - { - if (oid.equals(Extension.basicConstraints)) - { - buf.append(BasicConstraints.getInstance(dIn.readObject())).append(nl); - } - else if (oid.equals(Extension.keyUsage)) - { - buf.append(KeyUsage.getInstance(dIn.readObject())).append(nl); - } - else if (oid.equals(MiscObjectIdentifiers.netscapeCertType)) - { - buf.append(new NetscapeCertType((DERBitString)dIn.readObject())).append(nl); - } - else if (oid.equals(MiscObjectIdentifiers.netscapeRevocationURL)) - { - buf.append(new NetscapeRevocationURL((DERIA5String)dIn.readObject())).append(nl); - } - else if (oid.equals(MiscObjectIdentifiers.verisignCzagExtension)) - { - buf.append(new VerisignCzagExtension((DERIA5String)dIn.readObject())).append(nl); - } - else - { - buf.append(oid.getId()); - buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl); - //buf.append(" value = ").append("*****").append(nl); - } - } - catch (Exception ex) - { - buf.append(oid.getId()); - // buf.append(" value = ").append(new String(Hex.encode(ext.getExtnValue().getOctets()))).append(nl); - buf.append(" value = ").append("*****").append(nl); - } - } - else - { - buf.append(nl); - } - } - } - - return buf.toString(); - } - - public final void verify( - PublicKey key) - throws CertificateException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - Signature signature; - String sigName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm()); - - try - { - signature = Signature.getInstance(sigName, BouncyCastleProvider.PROVIDER_NAME); - } - catch (Exception e) - { - signature = Signature.getInstance(sigName); - } - - checkSignature(key, signature); - } - - public final void verify( - PublicKey key, - String sigProvider) - throws CertificateException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException - { - String sigName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm()); - Signature signature = Signature.getInstance(sigName, sigProvider); - - checkSignature(key, signature); - } - - private void checkSignature( - PublicKey key, - Signature signature) - throws CertificateException, NoSuchAlgorithmException, - SignatureException, InvalidKeyException - { - if (!isAlgIdEqual(c.getSignatureAlgorithm(), c.getTBSCertificate().getSignature())) - { - throw new CertificateException("signature algorithm in TBS cert not same as outer cert"); - } - - ASN1Encodable params = c.getSignatureAlgorithm().getParameters(); - - // TODO This should go after the initVerify? - X509SignatureUtil.setSignatureParameters(signature, params); - - signature.initVerify(key); - - signature.update(this.getTBSCertificate()); - - if (!signature.verify(this.getSignature())) - { - throw new SignatureException("certificate does not verify with supplied key"); - } - } - - private boolean isAlgIdEqual(AlgorithmIdentifier id1, AlgorithmIdentifier id2) - { - if (!id1.getAlgorithm().equals(id2.getAlgorithm())) - { - return false; - } - - if (id1.getParameters() == null) - { - if (id2.getParameters() != null && !id2.getParameters().equals(DERNull.INSTANCE)) - { - return false; - } - - return true; - } - - if (id2.getParameters() == null) - { - if (id1.getParameters() != null && !id1.getParameters().equals(DERNull.INSTANCE)) - { - return false; - } - - return true; - } - - return id1.getParameters().equals(id2.getParameters()); - } - - private static Collection getAlternativeNames(byte[] extVal) - throws CertificateParsingException - { - if (extVal == null) - { - return null; - } - try - { - Collection temp = new ArrayList(); - Enumeration it = ASN1Sequence.getInstance(extVal).getObjects(); - while (it.hasMoreElements()) - { - GeneralName genName = GeneralName.getInstance(it.nextElement()); - List list = new ArrayList(); - list.add(Integers.valueOf(genName.getTagNo())); - switch (genName.getTagNo()) - { - case GeneralName.ediPartyName: - case GeneralName.x400Address: - case GeneralName.otherName: - list.add(genName.getEncoded()); - break; - case GeneralName.directoryName: - list.add(X500Name.getInstance(RFC4519Style.INSTANCE, genName.getName()).toString()); - break; - case GeneralName.dNSName: - case GeneralName.rfc822Name: - case GeneralName.uniformResourceIdentifier: - list.add(((ASN1String)genName.getName()).getString()); - break; - case GeneralName.registeredID: - list.add(ASN1ObjectIdentifier.getInstance(genName.getName()).getId()); - break; - case GeneralName.iPAddress: - byte[] addrBytes = DEROctetString.getInstance(genName.getName()).getOctets(); - list.add(addrBytes); - break; - default: - throw new IOException("Bad tag number: " + genName.getTagNo()); - } - - temp.add(list); - } - if (temp.size() == 0) - { - return null; - } - return Collections.unmodifiableCollection(temp); - } - catch (Exception e) - { - throw new CertificateParsingException(e.getMessage()); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/spec/PSSParameterSpec.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/spec/PSSParameterSpec.java deleted file mode 100644 index 0711e29c8..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/jce/spec/PSSParameterSpec.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.spongycastle.jce.spec; - -/** - * This class specifies a parameter spec for RSA PSS encoding scheme, - * as defined in the PKCS#1 v2.1. - * - * @see java.security.spec.AlgorithmParameterSpec - * @see java.security.Signature - */ -public class PSSParameterSpec - extends Object - implements java.security.spec.AlgorithmParameterSpec -{ - private int saltLen; - - /** - * Creates a new PSSParameterSpec given the salt length as defined - * in PKCS#1. - * - * @param saltLen - the length of salt in bits to be used in PKCS#1 - * PSS encoding. - * @throws IllegalArgumentException - if saltLen is less than 0. - */ - public PSSParameterSpec(int saltLen) - { - if (saltLen < 0) - { - throw new IllegalArgumentException("Salt length must be >= 0"); - } - - this.saltLen = saltLen; - } - - /** - * Returns the salt length in bits. - * - * @returns the salt length. - */ - public int getSaltLength() - { - return saltLen; - } -} - diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/AttributeCertificateHolder.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/AttributeCertificateHolder.java deleted file mode 100644 index 5b161b4de..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/AttributeCertificateHolder.java +++ /dev/null @@ -1,406 +0,0 @@ -package org.spongycastle.x509; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.Principal; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.GeneralNames; -import org.spongycastle.asn1.x509.Holder; -import org.spongycastle.asn1.x509.IssuerSerial; -import org.spongycastle.asn1.x509.ObjectDigestInfo; -import org.spongycastle.jce.PrincipalUtil; -import org.spongycastle.jce.X509Principal; -import org.spongycastle.jce.cert.CertSelector; -import org.spongycastle.util.Arrays; -import org.spongycastle.util.Selector; - -/** - * The Holder object. - * - *
- *          Holder ::= SEQUENCE {
- *                baseCertificateID   [0] IssuerSerial OPTIONAL,
- *                         -- the issuer and serial number of
- *                         -- the holder's Public Key Certificate
- *                entityName          [1] GeneralNames OPTIONAL,
- *                         -- the name of the claimant or role
- *                objectDigestInfo    [2] ObjectDigestInfo OPTIONAL
- *                         -- used to directly authenticate the holder,
- *                         -- for example, an executable
- *          }
- * 
- * @deprecated use org.spongycastle.cert.AttributeCertificateHolder - */ -public class AttributeCertificateHolder - implements CertSelector, Selector -{ - final Holder holder; - - AttributeCertificateHolder(ASN1Sequence seq) - { - holder = Holder.getInstance(seq); - } - - public AttributeCertificateHolder(X509Principal issuerName, - BigInteger serialNumber) - { - holder = new org.spongycastle.asn1.x509.Holder(new IssuerSerial( - new GeneralNames(new GeneralName(issuerName)), - new ASN1Integer(serialNumber))); - } - - public AttributeCertificateHolder(X509Certificate cert) - throws CertificateParsingException - { - X509Principal name; - - try - { - name = PrincipalUtil.getIssuerX509Principal(cert); - } - catch (Exception e) - { - throw new CertificateParsingException(e.getMessage()); - } - - holder = new Holder(new IssuerSerial(generateGeneralNames(name), - new ASN1Integer(cert.getSerialNumber()))); - } - - public AttributeCertificateHolder(X509Principal principal) - { - holder = new Holder(generateGeneralNames(principal)); - } - - /** - * Constructs a holder for v2 attribute certificates with a hash value for - * some type of object. - *

- * digestedObjectType can be one of the following: - *

    - *
  • 0 - publicKey - A hash of the public key of the holder must be - * passed. - *
  • 1 - publicKeyCert - A hash of the public key certificate of the - * holder must be passed. - *
  • 2 - otherObjectDigest - A hash of some other object type must be - * passed. otherObjectTypeID must not be empty. - *
- *

- * This cannot be used if a v1 attribute certificate is used. - * - * @param digestedObjectType The digest object type. - * @param digestAlgorithm The algorithm identifier for the hash. - * @param otherObjectTypeID The object type ID if - * digestedObjectType is - * otherObjectDigest. - * @param objectDigest The hash value. - */ - public AttributeCertificateHolder(int digestedObjectType, - String digestAlgorithm, String otherObjectTypeID, byte[] objectDigest) - { - holder = new Holder(new ObjectDigestInfo(digestedObjectType, - new ASN1ObjectIdentifier(otherObjectTypeID), new AlgorithmIdentifier(digestAlgorithm), Arrays - .clone(objectDigest))); - } - - /** - * Returns the digest object type if an object digest info is used. - *

- *

    - *
  • 0 - publicKey - A hash of the public key of the holder must be - * passed. - *
  • 1 - publicKeyCert - A hash of the public key certificate of the - * holder must be passed. - *
  • 2 - otherObjectDigest - A hash of some other object type must be - * passed. otherObjectTypeID must not be empty. - *
- * - * @return The digest object type or -1 if no object digest info is set. - */ - public int getDigestedObjectType() - { - if (holder.getObjectDigestInfo() != null) - { - return holder.getObjectDigestInfo().getDigestedObjectType() - .getValue().intValue(); - } - return -1; - } - - /** - * Returns the other object type ID if an object digest info is used. - * - * @return The other object type ID or null if no object - * digest info is set. - */ - public String getDigestAlgorithm() - { - if (holder.getObjectDigestInfo() != null) - { - return holder.getObjectDigestInfo().getDigestAlgorithm().getObjectId() - .getId(); - } - return null; - } - - /** - * Returns the hash if an object digest info is used. - * - * @return The hash or null if no object digest info is set. - */ - public byte[] getObjectDigest() - { - if (holder.getObjectDigestInfo() != null) - { - return holder.getObjectDigestInfo().getObjectDigest().getBytes(); - } - return null; - } - - /** - * Returns the digest algorithm ID if an object digest info is used. - * - * @return The digest algorithm ID or null if no object - * digest info is set. - */ - public String getOtherObjectTypeID() - { - if (holder.getObjectDigestInfo() != null) - { - holder.getObjectDigestInfo().getOtherObjectTypeID().getId(); - } - return null; - } - - private GeneralNames generateGeneralNames(X509Principal principal) - { - return new GeneralNames(new GeneralName(principal)); - } - - private boolean matchesDN(X509Principal subject, GeneralNames targets) - { - GeneralName[] names = targets.getNames(); - - for (int i = 0; i != names.length; i++) - { - GeneralName gn = names[i]; - - if (gn.getTagNo() == GeneralName.directoryName) - { - try - { - if (new X509Principal(((ASN1Encodable)gn.getName()).toASN1Primitive() - .getEncoded()).equals(subject)) - { - return true; - } - } - catch (IOException e) - { - } - } - } - - return false; - } - - private Object[] getNames(GeneralName[] names) - { - List l = new ArrayList(names.length); - - for (int i = 0; i != names.length; i++) - { - if (names[i].getTagNo() == GeneralName.directoryName) - { - try - { - l.add(new X509Principal( - ((ASN1Encodable)names[i].getName()).toASN1Primitive().getEncoded())); - } - catch (IOException e) - { - throw new RuntimeException("badly formed Name object"); - } - } - } - - return l.toArray(new Object[l.size()]); - } - - private Principal[] getPrincipals(GeneralNames names) - { - Object[] p = this.getNames(names.getNames()); - List l = new ArrayList(); - - for (int i = 0; i != p.length; i++) - { - if (p[i] instanceof Principal) - { - l.add(p[i]); - } - } - - return (Principal[])l.toArray(new Principal[l.size()]); - } - - /** - * Return any principal objects inside the attribute certificate holder - * entity names field. - * - * @return an array of Principal objects (usually X509Principal), null if no - * entity names field is set. - */ - public Principal[] getEntityNames() - { - if (holder.getEntityName() != null) - { - return getPrincipals(holder.getEntityName()); - } - - return null; - } - - /** - * Return the principals associated with the issuer attached to this holder - * - * @return an array of principals, null if no BaseCertificateID is set. - */ - public Principal[] getIssuer() - { - if (holder.getBaseCertificateID() != null) - { - return getPrincipals(holder.getBaseCertificateID().getIssuer()); - } - - return null; - } - - /** - * Return the serial number associated with the issuer attached to this - * holder. - * - * @return the certificate serial number, null if no BaseCertificateID is - * set. - */ - public BigInteger getSerialNumber() - { - if (holder.getBaseCertificateID() != null) - { - return holder.getBaseCertificateID().getSerial().getValue(); - } - - return null; - } - - public Object clone() - { - return new AttributeCertificateHolder((ASN1Sequence)holder - .toASN1Object()); - } - - public boolean match(Certificate cert) - { - if (!(cert instanceof X509Certificate)) - { - return false; - } - - X509Certificate x509Cert = (X509Certificate)cert; - - try - { - if (holder.getBaseCertificateID() != null) - { - return holder.getBaseCertificateID().getSerial().getValue().equals(x509Cert.getSerialNumber()) - && matchesDN(PrincipalUtil.getIssuerX509Principal(x509Cert), holder.getBaseCertificateID().getIssuer()); - } - - if (holder.getEntityName() != null) - { - if (matchesDN(PrincipalUtil.getSubjectX509Principal(x509Cert), - holder.getEntityName())) - { - return true; - } - } - if (holder.getObjectDigestInfo() != null) - { - MessageDigest md = null; - try - { - md = MessageDigest.getInstance(getDigestAlgorithm(), "SC"); - - } - catch (Exception e) - { - return false; - } - switch (getDigestedObjectType()) - { - case ObjectDigestInfo.publicKey: - // TODO: DSA Dss-parms - md.update(cert.getPublicKey().getEncoded()); - break; - case ObjectDigestInfo.publicKeyCert: - md.update(cert.getEncoded()); - break; - } - if (!Arrays.areEqual(md.digest(), getObjectDigest())) - { - return false; - } - } - } - catch (CertificateEncodingException e) - { - return false; - } - - return false; - } - - public boolean equals(Object obj) - { - if (obj == this) - { - return true; - } - - if (!(obj instanceof AttributeCertificateHolder)) - { - return false; - } - - AttributeCertificateHolder other = (AttributeCertificateHolder)obj; - - return this.holder.equals(other.holder); - } - - public int hashCode() - { - return this.holder.hashCode(); - } - - public boolean match(Object obj) - { - if (!(obj instanceof X509Certificate)) - { - return false; - } - - return match((Certificate)obj); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/AttributeCertificateIssuer.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/AttributeCertificateIssuer.java deleted file mode 100644 index 44512802c..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/AttributeCertificateIssuer.java +++ /dev/null @@ -1,211 +0,0 @@ -package org.spongycastle.x509; - -import java.io.IOException; -import java.security.Principal; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.x509.AttCertIssuer; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.GeneralNames; -import org.spongycastle.asn1.x509.V2Form; -import org.spongycastle.jce.PrincipalUtil; -import org.spongycastle.jce.X509Principal; -import org.spongycastle.jce.cert.CertSelector; -import org.spongycastle.util.Selector; - -/** - * Carrying class for an attribute certificate issuer. - */ -public class AttributeCertificateIssuer - implements CertSelector, Selector -{ - final ASN1Encodable form; - - /** - * @param issuer - */ - AttributeCertificateIssuer( - AttCertIssuer issuer) - { - form = issuer.getIssuer(); - } - - public AttributeCertificateIssuer( - X509Principal principal) - { - form = new V2Form(new GeneralNames(new GeneralName(principal))); - } - - private Object[] getNames() - { - GeneralNames name; - - if (form instanceof V2Form) - { - name = ((V2Form)form).getIssuerName(); - } - else - { - name = (GeneralNames)form; - } - - GeneralName[] names = name.getNames(); - - List l = new ArrayList(names.length); - - for (int i = 0; i != names.length; i++) - { - if (names[i].getTagNo() == GeneralName.directoryName) - { - try - { - l.add(new X509Principal(((ASN1Encodable)names[i].getName()).toASN1Primitive().getEncoded())); - } - catch (IOException e) - { - throw new RuntimeException("badly formed Name object"); - } - } - } - - return l.toArray(new Object[l.size()]); - } - - /** - * Return any principal objects inside the attribute certificate issuer object. - * - * @return an array of Principal objects (usually X509Principal) - */ - public Principal[] getPrincipals() - { - Object[] p = this.getNames(); - List l = new ArrayList(); - - for (int i = 0; i != p.length; i++) - { - if (p[i] instanceof Principal) - { - l.add(p[i]); - } - } - - return (Principal[])l.toArray(new Principal[l.size()]); - } - - private boolean matchesDN(X509Principal subject, GeneralNames targets) - { - GeneralName[] names = targets.getNames(); - - for (int i = 0; i != names.length; i++) - { - GeneralName gn = names[i]; - - if (gn.getTagNo() == GeneralName.directoryName) - { - try - { - if (new X509Principal(((ASN1Encodable)gn.getName()).toASN1Primitive().getEncoded()).equals(subject)) - { - return true; - } - } - catch (IOException e) - { - } - } - } - - return false; - } - - /* (non-Javadoc) - * @see java.security.cert.CertSelector#clone() - */ - public Object clone() - { - return new AttributeCertificateIssuer(AttCertIssuer.getInstance(form)); - } - - /* (non-Javadoc) - * @see java.security.cert.CertSelector#match(java.security.cert.Certificate) - */ - public boolean match(Certificate cert) - { - if (!(cert instanceof X509Certificate)) - { - return false; - } - - X509Certificate x509Cert = (X509Certificate)cert; - - try - { - if (form instanceof V2Form) - { - V2Form issuer = (V2Form)form; - if (issuer.getBaseCertificateID() != null) - { - return issuer.getBaseCertificateID().getSerial().getValue().equals(x509Cert.getSerialNumber()) - && matchesDN(PrincipalUtil.getIssuerX509Principal(x509Cert), issuer.getBaseCertificateID().getIssuer()); - } - - GeneralNames name = issuer.getIssuerName(); - if (matchesDN(PrincipalUtil.getSubjectX509Principal(x509Cert), name)) - { - return true; - } - } - else - { - GeneralNames name = (GeneralNames)form; - if (matchesDN(PrincipalUtil.getSubjectX509Principal(x509Cert), name)) - { - return true; - } - } - } - catch (CertificateEncodingException e) - { - return false; - } - - return false; - } - - public boolean equals(Object obj) - { - if (obj == this) - { - return true; - } - - if (!(obj instanceof AttributeCertificateIssuer)) - { - return false; - } - - AttributeCertificateIssuer other = (AttributeCertificateIssuer)obj; - - return this.form.equals(other.form); - } - - public int hashCode() - { - return this.form.hashCode(); - } - - public boolean match(Object obj) - { - if (!(obj instanceof X509Certificate)) - { - return false; - } - - return match((Certificate)obj); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/ExtendedPKIXBuilderParameters.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/ExtendedPKIXBuilderParameters.java deleted file mode 100644 index 55d80de90..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/ExtendedPKIXBuilderParameters.java +++ /dev/null @@ -1,210 +0,0 @@ -package org.spongycastle.x509; - -import org.spongycastle.util.Selector; - -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidParameterException; -import org.spongycastle.jce.cert.PKIXBuilderParameters; -import org.spongycastle.jce.cert.PKIXParameters; -import org.spongycastle.jce.cert.TrustAnchor; -import org.spongycastle.jce.cert.X509CertSelector; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -/** - * This class contains extended parameters for PKIX certification path builders. - * - * @see java.security.cert.PKIXBuilderParameters - * @see org.spongycastle.jce.provider.PKIXCertPathBuilderSpi - */ -public class ExtendedPKIXBuilderParameters extends ExtendedPKIXParameters -{ - - private int maxPathLength = 5; - - private Set excludedCerts = Collections.EMPTY_SET; - - /** - * Excluded certificates are not used for building a certification path. - *

- * The returned set is immutable. - * - * @return Returns the excluded certificates. - */ - public Set getExcludedCerts() - { - return Collections.unmodifiableSet(excludedCerts); - } - - /** - * Sets the excluded certificates which are not used for building a - * certification path. If the Set is null an - * empty set is assumed. - *

- * The given set is cloned to protect it against subsequent modifications. - * - * @param excludedCerts The excluded certificates to set. - */ - public void setExcludedCerts(Set excludedCerts) - { - if (excludedCerts == null) - { - excludedCerts = Collections.EMPTY_SET; - } - else - { - this.excludedCerts = new HashSet(excludedCerts); - } - } - - /** - * Creates an instance of PKIXBuilderParameters with the - * specified Set of most-trusted CAs. Each element of the set - * is a {@link TrustAnchor TrustAnchor}. - * - *

- * Note that the Set is copied to protect against subsequent - * modifications. - * - * @param trustAnchors a Set of TrustAnchors - * @param targetConstraints a Selector specifying the - * constraints on the target certificate or attribute - * certificate. - * @throws InvalidAlgorithmParameterException if trustAnchors - * is empty. - * @throws NullPointerException if trustAnchors is - * null - * @throws ClassCastException if any of the elements of - * trustAnchors is not of type - * java.security.cert.TrustAnchor - */ - public ExtendedPKIXBuilderParameters(Set trustAnchors, - Selector targetConstraints) - throws InvalidAlgorithmParameterException - { - super(trustAnchors); - setTargetConstraints(targetConstraints); - } - - /** - * Sets the maximum number of intermediate non-self-issued certificates in a - * certification path. The PKIX CertPathBuilder must not - * build paths longer then this length. - *

- * A value of 0 implies that the path can only contain a single certificate. - * A value of -1 does not limit the length. The default length is 5. - * - *

- * - * The basic constraints extension of a CA certificate overrides this value - * if smaller. - * - * @param maxPathLength the maximum number of non-self-issued intermediate - * certificates in the certification path - * @throws InvalidParameterException if maxPathLength is set - * to a value less than -1 - * - * @see org.spongycastle.jce.provider.PKIXCertPathBuilderSpi - * @see #getMaxPathLength - */ - public void setMaxPathLength(int maxPathLength) - { - if (maxPathLength < -1) - { - throw new InvalidParameterException("The maximum path " - + "length parameter can not be less than -1."); - } - this.maxPathLength = maxPathLength; - } - - /** - * Returns the value of the maximum number of intermediate non-self-issued - * certificates in the certification path. - * - * @return the maximum number of non-self-issued intermediate certificates - * in the certification path, or -1 if no limit exists. - * - * @see #setMaxPathLength(int) - */ - public int getMaxPathLength() - { - return maxPathLength; - } - - /** - * Can alse handle ExtendedPKIXBuilderParameters and - * PKIXBuilderParameters. - * - * @param params Parameters to set. - * @see org.spongycastle.x509.ExtendedPKIXParameters#setParams(java.security.cert.PKIXParameters) - */ - protected void setParams(PKIXParameters params) - { - super.setParams(params); - if (params instanceof ExtendedPKIXBuilderParameters) - { - ExtendedPKIXBuilderParameters _params = (ExtendedPKIXBuilderParameters) params; - maxPathLength = _params.maxPathLength; - excludedCerts = new HashSet(_params.excludedCerts); - } - if (params instanceof PKIXBuilderParameters) - { - PKIXBuilderParameters _params = (PKIXBuilderParameters) params; - maxPathLength = _params.getMaxPathLength(); - } - } - - /** - * Makes a copy of this PKIXParameters object. Changes to the - * copy will not affect the original and vice versa. - * - * @return a copy of this PKIXParameters object - */ - public Object clone() - { - ExtendedPKIXBuilderParameters params = null; - try - { - params = new ExtendedPKIXBuilderParameters(getTrustAnchors(), - getTargetConstraints()); - } - catch (Exception e) - { - // cannot happen - throw new RuntimeException(e.getMessage()); - } - params.setParams(this); - return params; - } - - /** - * Returns an instance of ExtendedPKIXParameters which can be - * safely casted to ExtendedPKIXBuilderParameters. - *

- * This method can be used to get a copy from other - * PKIXBuilderParameters, PKIXParameters, - * and ExtendedPKIXParameters instances. - * - * @param pkixParams The PKIX parameters to create a copy of. - * @return An ExtendedPKIXBuilderParameters instance. - */ - public static ExtendedPKIXParameters getInstance(PKIXParameters pkixParams) - { - ExtendedPKIXBuilderParameters params; - try - { - params = new ExtendedPKIXBuilderParameters(pkixParams - .getTrustAnchors(), X509CertStoreSelector - .getInstance((X509CertSelector) pkixParams - .getTargetCertConstraints())); - } - catch (Exception e) - { - // cannot happen - throw new RuntimeException(e.getMessage()); - } - params.setParams(pkixParams); - return params; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/ExtendedPKIXParameters.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/ExtendedPKIXParameters.java deleted file mode 100644 index c2636c5b6..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/ExtendedPKIXParameters.java +++ /dev/null @@ -1,647 +0,0 @@ -package org.spongycastle.x509; - -import org.spongycastle.util.Selector; -import org.spongycastle.util.Store; - -import java.security.InvalidAlgorithmParameterException; -import org.spongycastle.jce.cert.CertSelector; -import org.spongycastle.jce.cert.CertStore; -import org.spongycastle.jce.cert.CollectionCertStoreParameters; -import org.spongycastle.jce.cert.LDAPCertStoreParameters; -import org.spongycastle.jce.cert.PKIXParameters; -import org.spongycastle.jce.cert.TrustAnchor; -import org.spongycastle.jce.cert.X509CertSelector; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -/** - * This class extends the PKIXParameters with a validity model parameter. - */ -public class ExtendedPKIXParameters - extends PKIXParameters -{ - - private List stores; - - private Selector selector; - - private boolean additionalLocationsEnabled; - - private List additionalStores; - - private Set trustedACIssuers; - - private Set necessaryACAttributes; - - private Set prohibitedACAttributes; - - private Set attrCertCheckers; - - /** - * Creates an instance of PKIXParameters with the specified - * Set of most-trusted CAs. Each element of the set is a - * {@link TrustAnchor TrustAnchor}.

Note that the Set - * is copied to protect against subsequent modifications. - * - * @param trustAnchors a Set of TrustAnchors - * @throws InvalidAlgorithmParameterException if the specified - * Set is empty. - * @throws NullPointerException if the specified Set is - * null - * @throws ClassCastException if any of the elements in the Set - * is not of type java.security.cert.TrustAnchor - */ - public ExtendedPKIXParameters(Set trustAnchors) - throws InvalidAlgorithmParameterException - { - super(trustAnchors); - stores = new ArrayList(); - additionalStores = new ArrayList(); - trustedACIssuers = new HashSet(); - necessaryACAttributes = new HashSet(); - prohibitedACAttributes = new HashSet(); - attrCertCheckers = new HashSet(); - } - - /** - * Returns an instance with the parameters of a given - * PKIXParameters object. - * - * @param pkixParams The given PKIXParameters - * @return an extended PKIX params object - */ - public static ExtendedPKIXParameters getInstance(PKIXParameters pkixParams) - { - ExtendedPKIXParameters params; - try - { - params = new ExtendedPKIXParameters(pkixParams.getTrustAnchors()); - } - catch (Exception e) - { - // cannot happen - throw new RuntimeException(e.getMessage()); - } - params.setParams(pkixParams); - return params; - } - - /** - * Method to support clone() under J2ME. - * super.clone() does not exist and fields are not copied. - * - * @param params Parameters to set. If this are - * ExtendedPKIXParameters they are copied to. - */ - protected void setParams(PKIXParameters params) - { - setDate(params.getDate()); - setCertPathCheckers(params.getCertPathCheckers()); - setCertStores(params.getCertStores()); - setAnyPolicyInhibited(params.isAnyPolicyInhibited()); - setExplicitPolicyRequired(params.isExplicitPolicyRequired()); - setPolicyMappingInhibited(params.isPolicyMappingInhibited()); - setRevocationEnabled(params.isRevocationEnabled()); - setInitialPolicies(params.getInitialPolicies()); - setPolicyQualifiersRejected(params.getPolicyQualifiersRejected()); - setSigProvider(params.getSigProvider()); - setTargetCertConstraints(params.getTargetCertConstraints()); - try - { - setTrustAnchors(params.getTrustAnchors()); - } - catch (Exception e) - { - // cannot happen - throw new RuntimeException(e.getMessage()); - } - if (params instanceof ExtendedPKIXParameters) - { - ExtendedPKIXParameters _params = (ExtendedPKIXParameters) params; - validityModel = _params.validityModel; - useDeltas = _params.useDeltas; - additionalLocationsEnabled = _params.additionalLocationsEnabled; - selector = _params.selector == null ? null - : (Selector) _params.selector.clone(); - stores = new ArrayList(_params.stores); - additionalStores = new ArrayList(_params.additionalStores); - trustedACIssuers = new HashSet(_params.trustedACIssuers); - prohibitedACAttributes = new HashSet(_params.prohibitedACAttributes); - necessaryACAttributes = new HashSet(_params.necessaryACAttributes); - attrCertCheckers = new HashSet(_params.attrCertCheckers); - } - } - - /** - * This is the default PKIX validity model. Actually there are two variants - * of this: The PKIX model and the modified PKIX model. The PKIX model - * verifies that all involved certificates must have been valid at the - * current time. The modified PKIX model verifies that all involved - * certificates were valid at the signing time. Both are indirectly choosen - * with the {@link PKIXParameters#setDate(java.util.Date)} method, so this - * methods sets the Date when all certificates must have been - * valid. - */ - public static final int PKIX_VALIDITY_MODEL = 0; - - /** - * This model uses the following validity model. Each certificate must have - * been valid at the moment where is was used. That means the end - * certificate must have been valid at the time the signature was done. The - * CA certificate which signed the end certificate must have been valid, - * when the end certificate was signed. The CA (or Root CA) certificate must - * have been valid, when the CA certificate was signed and so on. So the - * {@link PKIXParameters#setDate(java.util.Date)} method sets the time, when - * the end certificate must have been valid.

It is used e.g. - * in the German signature law. - */ - public static final int CHAIN_VALIDITY_MODEL = 1; - - private int validityModel = PKIX_VALIDITY_MODEL; - - private boolean useDeltas = false; - - /** - * Defaults to false. - * - * @return Returns if delta CRLs should be used. - */ - public boolean isUseDeltasEnabled() - { - return useDeltas; - } - - /** - * Sets if delta CRLs should be used for checking the revocation status. - * - * @param useDeltas true if delta CRLs should be used. - */ - public void setUseDeltasEnabled(boolean useDeltas) - { - this.useDeltas = useDeltas; - } - - /** - * @return Returns the validity model. - * @see #CHAIN_VALIDITY_MODEL - * @see #PKIX_VALIDITY_MODEL - */ - public int getValidityModel() - { - return validityModel; - } - - /** - * Sets the Java CertStore to this extended PKIX parameters. - * - * @throws ClassCastException if an element of stores is not - * a CertStore. - */ - public void setCertStores(List stores) - { - if (stores != null) - { - Iterator it = stores.iterator(); - while (it.hasNext()) - { - addCertStore((CertStore)it.next()); - } - } - } - - /** - * Sets the Bouncy Castle Stores for finding CRLs, certificates, attribute - * certificates or cross certificates. - *

- * The List is cloned. - * - * @param stores A list of stores to use. - * @see #getStores - * @throws ClassCastException if an element of stores is not - * a {@link Store}. - */ - public void setStores(List stores) - { - if (stores == null) - { - this.stores = new ArrayList(); - } - else - { - for (Iterator i = stores.iterator(); i.hasNext();) - { - if (!(i.next() instanceof Store)) - { - throw new ClassCastException( - "All elements of list must be " - + "of type org.spongycastle.util.Store."); - } - } - this.stores = new ArrayList(stores); - } - } - - /** - * Adds a Bouncy Castle {@link Store} to find CRLs, certificates, attribute - * certificates or cross certificates. - *

- * This method should be used to add local stores, like collection based - * X.509 stores, if available. Local stores should be considered first, - * before trying to use additional (remote) locations, because they do not - * need possible additional network traffic. - *

- * If store is null it is ignored. - * - * @param store The store to add. - * @see #getStores - */ - public void addStore(Store store) - { - if (stores != null) - { - stores.add(store); - } - } - - /** - * Adds a additional Bouncy Castle {@link Store} to find CRLs, certificates, - * attribute certificates or cross certificates. - *

- * You should not use this method. This method is used for adding additional - * X.509 stores, which are used to add (remote) locations, e.g. LDAP, found - * during X.509 object processing, e.g. in certificates or CRLs. This method - * is used in PKIX certification path processing. - *

- * If store is null it is ignored. - * - * @param store The store to add. - * @see #getStores() - */ - public void addAddionalStore(Store store) - { - if (store != null) - { - additionalStores.add(store); - } - } - - /** - * Returns an immutable List of additional Bouncy Castle - * Stores used for finding CRLs, certificates, attribute - * certificates or cross certificates. - * - * @return an immutable List of additional Bouncy Castle - * Stores. Never null. - * - * @see #addAddionalStore(Store) - */ - public List getAdditionalStores() - { - return Collections.unmodifiableList(additionalStores); - } - - /** - * Returns an immutable List of Bouncy Castle - * Stores used for finding CRLs, certificates, attribute - * certificates or cross certificates. - * - * @return an immutable List of Bouncy Castle - * Stores. Never null. - * - * @see #setStores(List) - */ - public List getStores() - { - return Collections.unmodifiableList(new ArrayList(stores)); - } - - /** - * @param validityModel The validity model to set. - * @see #CHAIN_VALIDITY_MODEL - * @see #PKIX_VALIDITY_MODEL - */ - public void setValidityModel(int validityModel) - { - this.validityModel = validityModel; - } - - public Object clone() - { - ExtendedPKIXParameters params; - try - { - params = new ExtendedPKIXParameters(getTrustAnchors()); - } - catch (Exception e) - { - // cannot happen - throw new RuntimeException(e.getMessage()); - } - params.setParams(this); - return params; - } - - /** - * Returns if additional {@link X509Store}s for locations like LDAP found - * in certificates or CRLs should be used. - * - * @return Returns true if additional stores are used. - */ - public boolean isAdditionalLocationsEnabled() - { - return additionalLocationsEnabled; - } - - /** - * Sets if additional {@link X509Store}s for locations like LDAP found in - * certificates or CRLs should be used. - * - * @param enabled true if additional stores are used. - */ - public void setAdditionalLocationsEnabled(boolean enabled) - { - additionalLocationsEnabled = enabled; - } - - /** - * Returns the required constraints on the target certificate or attribute - * certificate. The constraints are returned as an instance of - * Selector. If null, no constraints are - * defined. - * - *

- * The target certificate in a PKIX path may be a certificate or an - * attribute certificate. - *

- * Note that the Selector returned is cloned to protect - * against subsequent modifications. - * - * @return a Selector specifying the constraints on the - * target certificate or attribute certificate (or null) - * @see #setTargetConstraints - * @see X509CertStoreSelector - * @see X509AttributeCertStoreSelector - */ - public Selector getTargetConstraints() - { - if (selector != null) - { - return (Selector) selector.clone(); - } - else - { - return null; - } - } - - /** - * Sets the required constraints on the target certificate or attribute - * certificate. The constraints are specified as an instance of - * Selector. If null, no constraints are - * defined. - *

- * The target certificate in a PKIX path may be a certificate or an - * attribute certificate. - *

- * Note that the Selector specified is cloned to protect - * against subsequent modifications. - * - * @param selector a Selector specifying the constraints on - * the target certificate or attribute certificate (or - * null) - * @see #getTargetConstraints - * @see X509CertStoreSelector - * @see X509AttributeCertStoreSelector - */ - public void setTargetConstraints(Selector selector) - { - if (selector != null) - { - this.selector = (Selector) selector.clone(); - } - else - { - this.selector = null; - } - } - - /** - * Sets the required constraints on the target certificate. The constraints - * are specified as an instance of X509CertSelector. If - * null, no constraints are defined. - * - *

- * This method wraps the given X509CertSelector into a - * X509CertStoreSelector. - *

- * Note that the X509CertSelector specified is cloned to - * protect against subsequent modifications. - * - * @param selector a X509CertSelector specifying the - * constraints on the target certificate (or null) - * @see #getTargetCertConstraints - * @see X509CertStoreSelector - */ - public void setTargetCertConstraints(CertSelector selector) - { - super.setTargetCertConstraints(selector); - if (selector != null) - { - this.selector = X509CertStoreSelector - .getInstance((X509CertSelector) selector); - } - else - { - this.selector = null; - } - } - - /** - * Returns the trusted attribute certificate issuers. If attribute - * certificates is verified the trusted AC issuers must be set. - *

- * The returned Set consists of TrustAnchors. - *

- * The returned Set is immutable. Never null - * - * @return Returns an immutable set of the trusted AC issuers. - */ - public Set getTrustedACIssuers() - { - return Collections.unmodifiableSet(trustedACIssuers); - } - - /** - * Sets the trusted attribute certificate issuers. If attribute certificates - * is verified the trusted AC issuers must be set. - *

- * The trustedACIssuers must be a Set of - * TrustAnchor - *

- * The given set is cloned. - * - * @param trustedACIssuers The trusted AC issuers to set. Is never - * null. - * @throws ClassCastException if an element of stores is not - * a TrustAnchor. - */ - public void setTrustedACIssuers(Set trustedACIssuers) - { - if (trustedACIssuers == null) - { - trustedACIssuers.clear(); - return; - } - for (Iterator it = trustedACIssuers.iterator(); it.hasNext();) - { - if (!(it.next() instanceof TrustAnchor)) - { - throw new ClassCastException("All elements of set must be " - + "of type " + TrustAnchor.class.getName() + "."); - } - } - this.trustedACIssuers.clear(); - this.trustedACIssuers.addAll(trustedACIssuers); - } - - /** - * Returns the neccessary attributes which must be contained in an attribute - * certificate. - *

- * The returned Set is immutable and contains - * Strings with the OIDs. - * - * @return Returns the necessary AC attributes. - */ - public Set getNecessaryACAttributes() - { - return Collections.unmodifiableSet(necessaryACAttributes); - } - - /** - * Sets the neccessary which must be contained in an attribute certificate. - *

- * The Set must contain Strings with the - * OIDs. - *

- * The set is cloned. - * - * @param necessaryACAttributes The necessary AC attributes to set. - * @throws ClassCastException if an element of - * necessaryACAttributes is not a - * String. - */ - public void setNecessaryACAttributes(Set necessaryACAttributes) - { - if (necessaryACAttributes == null) - { - this.necessaryACAttributes.clear(); - return; - } - for (Iterator it = necessaryACAttributes.iterator(); it.hasNext();) - { - if (!(it.next() instanceof String)) - { - throw new ClassCastException("All elements of set must be " - + "of type String."); - } - } - this.necessaryACAttributes.clear(); - this.necessaryACAttributes.addAll(necessaryACAttributes); - } - - /** - * Returns the attribute certificates which are not allowed. - *

- * The returned Set is immutable and contains - * Strings with the OIDs. - * - * @return Returns the prohibited AC attributes. Is never null. - */ - public Set getProhibitedACAttributes() - { - return prohibitedACAttributes; - } - - /** - * Sets the attribute certificates which are not allowed. - *

- * The Set must contain Strings with the - * OIDs. - *

- * The set is cloned. - * - * @param prohibitedACAttributes The prohibited AC attributes to set. - * @throws ClassCastException if an element of - * prohibitedACAttributes is not a - * String. - */ - public void setProhibitedACAttributes(Set prohibitedACAttributes) - { - if (prohibitedACAttributes == null) - { - this.prohibitedACAttributes.clear(); - return; - } - for (Iterator it = prohibitedACAttributes.iterator(); it.hasNext();) - { - if (!(it.next() instanceof String)) - { - throw new ClassCastException("All elements of set must be " - + "of type String."); - } - } - this.prohibitedACAttributes.clear(); - this.prohibitedACAttributes.addAll(prohibitedACAttributes); - } - - /** - * Returns the attribute certificate checker. The returned set contains - * {@link PKIXAttrCertChecker}s and is immutable. - * - * @return Returns the attribute certificate checker. Is never - * null. - */ - public Set getAttrCertCheckers() - { - return Collections.unmodifiableSet(attrCertCheckers); - } - - /** - * Sets the attribute certificate checkers. - *

- * All elements in the Set must a {@link PKIXAttrCertChecker}. - *

- * The given set is cloned. - * - * @param attrCertCheckers The attribute certificate checkers to set. Is - * never null. - * @throws ClassCastException if an element of attrCertCheckers - * is not a PKIXAttrCertChecker. - */ -/* - public void setAttrCertCheckers(Set attrCertCheckers) - { - if (attrCertCheckers == null) - { - this.attrCertCheckers.clear(); - return; - } - for (Iterator it = attrCertCheckers.iterator(); it.hasNext();) - { - if (!(it.next() instanceof PKIXAttrCertChecker)) - { - throw new ClassCastException("All elements of set must be " - + "of type " + PKIXAttrCertChecker.class.getName() + "."); - } - } - this.attrCertCheckers.clear(); - this.attrCertCheckers.addAll(attrCertCheckers); - } -*/ -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509AttributeCertStoreSelector.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509AttributeCertStoreSelector.java deleted file mode 100644 index b47236d1b..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509AttributeCertStoreSelector.java +++ /dev/null @@ -1,486 +0,0 @@ -package org.spongycastle.x509; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.Target; -import org.spongycastle.asn1.x509.TargetInformation; -import org.spongycastle.asn1.x509.Targets; -import org.spongycastle.asn1.x509.X509Extensions; -import org.spongycastle.util.Selector; - -/** - * This class is an Selector like implementation to select - * attribute certificates from a given set of criteria. - * - * @see org.spongycastle.x509.X509AttributeCertificate - * @see org.spongycastle.x509.X509Store - */ -public class X509AttributeCertStoreSelector - implements Selector -{ - - // TODO: name constraints??? - - private AttributeCertificateHolder holder; - - private AttributeCertificateIssuer issuer; - - private BigInteger serialNumber; - - private Date attributeCertificateValid; - - private X509AttributeCertificate attributeCert; - - private Collection targetNames = new HashSet(); - - private Collection targetGroups = new HashSet(); - - public X509AttributeCertStoreSelector() - { - super(); - } - - /** - * Decides if the given attribute certificate should be selected. - * - * @param obj The attribute certificate which should be checked. - * @return true if the attribute certificate can be selected, - * false otherwise. - */ - public boolean match(Object obj) - { - if (!(obj instanceof X509AttributeCertificate)) - { - return false; - } - - X509AttributeCertificate attrCert = (X509AttributeCertificate) obj; - - if (this.attributeCert != null) - { - if (!this.attributeCert.equals(attrCert)) - { - return false; - } - } - if (serialNumber != null) - { - if (!attrCert.getSerialNumber().equals(serialNumber)) - { - return false; - } - } - if (holder != null) - { - if (!attrCert.getHolder().equals(holder)) - { - return false; - } - } - if (issuer != null) - { - if (!attrCert.getIssuer().equals(issuer)) - { - return false; - } - } - - if (attributeCertificateValid != null) - { - try - { - attrCert.checkValidity(attributeCertificateValid); - } - catch (CertificateExpiredException e) - { - return false; - } - catch (CertificateNotYetValidException e) - { - return false; - } - } - if (!targetNames.isEmpty() || !targetGroups.isEmpty()) - { - - byte[] targetInfoExt = attrCert - .getExtensionValue(X509Extensions.TargetInformation.getId()); - if (targetInfoExt != null) - { - TargetInformation targetinfo; - try - { - targetinfo = TargetInformation - .getInstance(new ASN1InputStream( - ((DEROctetString) DEROctetString - .fromByteArray(targetInfoExt)).getOctets()) - .readObject()); - } - catch (IOException e) - { - return false; - } - catch (IllegalArgumentException e) - { - return false; - } - Targets[] targetss = targetinfo.getTargetsObjects(); - if (!targetNames.isEmpty()) - { - boolean found = false; - - for (int i=0; inull is - * given any will do. - * - * @param attributeCert The attribute certificate to set. - */ - public void setAttributeCert(X509AttributeCertificate attributeCert) - { - this.attributeCert = attributeCert; - } - - /** - * Get the criteria for the validity. - * - * @return Returns the attributeCertificateValid. - */ - public Date getAttributeCertificateValid() - { - if (attributeCertificateValid != null) - { - return new Date(attributeCertificateValid.getTime()); - } - - return null; - } - - /** - * Set the time, when the certificate must be valid. If null - * is given any will do. - * - * @param attributeCertificateValid The attribute certificate validation - * time to set. - */ - public void setAttributeCertificateValid(Date attributeCertificateValid) - { - if (attributeCertificateValid != null) - { - this.attributeCertificateValid = new Date(attributeCertificateValid - .getTime()); - } - else - { - this.attributeCertificateValid = null; - } - } - - /** - * Gets the holder. - * - * @return Returns the holder. - */ - public AttributeCertificateHolder getHolder() - { - return holder; - } - - /** - * Sets the holder. If null is given any will do. - * - * @param holder The holder to set. - */ - public void setHolder(AttributeCertificateHolder holder) - { - this.holder = holder; - } - - /** - * Returns the issuer criterion. - * - * @return Returns the issuer. - */ - public AttributeCertificateIssuer getIssuer() - { - return issuer; - } - - /** - * Sets the issuer the attribute certificate must have. If null - * is given any will do. - * - * @param issuer The issuer to set. - */ - public void setIssuer(AttributeCertificateIssuer issuer) - { - this.issuer = issuer; - } - - /** - * Gets the serial number the attribute certificate must have. - * - * @return Returns the serialNumber. - */ - public BigInteger getSerialNumber() - { - return serialNumber; - } - - /** - * Sets the serial number the attribute certificate must have. If - * null is given any will do. - * - * @param serialNumber The serialNumber to set. - */ - public void setSerialNumber(BigInteger serialNumber) - { - this.serialNumber = serialNumber; - } - - /** - * Adds a target name criterion for the attribute certificate to the target - * information extension criteria. The X509AttributeCertificate - * must contain at least one of the specified target names. - *

- * Each attribute certificate may contain a target information extension - * limiting the servers where this attribute certificate can be used. If - * this extension is not present, the attribute certificate is not targeted - * and may be accepted by any server. - * - * @param name The name as a GeneralName (not null) - */ - public void addTargetName(GeneralName name) - { - targetNames.add(name); - } - - /** - * Adds a target name criterion for the attribute certificate to the target - * information extension criteria. The X509AttributeCertificate - * must contain at least one of the specified target names. - *

- * Each attribute certificate may contain a target information extension - * limiting the servers where this attribute certificate can be used. If - * this extension is not present, the attribute certificate is not targeted - * and may be accepted by any server. - * - * @param name a byte array containing the name in ASN.1 DER encoded form of a GeneralName - * @throws IOException if a parsing error occurs. - */ - public void addTargetName(byte[] name) throws IOException - { - addTargetName(GeneralName.getInstance(ASN1Primitive.fromByteArray(name))); - } - - /** - * Adds a collection with target names criteria. If null is - * given any will do. - *

- * The collection consists of either GeneralName objects or byte[] arrays representing - * DER encoded GeneralName structures. - * - * @param names A collection of target names. - * @throws IOException if a parsing error occurs. - * @see #addTargetName(byte[]) - * @see #addTargetName(GeneralName) - */ - public void setTargetNames(Collection names) throws IOException - { - targetNames = extractGeneralNames(names); - } - - /** - * Gets the target names. The collection consists of Lists - * made up of an Integer in the first entry and a DER encoded - * byte array or a String in the second entry. - *

- * The returned collection is immutable. - * - * @return The collection of target names - * @see #setTargetNames(Collection) - */ - public Collection getTargetNames() - { - return Collections.unmodifiableCollection(targetNames); - } - - /** - * Adds a target group criterion for the attribute certificate to the target - * information extension criteria. The X509AttributeCertificate - * must contain at least one of the specified target groups. - *

- * Each attribute certificate may contain a target information extension - * limiting the servers where this attribute certificate can be used. If - * this extension is not present, the attribute certificate is not targeted - * and may be accepted by any server. - * - * @param group The group as GeneralName form (not null) - */ - public void addTargetGroup(GeneralName group) - { - targetGroups.add(group); - } - - /** - * Adds a target group criterion for the attribute certificate to the target - * information extension criteria. The X509AttributeCertificate - * must contain at least one of the specified target groups. - *

- * Each attribute certificate may contain a target information extension - * limiting the servers where this attribute certificate can be used. If - * this extension is not present, the attribute certificate is not targeted - * and may be accepted by any server. - * - * @param name a byte array containing the group in ASN.1 DER encoded form of a GeneralName - * @throws IOException if a parsing error occurs. - */ - public void addTargetGroup(byte[] name) throws IOException - { - addTargetGroup(GeneralName.getInstance(ASN1Primitive.fromByteArray(name))); - } - - /** - * Adds a collection with target groups criteria. If null is - * given any will do. - *

- * The collection consists of GeneralName objects or byte[]Lists - * made up of an Integer in the first entry and a DER encoded - * byte array or a String in the second entry. - *

- * The returned collection is immutable. - * - * @return The collection of target groups. - * @see #setTargetGroups(Collection) - */ - public Collection getTargetGroups() - { - return Collections.unmodifiableCollection(targetGroups); - } - - private Set extractGeneralNames(Collection names) - throws IOException - { - if (names == null || names.isEmpty()) - { - return new HashSet(); - } - Set temp = new HashSet(); - for (Iterator it = names.iterator(); it.hasNext();) - { - Object o = it.next(); - if (o instanceof GeneralName) - { - temp.add(o); - } - else - { - temp.add(GeneralName.getInstance(ASN1Primitive.fromByteArray((byte[])o))); - } - } - return temp; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509CRLStoreSelector.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509CRLStoreSelector.java deleted file mode 100644 index 554911f0f..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509CRLStoreSelector.java +++ /dev/null @@ -1,330 +0,0 @@ -package org.spongycastle.x509; - -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.x509.X509Extensions; -import org.spongycastle.util.Arrays; -import org.spongycastle.util.Selector; -import org.spongycastle.x509.extension.X509ExtensionUtil; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.cert.CRL; -import java.security.cert.X509CRL; -import org.spongycastle.jce.cert.X509CRLSelector; - -/** - * This class is a Selector implementation for X.509 certificate revocation - * lists. - * - * @see org.spongycastle.util.Selector - * @see org.spongycastle.x509.X509Store - * @see org.spongycastle.jce.provider.X509StoreCRLCollection - */ -public class X509CRLStoreSelector - extends X509CRLSelector - implements Selector -{ - private boolean deltaCRLIndicator = false; - - private boolean completeCRLEnabled = false; - - private BigInteger maxBaseCRLNumber = null; - - private byte[] issuingDistributionPoint = null; - - private boolean issuingDistributionPointEnabled = false; - - private X509AttributeCertificate attrCertChecking; - - /** - * Returns if the issuing distribution point criteria should be applied. - * Defaults to false. - *

- * You may also set the issuing distribution point criteria if not a missing - * issuing distribution point should be assumed. - * - * @return Returns if the issuing distribution point check is enabled. - */ - public boolean isIssuingDistributionPointEnabled() - { - return issuingDistributionPointEnabled; - } - - /** - * Enables or disables the issuing distribution point check. - * - * @param issuingDistributionPointEnabled true to enable the - * issuing distribution point check. - */ - public void setIssuingDistributionPointEnabled( - boolean issuingDistributionPointEnabled) - { - this.issuingDistributionPointEnabled = issuingDistributionPointEnabled; - } - - /** - * Sets the attribute certificate being checked. This is not a criterion. - * Rather, it is optional information that may help a {@link X509Store} find - * CRLs that would be relevant when checking revocation for the specified - * attribute certificate. If null is specified, then no such - * optional information is provided. - * - * @param attrCert the X509AttributeCertificate being checked (or - * null) - * @see #getAttrCertificateChecking() - */ - public void setAttrCertificateChecking(X509AttributeCertificate attrCert) - { - attrCertChecking = attrCert; - } - - /** - * Returns the attribute certificate being checked. - * - * @return Returns the attribute certificate being checked. - * @see #setAttrCertificateChecking(X509AttributeCertificate) - */ - public X509AttributeCertificate getAttrCertificateChecking() - { - return attrCertChecking; - } - - public boolean match(Object obj) - { - if (!(obj instanceof X509CRL)) - { - return false; - } - X509CRL crl = (X509CRL)obj; - ASN1Integer dci = null; - try - { - byte[] bytes = crl - .getExtensionValue(X509Extensions.DeltaCRLIndicator.getId()); - if (bytes != null) - { - dci = ASN1Integer.getInstance(X509ExtensionUtil - .fromExtensionValue(bytes)); - } - } - catch (Exception e) - { - return false; - } - if (isDeltaCRLIndicatorEnabled()) - { - if (dci == null) - { - return false; - } - } - if (isCompleteCRLEnabled()) - { - if (dci != null) - { - return false; - } - } - if (dci != null) - { - - if (maxBaseCRLNumber != null) - { - if (dci.getPositiveValue().compareTo(maxBaseCRLNumber) == 1) - { - return false; - } - } - } - if (issuingDistributionPointEnabled) - { - byte[] idp = crl - .getExtensionValue(X509Extensions.IssuingDistributionPoint - .getId()); - if (issuingDistributionPoint == null) - { - if (idp != null) - { - return false; - } - } - else - { - if (!Arrays.areEqual(idp, issuingDistributionPoint)) - { - return false; - } - } - - } - return super.match((X509CRL)obj); - } - - public boolean match(CRL crl) - { - return match((Object)crl); - } - - /** - * Returns if this selector must match CRLs with the delta CRL indicator - * extension set. Defaults to false. - * - * @return Returns true if only CRLs with the delta CRL - * indicator extension are selected. - */ - public boolean isDeltaCRLIndicatorEnabled() - { - return deltaCRLIndicator; - } - - /** - * If this is set to true the CRL reported contains the delta - * CRL indicator CRL extension. - *

- * {@link #setCompleteCRLEnabled(boolean)} and - * {@link #setDeltaCRLIndicatorEnabled(boolean)} excluded each other. - * - * @param deltaCRLIndicator true if the delta CRL indicator - * extension must be in the CRL. - */ - public void setDeltaCRLIndicatorEnabled(boolean deltaCRLIndicator) - { - this.deltaCRLIndicator = deltaCRLIndicator; - } - - /** - * Returns an instance of this from a X509CRLSelector. - * - * @param selector A X509CRLSelector instance. - * @return An instance of an X509CRLStoreSelector. - * @exception IllegalArgumentException if selector is null or creation - * fails. - */ - public static X509CRLStoreSelector getInstance(X509CRLSelector selector) - { - if (selector == null) - { - throw new IllegalArgumentException( - "cannot create from null selector"); - } - X509CRLStoreSelector cs = new X509CRLStoreSelector(); - cs.setCertificateChecking(selector.getCertificateChecking()); - cs.setDateAndTime(selector.getDateAndTime()); - try - { - cs.setIssuerNames(selector.getIssuerNames()); - } - catch (IOException e) - { - // cannot happen - throw new IllegalArgumentException(e.getMessage()); - } - //cs.setIssuers(selector.getIssuers()); - cs.setMaxCRLNumber(selector.getMaxCRL()); - cs.setMinCRLNumber(selector.getMinCRL()); - return cs; - } - - public Object clone() - { - X509CRLStoreSelector sel = X509CRLStoreSelector.getInstance(this); - sel.deltaCRLIndicator = deltaCRLIndicator; - sel.completeCRLEnabled = completeCRLEnabled; - sel.maxBaseCRLNumber = maxBaseCRLNumber; - sel.attrCertChecking = attrCertChecking; - sel.issuingDistributionPointEnabled = issuingDistributionPointEnabled; - sel.issuingDistributionPoint = Arrays.clone(issuingDistributionPoint); - return sel; - } - - /** - * If true only complete CRLs are returned. Defaults to - * false. - * - * @return true if only complete CRLs are returned. - */ - public boolean isCompleteCRLEnabled() - { - return completeCRLEnabled; - } - - /** - * If set to true only complete CRLs are returned. - *

- * {@link #setCompleteCRLEnabled(boolean)} and - * {@link #setDeltaCRLIndicatorEnabled(boolean)} excluded each other. - * - * @param completeCRLEnabled true if only complete CRLs - * should be returned. - */ - public void setCompleteCRLEnabled(boolean completeCRLEnabled) - { - this.completeCRLEnabled = completeCRLEnabled; - } - - /** - * Get the maximum base CRL number. Defaults to null. - * - * @return Returns the maximum base CRL number. - * @see #setMaxBaseCRLNumber(BigInteger) - */ - public BigInteger getMaxBaseCRLNumber() - { - return maxBaseCRLNumber; - } - - /** - * Sets the maximum base CRL number. Setting to null disables - * this cheack. - *

- * This is only meaningful for delta CRLs. Complete CRLs must have a CRL - * number which is greater or equal than the base number of the - * corresponding CRL. - * - * @param maxBaseCRLNumber The maximum base CRL number to set. - */ - public void setMaxBaseCRLNumber(BigInteger maxBaseCRLNumber) - { - this.maxBaseCRLNumber = maxBaseCRLNumber; - } - - /** - * Returns the issuing distribution point. Defaults to null, - * which is a missing issuing distribution point extension. - *

- * The internal byte array is cloned before it is returned. - *

- * The criteria must be enable with - * {@link #setIssuingDistributionPointEnabled(boolean)}. - * - * @return Returns the issuing distribution point. - * @see #setIssuingDistributionPoint(byte[]) - */ - public byte[] getIssuingDistributionPoint() - { - return Arrays.clone(issuingDistributionPoint); - } - - /** - * Sets the issuing distribution point. - *

- * The issuing distribution point extension is a CRL extension which - * identifies the scope and the distribution point of a CRL. The scope - * contains among others information about revocation reasons contained in - * the CRL. Delta CRLs and complete CRLs must have matching issuing - * distribution points. - *

- * The byte array is cloned to protect against subsequent modifications. - *

- * You must also enable or disable this criteria with - * {@link #setIssuingDistributionPointEnabled(boolean)}. - * - * @param issuingDistributionPoint The issuing distribution point to set. - * This is the DER encoded OCTET STRING extension value. - * @see #getIssuingDistributionPoint() - */ - public void setIssuingDistributionPoint(byte[] issuingDistributionPoint) - { - this.issuingDistributionPoint = Arrays.clone(issuingDistributionPoint); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509CertStoreSelector.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509CertStoreSelector.java deleted file mode 100644 index f4efcddbc..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509CertStoreSelector.java +++ /dev/null @@ -1,86 +0,0 @@ -package org.spongycastle.x509; - -import org.spongycastle.util.Selector; - -import java.io.IOException; -import java.security.cert.Certificate; -import org.spongycastle.jce.cert.X509CertSelector; -import java.security.cert.X509Certificate; - -/** - * This class is a Selector implementation for X.509 certificates. - * - * @see org.spongycastle.util.Selector - * @see org.spongycastle.x509.X509Store - * @see org.spongycastle.jce.provider.X509StoreCertCollection - */ -public class X509CertStoreSelector - extends X509CertSelector - implements Selector -{ - public boolean match(Object obj) - { - if (!(obj instanceof X509Certificate)) - { - return false; - } - - X509Certificate other = (X509Certificate)obj; - - return super.match(other); - } - - public boolean match(Certificate cert) - { - return match((Object)cert); - } - - public Object clone() - { - X509CertStoreSelector selector = (X509CertStoreSelector)super.clone(); - - return selector; - } - - /** - * Returns an instance of this from a X509CertSelector. - * - * @param selector A X509CertSelector instance. - * @return An instance of an X509CertStoreSelector. - * @exception IllegalArgumentException if selector is null or creation fails. - */ - public static X509CertStoreSelector getInstance(X509CertSelector selector) - { - if (selector == null) - { - throw new IllegalArgumentException("cannot create from null selector"); - } - X509CertStoreSelector cs = new X509CertStoreSelector(); - cs.setAuthorityKeyIdentifier(selector.getAuthorityKeyIdentifier()); - cs.setBasicConstraints(selector.getBasicConstraints()); - cs.setCertificate(selector.getCertificate()); - cs.setCertificateValid(selector.getCertificateValid()); - cs.setMatchAllSubjectAltNames(selector.getMatchAllSubjectAltNames()); - try - { - cs.setPathToNames(selector.getPathToNames()); - cs.setExtendedKeyUsage(selector.getExtendedKeyUsage()); - //cs.setNameConstraints(selector.getNameConstraints()); - cs.setPolicy(selector.getPolicy()); - cs.setSubjectPublicKeyAlgID(selector.getSubjectPublicKeyAlgID()); - cs.setSubject(selector.getSubjectAsBytes()); - cs.setIssuer(selector.getIssuerAsBytes()); - } - catch (IOException e) - { - throw new IllegalArgumentException("error in passed in selector: " + e); - } - cs.setKeyUsage(selector.getKeyUsage()); - cs.setPrivateKeyValid(selector.getPrivateKeyValid()); - cs.setSerialNumber(selector.getSerialNumber()); - cs.setSubjectKeyIdentifier(selector.getSubjectKeyIdentifier()); - cs.setSubjectPublicKey(selector.getSubjectPublicKey()); - return cs; - } - -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509Util.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509Util.java deleted file mode 100644 index 93ec8b638..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509Util.java +++ /dev/null @@ -1,397 +0,0 @@ -package org.spongycastle.x509; - -import java.io.IOException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.SecureRandom; -import java.security.Security; -import java.security.Signature; -import java.security.SignatureException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.spongycastle.asn1.nist.NISTObjectIdentifiers; -import org.spongycastle.asn1.oiw.OIWObjectIdentifiers; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.pkcs.RSASSAPSSparams; -import org.spongycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x9.X9ObjectIdentifiers; -import org.spongycastle.jce.X509Principal; -import org.spongycastle.util.Strings; - -class X509Util -{ - private static Hashtable algorithms = new Hashtable(); - private static Hashtable params = new Hashtable(); - private static Set noParams = new HashSet(); - - static - { - algorithms.put("MD2WITHRSAENCRYPTION", PKCSObjectIdentifiers.md2WithRSAEncryption); - algorithms.put("MD2WITHRSA", PKCSObjectIdentifiers.md2WithRSAEncryption); - algorithms.put("MD5WITHRSAENCRYPTION", PKCSObjectIdentifiers.md5WithRSAEncryption); - algorithms.put("MD5WITHRSA", PKCSObjectIdentifiers.md5WithRSAEncryption); - algorithms.put("SHA1WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha1WithRSAEncryption); - algorithms.put("SHA1WITHRSA", PKCSObjectIdentifiers.sha1WithRSAEncryption); - algorithms.put("SHA224WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha224WithRSAEncryption); - algorithms.put("SHA224WITHRSA", PKCSObjectIdentifiers.sha224WithRSAEncryption); - algorithms.put("SHA256WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha256WithRSAEncryption); - algorithms.put("SHA256WITHRSA", PKCSObjectIdentifiers.sha256WithRSAEncryption); - algorithms.put("SHA384WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha384WithRSAEncryption); - algorithms.put("SHA384WITHRSA", PKCSObjectIdentifiers.sha384WithRSAEncryption); - algorithms.put("SHA512WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha512WithRSAEncryption); - algorithms.put("SHA512WITHRSA", PKCSObjectIdentifiers.sha512WithRSAEncryption); - algorithms.put("SHA1WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA224WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA256WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA384WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("SHA512WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); - algorithms.put("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160); - algorithms.put("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160); - algorithms.put("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128); - algorithms.put("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128); - algorithms.put("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256); - algorithms.put("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256); - algorithms.put("SHA1WITHDSA", X9ObjectIdentifiers.id_dsa_with_sha1); - algorithms.put("DSAWITHSHA1", X9ObjectIdentifiers.id_dsa_with_sha1); - algorithms.put("SHA224WITHDSA", NISTObjectIdentifiers.dsa_with_sha224); - algorithms.put("SHA256WITHDSA", NISTObjectIdentifiers.dsa_with_sha256); - algorithms.put("SHA384WITHDSA", NISTObjectIdentifiers.dsa_with_sha384); - algorithms.put("SHA512WITHDSA", NISTObjectIdentifiers.dsa_with_sha512); - algorithms.put("SHA1WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA1); - algorithms.put("ECDSAWITHSHA1", X9ObjectIdentifiers.ecdsa_with_SHA1); - algorithms.put("SHA224WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); - algorithms.put("SHA256WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); - algorithms.put("SHA384WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); - algorithms.put("SHA512WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); - algorithms.put("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); - algorithms.put("GOST3411WITHGOST3410-94", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); - algorithms.put("GOST3411WITHECGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - algorithms.put("GOST3411WITHECGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - algorithms.put("GOST3411WITHGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - - // - // According to RFC 3279, the ASN.1 encoding SHALL (id-dsa-with-sha1) or MUST (ecdsa-with-SHA*) omit the parameters field. - // The parameters field SHALL be NULL for RSA based signature algorithms. - // - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA1); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA224); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA256); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA384); - noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA512); - noParams.add(X9ObjectIdentifiers.id_dsa_with_sha1); - noParams.add(NISTObjectIdentifiers.dsa_with_sha224); - noParams.add(NISTObjectIdentifiers.dsa_with_sha256); - noParams.add(NISTObjectIdentifiers.dsa_with_sha384); - noParams.add(NISTObjectIdentifiers.dsa_with_sha512); - - // - // RFC 4491 - // - noParams.add(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); - noParams.add(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); - - // - // explicit params - // - AlgorithmIdentifier sha1AlgId = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, new DERNull()); - params.put("SHA1WITHRSAANDMGF1", creatPSSParams(sha1AlgId, 20)); - - AlgorithmIdentifier sha224AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha224, new DERNull()); - params.put("SHA224WITHRSAANDMGF1", creatPSSParams(sha224AlgId, 28)); - - AlgorithmIdentifier sha256AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, new DERNull()); - params.put("SHA256WITHRSAANDMGF1", creatPSSParams(sha256AlgId, 32)); - - AlgorithmIdentifier sha384AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha384, new DERNull()); - params.put("SHA384WITHRSAANDMGF1", creatPSSParams(sha384AlgId, 48)); - - AlgorithmIdentifier sha512AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512, new DERNull()); - params.put("SHA512WITHRSAANDMGF1", creatPSSParams(sha512AlgId, 64)); - } - - private static RSASSAPSSparams creatPSSParams(AlgorithmIdentifier hashAlgId, int saltSize) - { - return new RSASSAPSSparams( - hashAlgId, - new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, hashAlgId), - new ASN1Integer(saltSize), - new ASN1Integer(1)); - } - - static ASN1ObjectIdentifier getAlgorithmOID( - String algorithmName) - { - algorithmName = Strings.toUpperCase(algorithmName); - - if (algorithms.containsKey(algorithmName)) - { - return (ASN1ObjectIdentifier)algorithms.get(algorithmName); - } - - return new ASN1ObjectIdentifier(algorithmName); - } - - static AlgorithmIdentifier getSigAlgID( - ASN1ObjectIdentifier sigOid, - String algorithmName) - { - if (noParams.contains(sigOid)) - { - return new AlgorithmIdentifier(sigOid); - } - - algorithmName = Strings.toUpperCase(algorithmName); - - if (params.containsKey(algorithmName)) - { - return new AlgorithmIdentifier(sigOid, (ASN1Encodable)params.get(algorithmName)); - } - else - { - return new AlgorithmIdentifier(sigOid, new DERNull()); - } - } - - static Iterator getAlgNames() - { - Enumeration e = algorithms.keys(); - List l = new ArrayList(); - - while (e.hasMoreElements()) - { - l.add(e.nextElement()); - } - - return l.iterator(); - } - - static Signature getSignatureInstance( - String algorithm) - throws NoSuchAlgorithmException - { - return Signature.getInstance(algorithm); - } - - static Signature getSignatureInstance( - String algorithm, - String provider) - throws NoSuchProviderException, NoSuchAlgorithmException - { - if (provider != null) - { - return Signature.getInstance(algorithm, provider); - } - else - { - return Signature.getInstance(algorithm); - } - } - - static byte[] calculateSignature( - ASN1ObjectIdentifier sigOid, - String sigName, - PrivateKey key, - SecureRandom random, - ASN1Encodable object) - throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException - { - Signature sig; - - if (sigOid == null) - { - throw new IllegalStateException("no signature algorithm specified"); - } - - sig = X509Util.getSignatureInstance(sigName); - - if (random != null) - { - sig.initSign(key, random); - } - else - { - sig.initSign(key); - } - - sig.update(object.toASN1Primitive().getEncoded(ASN1Encoding.DER)); - - return sig.sign(); - } - - static byte[] calculateSignature( - ASN1ObjectIdentifier sigOid, - String sigName, - String provider, - PrivateKey key, - SecureRandom random, - ASN1Encodable object) - throws IOException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException - { - Signature sig; - - if (sigOid == null) - { - throw new IllegalStateException("no signature algorithm specified"); - } - - sig = X509Util.getSignatureInstance(sigName, provider); - - if (random != null) - { - sig.initSign(key, random); - } - else - { - sig.initSign(key); - } - - sig.update(object.toASN1Primitive().getEncoded(ASN1Encoding.DER)); - - return sig.sign(); - } - - static class Implementation - { - Object engine; - Provider provider; - - Implementation( - Object engine, - Provider provider) - { - this.engine = engine; - this.provider = provider; - } - - Object getEngine() - { - return engine; - } - - Provider getProvider() - { - return provider; - } - } - - /** - * see if we can find an algorithm (or its alias and what it represents) in - * the property table for the given provider. - */ - static Implementation getImplementation( - String baseName, - String algorithm, - Provider prov) - throws NoSuchAlgorithmException - { - algorithm = Strings.toUpperCase(algorithm); - - String alias; - - while ((alias = prov.getProperty("Alg.Alias." + baseName + "." + algorithm)) != null) - { - algorithm = alias; - } - - String className = prov.getProperty(baseName + "." + algorithm); - - if (className != null) - { - try - { - Class cls; - ClassLoader clsLoader = prov.getClass().getClassLoader(); - - if (clsLoader != null) - { - cls = clsLoader.loadClass(className); - } - else - { - cls = Class.forName(className); - } - - return new Implementation(cls.newInstance(), prov); - } - catch (ClassNotFoundException e) - { - throw new IllegalStateException( - "algorithm " + algorithm + " in provider " + prov.getName() + " but no class \"" + className + "\" found!"); - } - catch (Exception e) - { - throw new IllegalStateException( - "algorithm " + algorithm + " in provider " + prov.getName() + " but class \"" + className + "\" inaccessible!"); - } - } - - throw new NoSuchAlgorithmException("cannot find implementation " + algorithm + " for provider " + prov.getName()); - } - - /** - * return an implementation for a given algorithm/provider. - * If the provider is null, we grab the first avalaible who has the required algorithm. - */ - static Implementation getImplementation( - String baseName, - String algorithm) - throws NoSuchAlgorithmException - { - Provider[] prov = Security.getProviders(); - - // - // search every provider looking for the algorithm we want. - // - for (int i = 0; i != prov.length; i++) - { - // - // try case insensitive - // - Implementation imp = getImplementation(baseName, Strings.toUpperCase(algorithm), prov[i]); - if (imp != null) - { - return imp; - } - - try - { - imp = getImplementation(baseName, algorithm, prov[i]); - } - catch (NoSuchAlgorithmException e) - { - // continue - } - } - - throw new NoSuchAlgorithmException("cannot find implementation " + algorithm); - } - - static Provider getProvider(String provider) - throws NoSuchProviderException - { - Provider prov = Security.getProvider(provider); - - if (prov == null) - { - throw new NoSuchProviderException("Provider " + provider + " not found"); - } - - return prov; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509V1CertificateGenerator.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509V1CertificateGenerator.java deleted file mode 100644 index d038b5cfd..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509V1CertificateGenerator.java +++ /dev/null @@ -1,341 +0,0 @@ -package org.spongycastle.x509; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.Date; -import java.util.Iterator; - -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.DERBitString; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x509.TBSCertificate; -import org.spongycastle.asn1.x509.Time; -import org.spongycastle.asn1.x509.V1TBSCertificateGenerator; -import org.spongycastle.asn1.x509.Certificate; -import org.spongycastle.asn1.x509.X509Name; -import org.spongycastle.jce.provider.X509CertificateObject; - -/** - * class to produce an X.509 Version 1 certificate. - * @deprecated use org.spongycastle.cert.X509v1CertificateBuilder. - */ -public class X509V1CertificateGenerator -{ - private V1TBSCertificateGenerator tbsGen; - private ASN1ObjectIdentifier sigOID; - private AlgorithmIdentifier sigAlgId; - private String signatureAlgorithm; - - public X509V1CertificateGenerator() - { - tbsGen = new V1TBSCertificateGenerator(); - } - - /** - * reset the generator - */ - public void reset() - { - tbsGen = new V1TBSCertificateGenerator(); - } - - /** - * set the serial number for the certificate. - */ - public void setSerialNumber( - BigInteger serialNumber) - { - if (serialNumber.compareTo(BigInteger.ZERO) <= 0) - { - throw new IllegalArgumentException("serial number must be a positive integer"); - } - - tbsGen.setSerialNumber(new ASN1Integer(serialNumber)); - } - - /** - * Set the issuer distinguished name - the issuer is the entity whose private key is used to sign the - * certificate. - */ - public void setIssuerDN( - X509Name issuer) - { - tbsGen.setIssuer(issuer); - } - - public void setNotBefore( - Date date) - { - tbsGen.setStartDate(new Time(date)); - } - - public void setNotAfter( - Date date) - { - tbsGen.setEndDate(new Time(date)); - } - - /** - * Set the subject distinguished name. The subject describes the entity associated with the public key. - */ - public void setSubjectDN( - X509Name subject) - { - tbsGen.setSubject(subject); - } - - public void setPublicKey( - PublicKey key) - { - try - { - tbsGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo((ASN1Sequence)new ASN1InputStream( - new ByteArrayInputStream(key.getEncoded())).readObject())); - } - catch (Exception e) - { - throw new IllegalArgumentException("unable to process key - " + e.toString()); - } - } - - /** - * Set the signature algorithm. This can be either a name or an OID, names - * are treated as case insensitive. - * - * @param signatureAlgorithm string representation of the algorithm name. - */ - public void setSignatureAlgorithm( - String signatureAlgorithm) - { - this.signatureAlgorithm = signatureAlgorithm; - - try - { - sigOID = X509Util.getAlgorithmOID(signatureAlgorithm); - } - catch (Exception e) - { - throw new IllegalArgumentException("Unknown signature type requested"); - } - - sigAlgId = X509Util.getSigAlgID(sigOID, signatureAlgorithm); - - tbsGen.setSignature(sigAlgId); - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider "SC". - * @deprecated use generate(key, "SC") - */ - public X509Certificate generateX509Certificate( - PrivateKey key) - throws SecurityException, SignatureException, InvalidKeyException - { - try - { - return generateX509Certificate(key, "SC", null); - } - catch (NoSuchProviderException e) - { - throw new SecurityException("BC provider not installed!"); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider "SC" and the passed in source of randomness - * @deprecated use generate(key, random, "SC") - */ - public X509Certificate generateX509Certificate( - PrivateKey key, - SecureRandom random) - throws SecurityException, SignatureException, InvalidKeyException - { - try - { - return generateX509Certificate(key, "SC", random); - } - catch (NoSuchProviderException e) - { - throw new SecurityException("BC provider not installed!"); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing, and the passed in source - * of randomness (if required). - * @deprecated use generate() - */ - public X509Certificate generateX509Certificate( - PrivateKey key, - String provider) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - return generateX509Certificate(key, provider, null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing, and the passed in source - * of randomness (if required). - * @deprecated use generate() - */ - public X509Certificate generateX509Certificate( - PrivateKey key, - String provider, - SecureRandom random) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - try - { - return generate(key, provider, random); - } - catch (NoSuchProviderException e) - { - throw e; - } - catch (SignatureException e) - { - throw e; - } - catch (InvalidKeyException e) - { - throw e; - } - catch (GeneralSecurityException e) - { - throw new SecurityException("exception: " + e); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider. - *

- * Note: this differs from the deprecated method in that the default provider is - * used - not "SC". - *

- */ - public X509Certificate generate( - PrivateKey key) - throws CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - return generate(key, (SecureRandom)null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider and the passed in source of randomness - *

- * Note: this differs from the deprecated method in that the default provider is - * used - not "SC". - *

- */ - public X509Certificate generate( - PrivateKey key, - SecureRandom random) - throws CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - TBSCertificate tbsCert = tbsGen.generateTBSCertificate(); - byte[] signature; - - try - { - signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, key, random, tbsCert); - } - catch (IOException e) - { - throw new ExtCertificateEncodingException("exception encoding TBS cert", e); - } - - return generateJcaObject(tbsCert, signature); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing, and the passed in source - * of randomness (if required). - */ - public X509Certificate generate( - PrivateKey key, - String provider) - throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - return generate(key, provider, null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing, and the passed in source - * of randomness (if required). - */ - public X509Certificate generate( - PrivateKey key, - String provider, - SecureRandom random) - throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - TBSCertificate tbsCert = tbsGen.generateTBSCertificate(); - byte[] signature; - - try - { - signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, provider, key, random, tbsCert); - } - catch (IOException e) - { - throw new ExtCertificateEncodingException("exception encoding TBS cert", e); - } - - return generateJcaObject(tbsCert, signature); - } - - private X509Certificate generateJcaObject(TBSCertificate tbsCert, byte[] signature) - throws CertificateEncodingException - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(tbsCert); - v.add(sigAlgId); - v.add(new DERBitString(signature)); - - try - { - return new X509CertificateObject(Certificate.getInstance(new DERSequence(v))); - } - catch (CertificateParsingException e) - { - throw new ExtCertificateEncodingException("exception producing certificate object", e); - } - } - - /** - * Return an iterator of the signature names supported by the generator. - * - * @return an iterator containing recognised names. - */ - public Iterator getSignatureAlgNames() - { - return X509Util.getAlgNames(); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509V2CRLGenerator.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509V2CRLGenerator.java deleted file mode 100644 index 8da36afb8..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509V2CRLGenerator.java +++ /dev/null @@ -1,430 +0,0 @@ -package org.spongycastle.x509; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.security.cert.CRLException; -import java.security.cert.X509CRL; -import java.security.cert.X509CRLEntry; -import java.util.Date; -import java.util.Iterator; -import java.util.Set; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.ASN1GeneralizedTime; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.DERBitString; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.CertificateList; -import org.spongycastle.asn1.x509.Extensions; -import org.spongycastle.asn1.x509.TBSCertList; -import org.spongycastle.asn1.x509.Time; -import org.spongycastle.asn1.x509.V2TBSCertListGenerator; -import org.spongycastle.asn1.x509.X509Extensions; -import org.spongycastle.asn1.x509.X509ExtensionsGenerator; -import org.spongycastle.asn1.x509.X509Name; -import org.spongycastle.jce.provider.X509CRLObject; - -/** - * class to produce an X.509 Version 2 CRL. - * @deprecated use org.spongycastle.cert.X509v2CRLBuilder. - */ -public class X509V2CRLGenerator -{ - private V2TBSCertListGenerator tbsGen; - private ASN1ObjectIdentifier sigOID; - private AlgorithmIdentifier sigAlgId; - private String signatureAlgorithm; - private X509ExtensionsGenerator extGenerator; - - public X509V2CRLGenerator() - { - tbsGen = new V2TBSCertListGenerator(); - extGenerator = new X509ExtensionsGenerator(); - } - - /** - * reset the generator - */ - public void reset() - { - tbsGen = new V2TBSCertListGenerator(); - extGenerator.reset(); - } - - /** - * Set the issuer distinguished name - the issuer is the entity whose private key is used to sign the - * certificate. - */ - public void setIssuerDN( - X509Name issuer) - { - tbsGen.setIssuer(issuer); - } - - public void setThisUpdate( - Date date) - { - tbsGen.setThisUpdate(new Time(date)); - } - - public void setNextUpdate( - Date date) - { - tbsGen.setNextUpdate(new Time(date)); - } - - /** - * Reason being as indicated by CRLReason, i.e. CRLReason.keyCompromise - * or 0 if CRLReason is not to be used - **/ - public void addCRLEntry(BigInteger userCertificate, Date revocationDate, int reason) - { - tbsGen.addCRLEntry(new ASN1Integer(userCertificate), new Time(revocationDate), reason); - } - - /** - * Add a CRL entry with an Invalidity Date extension as well as a CRLReason extension. - * Reason being as indicated by CRLReason, i.e. CRLReason.keyCompromise - * or 0 if CRLReason is not to be used - **/ - public void addCRLEntry(BigInteger userCertificate, Date revocationDate, int reason, Date invalidityDate) - { - tbsGen.addCRLEntry(new ASN1Integer(userCertificate), new Time(revocationDate), reason, new ASN1GeneralizedTime(invalidityDate)); - } - - /** - * Add a CRL entry with extensions. - **/ - public void addCRLEntry(BigInteger userCertificate, Date revocationDate, X509Extensions extensions) - { - tbsGen.addCRLEntry(new ASN1Integer(userCertificate), new Time(revocationDate), Extensions.getInstance(extensions)); - } - - /** - * Add the CRLEntry objects contained in a previous CRL. - * - * @param other the X509CRL to source the other entries from. - */ - public void addCRL(X509CRL other) - throws CRLException - { - Set revocations = other.getRevokedCertificates(); - - if (revocations != null) - { - Iterator it = revocations.iterator(); - while (it.hasNext()) - { - X509CRLEntry entry = (X509CRLEntry)it.next(); - - ASN1InputStream aIn = new ASN1InputStream(entry.getEncoded()); - - try - { - tbsGen.addCRLEntry(ASN1Sequence.getInstance(aIn.readObject())); - } - catch (IOException e) - { - throw new CRLException("exception processing encoding of CRL: " + e.toString()); - } - } - } - } - - /** - * Set the signature algorithm. This can be either a name or an OID, names - * are treated as case insensitive. - * - * @param signatureAlgorithm string representation of the algorithm name. - */ - public void setSignatureAlgorithm( - String signatureAlgorithm) - { - this.signatureAlgorithm = signatureAlgorithm; - - try - { - sigOID = X509Util.getAlgorithmOID(signatureAlgorithm); - } - catch (Exception e) - { - throw new IllegalArgumentException("Unknown signature type requested"); - } - - sigAlgId = X509Util.getSigAlgID(sigOID, signatureAlgorithm); - - tbsGen.setSignature(sigAlgId); - } - - /** - * add a given extension field for the standard extensions tag (tag 0) - */ - public void addExtension( - String oid, - boolean critical, - ASN1Encodable value) - { - this.addExtension(new ASN1ObjectIdentifier(oid), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 0) - */ - public void addExtension( - ASN1ObjectIdentifier oid, - boolean critical, - ASN1Encodable value) - { - extGenerator.addExtension(new ASN1ObjectIdentifier(oid.getId()), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 0) - */ - public void addExtension( - String oid, - boolean critical, - byte[] value) - { - this.addExtension(new ASN1ObjectIdentifier(oid), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 0) - */ - public void addExtension( - ASN1ObjectIdentifier oid, - boolean critical, - byte[] value) - { - extGenerator.addExtension(new ASN1ObjectIdentifier(oid.getId()), critical, value); - } - - /** - * generate an X509 CRL, based on the current issuer and subject - * using the default provider "SC". - * @deprecated use generate(key, "SC") - */ - public X509CRL generateX509CRL( - PrivateKey key) - throws SecurityException, SignatureException, InvalidKeyException - { - try - { - return generateX509CRL(key, "SC", null); - } - catch (NoSuchProviderException e) - { - throw new SecurityException("BC provider not installed!"); - } - } - - /** - * generate an X509 CRL, based on the current issuer and subject - * using the default provider "SC" and an user defined SecureRandom object as - * source of randomness. - * @deprecated use generate(key, random, "SC") - */ - public X509CRL generateX509CRL( - PrivateKey key, - SecureRandom random) - throws SecurityException, SignatureException, InvalidKeyException - { - try - { - return generateX509CRL(key, "SC", random); - } - catch (NoSuchProviderException e) - { - throw new SecurityException("BC provider not installed!"); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the passed in provider for the signing. - * @deprecated use generate() - */ - public X509CRL generateX509CRL( - PrivateKey key, - String provider) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - return generateX509CRL(key, provider, null); - } - - /** - * generate an X509 CRL, based on the current issuer and subject, - * using the passed in provider for the signing. - * @deprecated use generate() - */ - public X509CRL generateX509CRL( - PrivateKey key, - String provider, - SecureRandom random) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - try - { - return generate(key, provider, random); - } - catch (NoSuchProviderException e) - { - throw e; - } - catch (SignatureException e) - { - throw e; - } - catch (InvalidKeyException e) - { - throw e; - } - catch (GeneralSecurityException e) - { - throw new SecurityException("exception: " + e); - } - } - - /** - * generate an X509 CRL, based on the current issuer and subject - * using the default provider. - *

- * Note: this differs from the deprecated method in that the default provider is - * used - not "SC". - *

- */ - public X509CRL generate( - PrivateKey key) - throws CRLException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - return generate(key, (SecureRandom)null); - } - - /** - * generate an X509 CRL, based on the current issuer and subject - * using the default provider and an user defined SecureRandom object as - * source of randomness. - *

- * Note: this differs from the deprecated method in that the default provider is - * used - not "SC". - *

- */ - public X509CRL generate( - PrivateKey key, - SecureRandom random) - throws CRLException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - TBSCertList tbsCrl = generateCertList(); - byte[] signature; - - try - { - signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, key, random, tbsCrl); - } - catch (IOException e) - { - throw new ExtCRLException("cannot generate CRL encoding", e); - } - - return generateJcaObject(tbsCrl, signature); - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the passed in provider for the signing. - */ - public X509CRL generate( - PrivateKey key, - String provider) - throws CRLException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - return generate(key, provider, null); - } - - /** - * generate an X509 CRL, based on the current issuer and subject, - * using the passed in provider for the signing. - */ - public X509CRL generate( - PrivateKey key, - String provider, - SecureRandom random) - throws CRLException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - TBSCertList tbsCrl = generateCertList(); - byte[] signature; - - try - { - signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, provider, key, random, tbsCrl); - } - catch (IOException e) - { - throw new ExtCRLException("cannot generate CRL encoding", e); - } - - return generateJcaObject(tbsCrl, signature); - } - - private TBSCertList generateCertList() - { - if (!extGenerator.isEmpty()) - { - tbsGen.setExtensions(extGenerator.generate()); - } - - return tbsGen.generateTBSCertList(); - } - - private X509CRL generateJcaObject(TBSCertList tbsCrl, byte[] signature) - throws CRLException - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(tbsCrl); - v.add(sigAlgId); - v.add(new DERBitString(signature)); - - return new X509CRLObject(new CertificateList(new DERSequence(v))); - } - - /** - * Return an iterator of the signature names supported by the generator. - * - * @return an iterator containing recognised names. - */ - public Iterator getSignatureAlgNames() - { - return X509Util.getAlgNames(); - } - - private static class ExtCRLException - extends CRLException - { - Throwable cause; - - ExtCRLException(String message, Throwable cause) - { - super(message); - this.cause = cause; - } - - public Throwable getCause() - { - return cause; - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509V3CertificateGenerator.java b/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509V3CertificateGenerator.java deleted file mode 100644 index e58310e2a..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.3/org/spongycastle/x509/X509V3CertificateGenerator.java +++ /dev/null @@ -1,491 +0,0 @@ -package org.spongycastle.x509; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.Date; -import java.util.Iterator; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DERBitString; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x509.TBSCertificate; -import org.spongycastle.asn1.x509.Time; -import org.spongycastle.asn1.x509.V3TBSCertificateGenerator; -import org.spongycastle.asn1.x509.Certificate; -import org.spongycastle.asn1.x509.X509ExtensionsGenerator; -import org.spongycastle.asn1.x509.X509Name; -import org.spongycastle.jce.provider.X509CertificateObject; -import org.spongycastle.x509.extension.X509ExtensionUtil; - -/** - * class to produce an X.509 Version 3 certificate. - * @deprecated use org.spongycastle.cert.X509v3CertificateBuilder. - */ -public class X509V3CertificateGenerator -{ - private V3TBSCertificateGenerator tbsGen; - private ASN1ObjectIdentifier sigOID; - private AlgorithmIdentifier sigAlgId; - private String signatureAlgorithm; - private X509ExtensionsGenerator extGenerator; - - public X509V3CertificateGenerator() - { - tbsGen = new V3TBSCertificateGenerator(); - extGenerator = new X509ExtensionsGenerator(); - } - - /** - * reset the generator - */ - public void reset() - { - tbsGen = new V3TBSCertificateGenerator(); - extGenerator.reset(); - } - - /** - * set the serial number for the certificate. - */ - public void setSerialNumber( - BigInteger serialNumber) - { - if (serialNumber.compareTo(BigInteger.ZERO) <= 0) - { - throw new IllegalArgumentException("serial number must be a positive integer"); - } - - tbsGen.setSerialNumber(new ASN1Integer(serialNumber)); - } - - /** - * Set the issuer distinguished name - the issuer is the entity whose private key is used to sign the - * certificate. - */ - public void setIssuerDN( - X509Name issuer) - { - tbsGen.setIssuer(issuer); - } - - public void setNotBefore( - Date date) - { - tbsGen.setStartDate(new Time(date)); - } - - public void setNotAfter( - Date date) - { - tbsGen.setEndDate(new Time(date)); - } - - /** - * Set the subject distinguished name. The subject describes the entity associated with the public key. - */ - public void setSubjectDN( - X509Name subject) - { - tbsGen.setSubject(subject); - } - - public void setPublicKey( - PublicKey key) - throws IllegalArgumentException - { - try - { - tbsGen.setSubjectPublicKeyInfo( - SubjectPublicKeyInfo.getInstance(new ASN1InputStream(key.getEncoded()).readObject())); - } - catch (Exception e) - { - throw new IllegalArgumentException("unable to process key - " + e.toString()); - } - } - - /** - * Set the signature algorithm. This can be either a name or an OID, names - * are treated as case insensitive. - * - * @param signatureAlgorithm string representation of the algorithm name. - */ - public void setSignatureAlgorithm( - String signatureAlgorithm) - { - this.signatureAlgorithm = signatureAlgorithm; - - try - { - sigOID = X509Util.getAlgorithmOID(signatureAlgorithm); - } - catch (Exception e) - { - throw new IllegalArgumentException("Unknown signature type requested: " + signatureAlgorithm); - } - - sigAlgId = X509Util.getSigAlgID(sigOID, signatureAlgorithm); - - tbsGen.setSignature(sigAlgId); - } - - /** - * Set the subject unique ID - note: it is very rare that it is correct to do this. - */ - public void setSubjectUniqueID(boolean[] uniqueID) - { - tbsGen.setSubjectUniqueID(booleanToBitString(uniqueID)); - } - - /** - * Set the issuer unique ID - note: it is very rare that it is correct to do this. - */ - public void setIssuerUniqueID(boolean[] uniqueID) - { - tbsGen.setIssuerUniqueID(booleanToBitString(uniqueID)); - } - - private DERBitString booleanToBitString(boolean[] id) - { - byte[] bytes = new byte[(id.length + 7) / 8]; - - for (int i = 0; i != id.length; i++) - { - bytes[i / 8] |= (id[i]) ? (1 << ((7 - (i % 8)))) : 0; - } - - int pad = id.length % 8; - - if (pad == 0) - { - return new DERBitString(bytes); - } - else - { - return new DERBitString(bytes, 8 - pad); - } - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - */ - public void addExtension( - String oid, - boolean critical, - ASN1Encodable value) - { - this.addExtension(new ASN1ObjectIdentifier(oid), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - */ - public void addExtension( - ASN1ObjectIdentifier oid, - boolean critical, - ASN1Encodable value) - { - extGenerator.addExtension(new ASN1ObjectIdentifier(oid.getId()), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - * The value parameter becomes the contents of the octet string associated - * with the extension. - */ - public void addExtension( - String oid, - boolean critical, - byte[] value) - { - this.addExtension(new ASN1ObjectIdentifier(oid), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - */ - public void addExtension( - ASN1ObjectIdentifier oid, - boolean critical, - byte[] value) - { - extGenerator.addExtension(new ASN1ObjectIdentifier(oid.getId()), critical, value); - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - * copying the extension value from another certificate. - * @throws CertificateParsingException if the extension cannot be extracted. - */ - public void copyAndAddExtension( - String oid, - boolean critical, - X509Certificate cert) - throws CertificateParsingException - { - byte[] extValue = cert.getExtensionValue(oid); - - if (extValue == null) - { - throw new CertificateParsingException("extension " + oid + " not present"); - } - - try - { - ASN1Encodable value = X509ExtensionUtil.fromExtensionValue(extValue); - - this.addExtension(oid, critical, value); - } - catch (IOException e) - { - throw new CertificateParsingException(e.toString()); - } - } - - /** - * add a given extension field for the standard extensions tag (tag 3) - * copying the extension value from another certificate. - * @throws CertificateParsingException if the extension cannot be extracted. - */ - public void copyAndAddExtension( - ASN1ObjectIdentifier oid, - boolean critical, - X509Certificate cert) - throws CertificateParsingException - { - this.copyAndAddExtension(oid.getId(), critical, cert); - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider "SC". - * @deprecated use generate(key, "SC") - */ - public X509Certificate generateX509Certificate( - PrivateKey key) - throws SecurityException, SignatureException, InvalidKeyException - { - try - { - return generateX509Certificate(key, "SC", null); - } - catch (NoSuchProviderException e) - { - throw new SecurityException("BC provider not installed!"); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider "SC", and the passed in source of randomness - * (if required). - * @deprecated use generate(key, random, "SC") - */ - public X509Certificate generateX509Certificate( - PrivateKey key, - SecureRandom random) - throws SecurityException, SignatureException, InvalidKeyException - { - try - { - return generateX509Certificate(key, "SC", random); - } - catch (NoSuchProviderException e) - { - throw new SecurityException("BC provider not installed!"); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing. - * @deprecated use generate() - */ - public X509Certificate generateX509Certificate( - PrivateKey key, - String provider) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - return generateX509Certificate(key, provider, null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing and the supplied source - * of randomness, if required. - * @deprecated use generate() - */ - public X509Certificate generateX509Certificate( - PrivateKey key, - String provider, - SecureRandom random) - throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException - { - try - { - return generate(key, provider, random); - } - catch (NoSuchProviderException e) - { - throw e; - } - catch (SignatureException e) - { - throw e; - } - catch (InvalidKeyException e) - { - throw e; - } - catch (GeneralSecurityException e) - { - throw new SecurityException("exception: " + e); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider. - *

- * Note: this differs from the deprecated method in that the default provider is - * used - not "SC". - *

- */ - public X509Certificate generate( - PrivateKey key) - throws CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - return generate(key, (SecureRandom)null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject - * using the default provider, and the passed in source of randomness - * (if required). - *

- * Note: this differs from the deprecated method in that the default provider is - * used - not "SC". - *

- */ - public X509Certificate generate( - PrivateKey key, - SecureRandom random) - throws CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - TBSCertificate tbsCert = generateTbsCert(); - byte[] signature; - - try - { - signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, key, random, tbsCert); - } - catch (IOException e) - { - throw new ExtCertificateEncodingException("exception encoding TBS cert", e); - } - - try - { - return generateJcaObject(tbsCert, signature); - } - catch (CertificateParsingException e) - { - throw new ExtCertificateEncodingException("exception producing certificate object", e); - } - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing. - */ - public X509Certificate generate( - PrivateKey key, - String provider) - throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - return generate(key, provider, null); - } - - /** - * generate an X509 certificate, based on the current issuer and subject, - * using the passed in provider for the signing and the supplied source - * of randomness, if required. - */ - public X509Certificate generate( - PrivateKey key, - String provider, - SecureRandom random) - throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - TBSCertificate tbsCert = generateTbsCert(); - byte[] signature; - - try - { - signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, provider, key, random, tbsCert); - } - catch (IOException e) - { - throw new ExtCertificateEncodingException("exception encoding TBS cert", e); - } - - try - { - return generateJcaObject(tbsCert, signature); - } - catch (CertificateParsingException e) - { - throw new ExtCertificateEncodingException("exception producing certificate object", e); - } - } - - private TBSCertificate generateTbsCert() - { - if (!extGenerator.isEmpty()) - { - tbsGen.setExtensions(extGenerator.generate()); - } - - return tbsGen.generateTBSCertificate(); - } - - private X509Certificate generateJcaObject(TBSCertificate tbsCert, byte[] signature) - throws CertificateParsingException - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(tbsCert); - v.add(sigAlgId); - v.add(new DERBitString(signature)); - - return new X509CertificateObject(Certificate.getInstance(new DERSequence(v))); - } - - /** - * Return an iterator of the signature names supported by the generator. - * - * @return an iterator containing recognised names. - */ - public Iterator getSignatureAlgNames() - { - return X509Util.getAlgNames(); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/BCECPrivateKey.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/BCECPrivateKey.java deleted file mode 100644 index 5c91202b1..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/BCECPrivateKey.java +++ /dev/null @@ -1,385 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.ec; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.math.BigInteger; -import java.util.Enumeration; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.DERBitString; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.DEROutputStream; -import org.spongycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.spongycastle.asn1.pkcs.PrivateKeyInfo; -import org.spongycastle.asn1.sec.ECPrivateKeyStructure; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x9.X962Parameters; -import org.spongycastle.asn1.x9.X9ECParameters; -import org.spongycastle.asn1.x9.X9ObjectIdentifiers; -import org.spongycastle.crypto.params.ECDomainParameters; -import org.spongycastle.crypto.params.ECPrivateKeyParameters; -import org.spongycastle.jcajce.provider.asymmetric.util.ECUtil; -import org.spongycastle.jcajce.provider.asymmetric.util.KeyUtil; -import org.spongycastle.jcajce.provider.asymmetric.util.PKCS12BagAttributeCarrierImpl; -import org.spongycastle.jcajce.provider.config.ProviderConfiguration; -import org.spongycastle.jce.interfaces.ECPointEncoder; -import org.spongycastle.jce.interfaces.ECPrivateKey; -import org.spongycastle.jce.interfaces.PKCS12BagAttributeCarrier; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.jce.spec.ECNamedCurveParameterSpec; -import org.spongycastle.jce.spec.ECParameterSpec; -import org.spongycastle.jce.spec.ECPrivateKeySpec; -import org.spongycastle.math.ec.ECCurve; -import org.spongycastle.math.ec.ECPoint; - -public class BCECPrivateKey - implements ECPrivateKey, PKCS12BagAttributeCarrier, ECPointEncoder -{ - private String algorithm = "EC"; - private boolean withCompression; - - private transient BigInteger d; - private transient ECParameterSpec ecSpec; - private transient ProviderConfiguration configuration; - private transient DERBitString publicKey; - - private transient PKCS12BagAttributeCarrierImpl attrCarrier = new PKCS12BagAttributeCarrierImpl(); - - protected BCECPrivateKey() - { - } - - BCECPrivateKey( - ECPrivateKey key, - ProviderConfiguration configuration) - { - this.d = key.getD(); - this.algorithm = key.getAlgorithm(); - this.ecSpec = key.getParameters(); - this.configuration = configuration; - } - - public BCECPrivateKey( - String algorithm, - ECPrivateKeySpec spec, - ProviderConfiguration configuration) - { - this.algorithm = algorithm; - this.d = spec.getD(); - this.ecSpec = spec.getParams(); - this.configuration = configuration; - } - - public BCECPrivateKey( - String algorithm, - ECPrivateKeyParameters params, - BCECPublicKey pubKey, - ECParameterSpec spec, - ProviderConfiguration configuration) - { - ECDomainParameters dp = params.getParameters(); - - this.algorithm = algorithm; - this.d = params.getD(); - this.configuration = configuration; - - if (spec == null) - { - this.ecSpec = new ECParameterSpec( - dp.getCurve(), - dp.getG(), - dp.getN(), - dp.getH(), - dp.getSeed()); - } - else - { - this.ecSpec = spec; - } - - publicKey = getPublicKeyDetails(pubKey); - } - - public BCECPrivateKey( - String algorithm, - ECPrivateKeyParameters params, - ProviderConfiguration configuration) - { - this.algorithm = algorithm; - this.d = params.getD(); - this.ecSpec = null; - this.configuration = configuration; - } - - public BCECPrivateKey( - String algorithm, - BCECPrivateKey key) - { - this.algorithm = algorithm; - this.d = key.d; - this.ecSpec = key.ecSpec; - this.withCompression = key.withCompression; - this.publicKey = key.publicKey; - this.attrCarrier = key.attrCarrier; - this.configuration = key.configuration; - } - - BCECPrivateKey( - PrivateKeyInfo info, - ProviderConfiguration configuration) - { - this.configuration = configuration; - - populateFromPrivKeyInfo(info); - } - - BCECPrivateKey( - String algorithm, - PrivateKeyInfo info, - ProviderConfiguration configuration) - { - this.configuration = configuration; - populateFromPrivKeyInfo(info); - this.algorithm = algorithm; - } - - private void populateFromPrivKeyInfo(PrivateKeyInfo info) - { - X962Parameters params = X962Parameters.getInstance(info.getAlgorithmId().getParameters()); - - if (params.isNamedCurve()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)params.getParameters(); - X9ECParameters ecP = ECUtil.getNamedCurveByOid(oid); - - ecSpec = new ECNamedCurveParameterSpec( - ECUtil.getCurveName(oid), - ecP.getCurve(), - ecP.getG(), - ecP.getN(), - ecP.getH(), - ecP.getSeed()); - } - else if (params.isImplicitlyCA()) - { - ecSpec = null; - } - else - { - X9ECParameters ecP = X9ECParameters.getInstance(params.getParameters()); - ecSpec = new ECParameterSpec(ecP.getCurve(), - ecP.getG(), - ecP.getN(), - ecP.getH(), - ecP.getSeed()); - } - - if (info.getPrivateKey() instanceof ASN1Integer) - { - ASN1Integer derD = ASN1Integer.getInstance(info.getPrivateKey()); - - this.d = derD.getValue(); - } - else - { - ECPrivateKeyStructure ec = new ECPrivateKeyStructure((ASN1Sequence)info.getPrivateKey()); - - this.d = ec.getKey(); - this.publicKey = ec.getPublicKey(); - } - } - - public String getAlgorithm() - { - return algorithm; - } - - /** - * return the encoding format we produce in getEncoded(). - * - * @return the string "PKCS#8" - */ - public String getFormat() - { - return "PKCS#8"; - } - - /** - * Return a PKCS8 representation of the key. The sequence returned - * represents a full PrivateKeyInfo object. - * - * @return a PKCS8 representation of the key. - */ - public byte[] getEncoded() - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - DEROutputStream dOut = new DEROutputStream(bOut); - X962Parameters params = null; - - if (ecSpec instanceof ECNamedCurveParameterSpec) - { - ASN1ObjectIdentifier curveOid = ECUtil.getNamedCurveOid(((ECNamedCurveParameterSpec)ecSpec).getName()); - - params = new X962Parameters(curveOid); - } - else if (ecSpec == null) - { - params = new X962Parameters(DERNull.INSTANCE); - } - else - { - ECParameterSpec p = (ECParameterSpec)ecSpec; - - ECPoint pG = p.getG().normalize(); - ECPoint g = pG.getCurve().createPoint(pG.getAffineXCoord().toBigInteger(), pG.getAffineYCoord().toBigInteger()); - - X9ECParameters ecP = new X9ECParameters( - p.getCurve(), - g, - p.getN(), - p.getH(), - p.getSeed()); - - params = new X962Parameters(ecP); - } - - PrivateKeyInfo info; - ECPrivateKeyStructure keyStructure; - - if (publicKey != null) - { - keyStructure = new ECPrivateKeyStructure(this.getD(), publicKey, params); - } - else - { - keyStructure = new ECPrivateKeyStructure(this.getD(), params); - } - - try - { - if (algorithm.equals("ECGOST3410")) - { - info = new PrivateKeyInfo(new AlgorithmIdentifier(CryptoProObjectIdentifiers.gostR3410_2001, params), keyStructure); - } - else - { - info = new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params), keyStructure); - } - - return KeyUtil.getEncodedPrivateKeyInfo(info); - } - catch (IOException e) - { - return null; - } - } - - public ECParameterSpec getParams() - { - return (ECParameterSpec)ecSpec; - } - - public ECParameterSpec getParameters() - { - return (ECParameterSpec)ecSpec; - } - - public BigInteger getD() - { - return d; - } - - public void setBagAttribute( - ASN1ObjectIdentifier oid, - ASN1Encodable attribute) - { - attrCarrier.setBagAttribute(oid, attribute); - } - - public ASN1Encodable getBagAttribute( - ASN1ObjectIdentifier oid) - { - return attrCarrier.getBagAttribute(oid); - } - - public Enumeration getBagAttributeKeys() - { - return attrCarrier.getBagAttributeKeys(); - } - - public void setPointFormat(String style) - { - withCompression = !("UNCOMPRESSED".equalsIgnoreCase(style)); - } - - ECParameterSpec engineGetSpec() - { - if (ecSpec != null) - { - return ecSpec; - } - - return BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa(); - } - - public boolean equals(Object o) - { - if (!(o instanceof BCECPrivateKey)) - { - return false; - } - - BCECPrivateKey other = (BCECPrivateKey)o; - - return getD().equals(other.getD()) && (engineGetSpec().equals(other.engineGetSpec())); - } - - public int hashCode() - { - return getD().hashCode() ^ engineGetSpec().hashCode(); - } - - private DERBitString getPublicKeyDetails(BCECPublicKey pub) - { - try - { - SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(pub.getEncoded())); - - return info.getPublicKeyData(); - } - catch (IOException e) - { // should never happen - return null; - } - } - - private void readObject( - ObjectInputStream in) - throws IOException, ClassNotFoundException - { - in.defaultReadObject(); - - byte[] enc = (byte[])in.readObject(); - - populateFromPrivKeyInfo(PrivateKeyInfo.getInstance(ASN1Primitive.fromByteArray(enc))); - - this.configuration = BouncyCastleProvider.CONFIGURATION; - this.attrCarrier = new PKCS12BagAttributeCarrierImpl(); - } - - private void writeObject( - ObjectOutputStream out) - throws IOException - { - out.defaultWriteObject(); - - out.writeObject(this.getEncoded()); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/BCECPublicKey.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/BCECPublicKey.java deleted file mode 100644 index 8f704ddc9..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/BCECPublicKey.java +++ /dev/null @@ -1,376 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.ec; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.DERBitString; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x9.X962Parameters; -import org.spongycastle.asn1.x9.X9ECParameters; -import org.spongycastle.asn1.x9.X9ECPoint; -import org.spongycastle.asn1.x9.X9IntegerConverter; -import org.spongycastle.asn1.x9.X9ObjectIdentifiers; -import org.spongycastle.crypto.params.ECDomainParameters; -import org.spongycastle.crypto.params.ECPublicKeyParameters; -import org.spongycastle.jcajce.provider.asymmetric.util.ECUtil; -import org.spongycastle.jcajce.provider.asymmetric.util.KeyUtil; -import org.spongycastle.jcajce.provider.config.ProviderConfiguration; -import org.spongycastle.jce.interfaces.ECPointEncoder; -import org.spongycastle.jce.interfaces.ECPublicKey; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.jce.spec.ECNamedCurveParameterSpec; -import org.spongycastle.jce.spec.ECParameterSpec; -import org.spongycastle.jce.spec.ECPublicKeySpec; -import org.spongycastle.math.ec.ECCurve; -import org.spongycastle.math.ec.ECPoint; - -public class BCECPublicKey - implements ECPublicKey, ECPointEncoder -{ - private String algorithm = "EC"; - private boolean withCompression; - - private transient org.spongycastle.math.ec.ECPoint q; - private transient ECParameterSpec ecSpec; - private transient ProviderConfiguration configuration; - - public BCECPublicKey( - String algorithm, - BCECPublicKey key - ) - { - this.algorithm = algorithm; - this.q = key.q; - this.ecSpec = key.ecSpec; - this.withCompression = key.withCompression; - this.configuration = key.configuration; - } - - public BCECPublicKey( - String algorithm, - ECPublicKeySpec spec, - ProviderConfiguration configuration) - { - this.algorithm = algorithm; - this.q = spec.getQ(); - this.configuration = configuration; - - if (spec.getParams() != null) - { - this.ecSpec = spec.getParams(); - } - else - { - if (q.getCurve() == null) - { - org.spongycastle.jce.spec.ECParameterSpec s = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa(); - - q = s.getCurve().createPoint(q.getX().toBigInteger(), q.getY().toBigInteger(), false); - } - this.ecSpec = null; - } - } - - public BCECPublicKey( - String algorithm, - ECPublicKeyParameters params, - ECParameterSpec spec, - ProviderConfiguration configuration) - { - ECDomainParameters dp = params.getParameters(); - - this.algorithm = algorithm; - this.q = params.getQ(); - this.configuration = configuration; - - if (spec == null) - { - this.ecSpec = new ECParameterSpec( - dp.getCurve(), - dp.getG(), - dp.getN(), - dp.getH(), - dp.getSeed()); - } - else - { - this.ecSpec = spec; - } - } - - public BCECPublicKey( - String algorithm, - ECPublicKeyParameters params, - ProviderConfiguration configuration) - { - this.algorithm = algorithm; - this.q = params.getQ(); - this.ecSpec = null; - this.configuration = configuration; - } - - BCECPublicKey( - ECPublicKey key, - ProviderConfiguration configuration) - { - this.q = key.getQ(); - this.algorithm = key.getAlgorithm(); - this.ecSpec = key.getParameters(); - this.configuration = configuration; - } - - BCECPublicKey( - String algorithm, - ECPoint q, - ECParameterSpec ecSpec, - ProviderConfiguration configuration) - { - this.algorithm = algorithm; - this.q = q; - this.ecSpec = ecSpec; - this.configuration = configuration; - } - - BCECPublicKey( - SubjectPublicKeyInfo info, - ProviderConfiguration configuration) - { - this.configuration = configuration; - - populateFromPubKeyInfo(info); - } - - BCECPublicKey( - String algorithm, - SubjectPublicKeyInfo info, - ProviderConfiguration configuration) - { - this.configuration = configuration; - populateFromPubKeyInfo(info); - this.algorithm = algorithm; - } - - private void populateFromPubKeyInfo(SubjectPublicKeyInfo info) - { - X962Parameters params = X962Parameters.getInstance(info.getAlgorithmId().getParameters()); - ECCurve curve; - - if (params.isNamedCurve()) - { - ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(params.getParameters()); - X9ECParameters ecP = ECUtil.getNamedCurveByOid(oid); - - ecSpec = new ECNamedCurveParameterSpec( - ECUtil.getCurveName(oid), - ecP.getCurve(), - ecP.getG(), - ecP.getN(), - ecP.getH(), - ecP.getSeed()); - curve = ((ECParameterSpec)ecSpec).getCurve(); - } - else if (params.isImplicitlyCA()) - { - ecSpec = null; - curve = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getCurve(); - } - else - { - X9ECParameters ecP = X9ECParameters.getInstance(params.getParameters()); - ecSpec = new ECParameterSpec( - ecP.getCurve(), - ecP.getG(), - ecP.getN(), - ecP.getH(), - ecP.getSeed()); - curve = ((ECParameterSpec)ecSpec).getCurve(); - } - - DERBitString bits = info.getPublicKeyData(); - byte[] data = bits.getBytes(); - ASN1OctetString key = new DEROctetString(data); - - // - // extra octet string - one of our old certs... - // - if (data[0] == 0x04 && data[1] == data.length - 2 - && (data[2] == 0x02 || data[2] == 0x03)) - { - int qLength = new X9IntegerConverter().getByteLength(curve); - - if (qLength >= data.length - 3) - { - try - { - key = (ASN1OctetString)ASN1Primitive.fromByteArray(data); - } - catch (IOException ex) - { - throw new IllegalArgumentException("error recovering public key"); - } - } - } - - X9ECPoint derQ = new X9ECPoint(curve, key); - - this.q = derQ.getPoint(); - } - - public String getAlgorithm() - { - return algorithm; - } - - public String getFormat() - { - return "X.509"; - } - - public byte[] getEncoded() - { - SubjectPublicKeyInfo info; - - X962Parameters params = null; - if (ecSpec instanceof ECNamedCurveParameterSpec) - { - ASN1ObjectIdentifier curveOid = ECUtil.getNamedCurveOid(((ECNamedCurveParameterSpec)ecSpec).getName()); - - if (curveOid == null) - { - curveOid = new ASN1ObjectIdentifier(((ECNamedCurveParameterSpec)ecSpec).getName()); - } - params = new X962Parameters(curveOid); - } - else if (ecSpec == null) - { - params = new X962Parameters(DERNull.INSTANCE); - } - else - { - ECParameterSpec p = (ECParameterSpec)ecSpec; - - ECCurve curve = p.getG().getCurve(); - ECPoint generator = curve.createPoint(p.getG().getX().toBigInteger(), p.getG().getY().toBigInteger(), withCompression); - - X9ECParameters ecP = new X9ECParameters( - p.getCurve(), generator, p.getN(), p.getH(), p.getSeed()); - - params = new X962Parameters(ecP); - } - - ECCurve curve = this.engineGetQ().getCurve(); - ECPoint point = curve.createPoint(this.getQ().getX().toBigInteger(), this.getQ().getY().toBigInteger(), withCompression); - ASN1OctetString p = ASN1OctetString.getInstance(new X9ECPoint(point)); - - info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params), p.getOctets()); - - return KeyUtil.getEncodedSubjectPublicKeyInfo(info); - } - - public ECParameterSpec getParams() - { - return (ECParameterSpec)ecSpec; - } - - public ECParameterSpec getParameters() - { - return (ECParameterSpec)ecSpec; - } - - public org.spongycastle.math.ec.ECPoint getQ() - { - if (ecSpec == null) - { - if (q instanceof org.spongycastle.math.ec.ECPoint.Fp) - { - return new org.spongycastle.math.ec.ECPoint.Fp(null, q.getX(), q.getY()); - } - else - { - return new org.spongycastle.math.ec.ECPoint.F2m(null, q.getX(), q.getY()); - } - } - - return q; - } - - public org.spongycastle.math.ec.ECPoint engineGetQ() - { - return q; - } - - public String toString() - { - StringBuffer buf = new StringBuffer(); - String nl = System.getProperty("line.separator"); - - buf.append("EC Public Key").append(nl); - buf.append(" X: ").append(this.getQ().getX().toBigInteger().toString(16)).append(nl); - buf.append(" Y: ").append(this.getQ().getY().toBigInteger().toString(16)).append(nl); - - return buf.toString(); - - } - - public void setPointFormat(String style) - { - withCompression = !("UNCOMPRESSED".equalsIgnoreCase(style)); - } - - ECParameterSpec engineGetSpec() - { - if (ecSpec != null) - { - return (ECParameterSpec)ecSpec; - } - - return BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa(); - } - - public boolean equals(Object o) - { - if (!(o instanceof BCECPublicKey)) - { - return false; - } - - BCECPublicKey other = (BCECPublicKey)o; - - return getQ().equals(other.getQ()) && (engineGetSpec().equals(other.engineGetSpec())); - } - - public int hashCode() - { - return getQ().hashCode() ^ engineGetSpec().hashCode(); - } - - private void readObject( - ObjectInputStream in) - throws IOException, ClassNotFoundException - { - in.defaultReadObject(); - - byte[] enc = (byte[])in.readObject(); - - populateFromPubKeyInfo(SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(enc))); - - this.configuration = BouncyCastleProvider.CONFIGURATION; - } - - private void writeObject( - ObjectOutputStream out) - throws IOException - { - out.defaultWriteObject(); - - out.writeObject(this.getEncoded()); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/KeyAgreementSpi.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/KeyAgreementSpi.java deleted file mode 100644 index 27c2eed1d..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/KeyAgreementSpi.java +++ /dev/null @@ -1,317 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.ec; - -import java.math.BigInteger; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.spec.AlgorithmParameterSpec; -import java.util.Hashtable; - -import javax.crypto.SecretKey; -import javax.crypto.ShortBufferException; -import javax.crypto.spec.SecretKeySpec; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.nist.NISTObjectIdentifiers; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.x9.X9IntegerConverter; -import org.spongycastle.crypto.BasicAgreement; -import org.spongycastle.crypto.CipherParameters; -import org.spongycastle.crypto.DerivationFunction; -import org.spongycastle.crypto.agreement.ECDHBasicAgreement; -import org.spongycastle.crypto.agreement.ECDHCBasicAgreement; -import org.spongycastle.crypto.agreement.ECMQVBasicAgreement; -import org.spongycastle.crypto.agreement.kdf.DHKDFParameters; -import org.spongycastle.crypto.agreement.kdf.ECDHKEKGenerator; -import org.spongycastle.crypto.digests.SHA1Digest; -import org.spongycastle.crypto.params.ECDomainParameters; -import org.spongycastle.crypto.params.ECPrivateKeyParameters; -import org.spongycastle.crypto.params.ECPublicKeyParameters; -import org.spongycastle.crypto.params.MQVPrivateParameters; -import org.spongycastle.crypto.params.MQVPublicParameters; -import org.spongycastle.jcajce.provider.asymmetric.util.ECUtil; -import org.spongycastle.jce.interfaces.ECPrivateKey; -import org.spongycastle.jce.interfaces.ECPublicKey; -import org.spongycastle.jce.interfaces.MQVPrivateKey; -import org.spongycastle.jce.interfaces.MQVPublicKey; -import org.spongycastle.util.Integers; - -/** - * Diffie-Hellman key agreement using elliptic curve keys, ala IEEE P1363 - * both the simple one, and the simple one with cofactors are supported. - * - * Also, MQV key agreement per SEC-1 - */ -public class KeyAgreementSpi - extends javax.crypto.KeyAgreementSpi -{ - private static final X9IntegerConverter converter = new X9IntegerConverter(); - private static final Hashtable algorithms = new Hashtable(); - - static - { - Integer i128 = Integers.valueOf(128); - Integer i192 = Integers.valueOf(192); - Integer i256 = Integers.valueOf(256); - - algorithms.put(NISTObjectIdentifiers.id_aes128_CBC.getId(), i128); - algorithms.put(NISTObjectIdentifiers.id_aes192_CBC.getId(), i192); - algorithms.put(NISTObjectIdentifiers.id_aes256_CBC.getId(), i256); - algorithms.put(NISTObjectIdentifiers.id_aes128_wrap.getId(), i128); - algorithms.put(NISTObjectIdentifiers.id_aes192_wrap.getId(), i192); - algorithms.put(NISTObjectIdentifiers.id_aes256_wrap.getId(), i256); - algorithms.put(PKCSObjectIdentifiers.id_alg_CMS3DESwrap.getId(), i192); - } - - private String kaAlgorithm; - private BigInteger result; - private ECDomainParameters parameters; - private BasicAgreement agreement; - private DerivationFunction kdf; - - private byte[] bigIntToBytes( - BigInteger r) - { - return converter.integerToBytes(r, converter.getByteLength(parameters.getG().getX())); - } - - protected KeyAgreementSpi( - String kaAlgorithm, - BasicAgreement agreement, - DerivationFunction kdf) - { - this.kaAlgorithm = kaAlgorithm; - this.agreement = agreement; - this.kdf = kdf; - } - - protected Key engineDoPhase( - Key key, - boolean lastPhase) - throws InvalidKeyException, IllegalStateException - { - if (parameters == null) - { - throw new IllegalStateException(kaAlgorithm + " not initialised."); - } - - if (!lastPhase) - { - throw new IllegalStateException(kaAlgorithm + " can only be between two parties."); - } - - CipherParameters pubKey; - if (agreement instanceof ECMQVBasicAgreement) - { - if (!(key instanceof MQVPublicKey)) - { - throw new InvalidKeyException(kaAlgorithm + " key agreement requires " - + getSimpleName(MQVPublicKey.class) + " for doPhase"); - } - - MQVPublicKey mqvPubKey = (MQVPublicKey)key; - ECPublicKeyParameters staticKey = (ECPublicKeyParameters) - ECUtil.generatePublicKeyParameter(mqvPubKey.getStaticKey()); - ECPublicKeyParameters ephemKey = (ECPublicKeyParameters) - ECUtil.generatePublicKeyParameter(mqvPubKey.getEphemeralKey()); - - pubKey = new MQVPublicParameters(staticKey, ephemKey); - - // TODO Validate that all the keys are using the same parameters? - } - else - { - if (!(key instanceof ECPublicKey)) - { - throw new InvalidKeyException(kaAlgorithm + " key agreement requires " - + getSimpleName(ECPublicKey.class) + " for doPhase"); - } - - pubKey = ECUtil.generatePublicKeyParameter((PublicKey)key); - - // TODO Validate that all the keys are using the same parameters? - } - - result = agreement.calculateAgreement(pubKey); - - return null; - } - - protected byte[] engineGenerateSecret() - throws IllegalStateException - { - if (kdf != null) - { - throw new UnsupportedOperationException( - "KDF can only be used when algorithm is known"); - } - - return bigIntToBytes(result); - } - - protected int engineGenerateSecret( - byte[] sharedSecret, - int offset) - throws IllegalStateException, ShortBufferException - { - byte[] secret = engineGenerateSecret(); - - if (sharedSecret.length - offset < secret.length) - { - throw new ShortBufferException(kaAlgorithm + " key agreement: need " + secret.length + " bytes"); - } - - System.arraycopy(secret, 0, sharedSecret, offset, secret.length); - - return secret.length; - } - - protected SecretKey engineGenerateSecret( - String algorithm) - throws NoSuchAlgorithmException - { - byte[] secret = bigIntToBytes(result); - - if (kdf != null) - { - if (!algorithms.containsKey(algorithm)) - { - throw new NoSuchAlgorithmException("unknown algorithm encountered: " + algorithm); - } - - int keySize = ((Integer)algorithms.get(algorithm)).intValue(); - - DHKDFParameters params = new DHKDFParameters(new ASN1ObjectIdentifier(algorithm), keySize, secret); - - byte[] keyBytes = new byte[keySize / 8]; - kdf.init(params); - kdf.generateBytes(keyBytes, 0, keyBytes.length); - secret = keyBytes; - } - else - { - // TODO Should we be ensuring the key is the right length? - } - - return new SecretKeySpec(secret, algorithm); - } - - protected void engineInit( - Key key, - AlgorithmParameterSpec params, - SecureRandom random) - throws InvalidKeyException, InvalidAlgorithmParameterException - { - initFromKey(key); - } - - protected void engineInit( - Key key, - SecureRandom random) - throws InvalidKeyException - { - initFromKey(key); - } - - private void initFromKey(Key key) - throws InvalidKeyException - { - if (agreement instanceof ECMQVBasicAgreement) - { - if (!(key instanceof MQVPrivateKey)) - { - throw new InvalidKeyException(kaAlgorithm + " key agreement requires " - + getSimpleName(MQVPrivateKey.class) + " for initialisation"); - } - - MQVPrivateKey mqvPrivKey = (MQVPrivateKey)key; - ECPrivateKeyParameters staticPrivKey = (ECPrivateKeyParameters) - ECUtil.generatePrivateKeyParameter(mqvPrivKey.getStaticPrivateKey()); - ECPrivateKeyParameters ephemPrivKey = (ECPrivateKeyParameters) - ECUtil.generatePrivateKeyParameter(mqvPrivKey.getEphemeralPrivateKey()); - - ECPublicKeyParameters ephemPubKey = null; - if (mqvPrivKey.getEphemeralPublicKey() != null) - { - ephemPubKey = (ECPublicKeyParameters) - ECUtil.generatePublicKeyParameter(mqvPrivKey.getEphemeralPublicKey()); - } - - MQVPrivateParameters localParams = new MQVPrivateParameters(staticPrivKey, ephemPrivKey, ephemPubKey); - this.parameters = staticPrivKey.getParameters(); - - // TODO Validate that all the keys are using the same parameters? - - agreement.init(localParams); - } - else - { - if (!(key instanceof ECPrivateKey)) - { - throw new InvalidKeyException(kaAlgorithm + " key agreement requires " - + getSimpleName(ECPrivateKey.class) + " for initialisation"); - } - - ECPrivateKeyParameters privKey = (ECPrivateKeyParameters)ECUtil.generatePrivateKeyParameter((PrivateKey)key); - this.parameters = privKey.getParameters(); - - agreement.init(privKey); - } - } - - private static String getSimpleName(Class clazz) - { - String fullName = clazz.getName(); - - return fullName.substring(fullName.lastIndexOf('.') + 1); - } - - public static class DH - extends KeyAgreementSpi - { - public DH() - { - super("ECDH", new ECDHBasicAgreement(), null); - } - } - - public static class DHC - extends KeyAgreementSpi - { - public DHC() - { - super("ECDHC", new ECDHCBasicAgreement(), null); - } - } - - public static class MQV - extends KeyAgreementSpi - { - public MQV() - { - super("ECMQV", new ECMQVBasicAgreement(), null); - } - } - - public static class DHwithSHA1KDF - extends KeyAgreementSpi - { - public DHwithSHA1KDF() - { - super("ECDHwithSHA1KDF", new ECDHBasicAgreement(), new ECDHKEKGenerator(new SHA1Digest())); - } - } - - public static class MQVwithSHA1KDF - extends KeyAgreementSpi - { - public MQVwithSHA1KDF() - { - super("ECMQVwithSHA1KDF", new ECMQVBasicAgreement(), new ECDHKEKGenerator(new SHA1Digest())); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/KeyFactorySpi.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/KeyFactorySpi.java deleted file mode 100644 index 76c11e0b5..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/KeyFactorySpi.java +++ /dev/null @@ -1,200 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.ec; - -import java.io.IOException; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.KeySpec; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.pkcs.PrivateKeyInfo; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x9.X9ObjectIdentifiers; -import org.spongycastle.jcajce.provider.asymmetric.util.BaseKeyFactorySpi; -import org.spongycastle.jcajce.provider.config.ProviderConfiguration; -import org.spongycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; -import org.spongycastle.jce.interfaces.ECPrivateKey; -import org.spongycastle.jce.interfaces.ECPublicKey; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.jce.spec.ECParameterSpec; -import org.spongycastle.jce.spec.ECPrivateKeySpec; -import org.spongycastle.jce.spec.ECPublicKeySpec; - -public class KeyFactorySpi - extends BaseKeyFactorySpi - implements AsymmetricKeyInfoConverter -{ - String algorithm; - ProviderConfiguration configuration; - - KeyFactorySpi( - String algorithm, - ProviderConfiguration configuration) - { - this.algorithm = algorithm; - this.configuration = configuration; - } - - protected Key engineTranslateKey( - Key key) - throws InvalidKeyException - { - if (key instanceof ECPublicKey) - { - return new BCECPublicKey((ECPublicKey)key, configuration); - } - else if (key instanceof ECPrivateKey) - { - return new BCECPrivateKey((ECPrivateKey)key, configuration); - } - - throw new InvalidKeyException("key type unknown"); - } - - protected KeySpec engineGetKeySpec( - Key key, - Class spec) - throws InvalidKeySpecException - { - if (spec.isAssignableFrom(org.spongycastle.jce.spec.ECPublicKeySpec.class) && key instanceof ECPublicKey) - { - ECPublicKey k = (ECPublicKey)key; - if (k.getParams() != null) - { - return new org.spongycastle.jce.spec.ECPublicKeySpec(k.getQ(), k.getParameters()); - } - else - { - ECParameterSpec implicitSpec = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa(); - - return new org.spongycastle.jce.spec.ECPublicKeySpec(k.getQ(), implicitSpec); - } - } - else if (spec.isAssignableFrom(org.spongycastle.jce.spec.ECPrivateKeySpec.class) && key instanceof ECPrivateKey) - { - ECPrivateKey k = (ECPrivateKey)key; - - if (k.getParams() != null) - { - return new org.spongycastle.jce.spec.ECPrivateKeySpec(k.getD(), k.getParameters()); - } - else - { - ECParameterSpec implicitSpec = configuration.getEcImplicitlyCa(); - - return new org.spongycastle.jce.spec.ECPrivateKeySpec(k.getD(), implicitSpec); - } - } - return super.engineGetKeySpec(key, spec); - } - - protected PrivateKey engineGeneratePrivate( - KeySpec keySpec) - throws InvalidKeySpecException - { - if (keySpec instanceof ECPrivateKeySpec) - { - return new BCECPrivateKey(algorithm, (ECPrivateKeySpec)keySpec, configuration); - } - - return super.engineGeneratePrivate(keySpec); - } - - protected PublicKey engineGeneratePublic( - KeySpec keySpec) - throws InvalidKeySpecException - { - if (keySpec instanceof ECPublicKeySpec) - { - return new BCECPublicKey(algorithm, (ECPublicKeySpec)keySpec, configuration); - } - - return super.engineGeneratePublic(keySpec); - } - - public PrivateKey generatePrivate(PrivateKeyInfo keyInfo) - throws IOException - { - ASN1ObjectIdentifier algOid = keyInfo.getPrivateKeyAlgorithm().getAlgorithm(); - - if (algOid.equals(X9ObjectIdentifiers.id_ecPublicKey)) - { - return new BCECPrivateKey(algorithm, keyInfo, configuration); - } - else - { - throw new IOException("algorithm identifier " + algOid + " in key not recognised"); - } - } - - public PublicKey generatePublic(SubjectPublicKeyInfo keyInfo) - throws IOException - { - ASN1ObjectIdentifier algOid = keyInfo.getAlgorithm().getAlgorithm(); - - if (algOid.equals(X9ObjectIdentifiers.id_ecPublicKey)) - { - return new BCECPublicKey(algorithm, keyInfo, configuration); - } - else - { - throw new IOException("algorithm identifier " + algOid + " in key not recognised"); - } - } - - public static class EC - extends KeyFactorySpi - { - public EC() - { - super("EC", BouncyCastleProvider.CONFIGURATION); - } - } - - public static class ECDSA - extends KeyFactorySpi - { - public ECDSA() - { - super("ECDSA", BouncyCastleProvider.CONFIGURATION); - } - } - - public static class ECGOST3410 - extends KeyFactorySpi - { - public ECGOST3410() - { - super("ECGOST3410", BouncyCastleProvider.CONFIGURATION); - } - } - - public static class ECDH - extends KeyFactorySpi - { - public ECDH() - { - super("ECDH", BouncyCastleProvider.CONFIGURATION); - } - } - - public static class ECDHC - extends KeyFactorySpi - { - public ECDHC() - { - super("ECDHC", BouncyCastleProvider.CONFIGURATION); - } - } - - public static class ECMQV - extends KeyFactorySpi - { - public ECMQV() - { - super("ECMQV", BouncyCastleProvider.CONFIGURATION); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/KeyPairGeneratorSpi.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/KeyPairGeneratorSpi.java deleted file mode 100644 index 8d74dd598..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/KeyPairGeneratorSpi.java +++ /dev/null @@ -1,259 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.ec; - -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidParameterException; -import java.security.KeyPair; -import java.security.SecureRandom; -import java.security.spec.AlgorithmParameterSpec; -import java.util.Hashtable; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.nist.NISTNamedCurves; -import org.spongycastle.asn1.sec.SECNamedCurves; -import org.spongycastle.asn1.teletrust.TeleTrusTNamedCurves; -import org.spongycastle.asn1.x9.X962NamedCurves; -import org.spongycastle.asn1.x9.X9ECParameters; -import org.spongycastle.crypto.AsymmetricCipherKeyPair; -import org.spongycastle.crypto.generators.ECKeyPairGenerator; -import org.spongycastle.crypto.params.ECDomainParameters; -import org.spongycastle.crypto.params.ECKeyGenerationParameters; -import org.spongycastle.crypto.params.ECPrivateKeyParameters; -import org.spongycastle.crypto.params.ECPublicKeyParameters; -import org.spongycastle.jcajce.provider.config.ProviderConfiguration; -import org.spongycastle.jce.ECNamedCurveTable; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.jce.spec.ECNamedCurveGenParameterSpec; -import org.spongycastle.jce.spec.ECNamedCurveParameterSpec; -import org.spongycastle.jce.spec.ECParameterSpec; -import org.spongycastle.util.Integers; - -public abstract class KeyPairGeneratorSpi - extends java.security.KeyPairGenerator -{ - public KeyPairGeneratorSpi(String algorithmName) - { - super(algorithmName); - } - - public static class EC - extends KeyPairGeneratorSpi - { - ECKeyGenerationParameters param; - ECKeyPairGenerator engine = new ECKeyPairGenerator(); - ECParameterSpec ecParams = null; - int strength = 239; - int certainty = 50; - SecureRandom random = new SecureRandom(); - boolean initialised = false; - String algorithm; - ProviderConfiguration configuration; - - static private Hashtable ecParameters; - - static { - ecParameters = new Hashtable(); - - ecParameters.put(Integers.valueOf(192), - ECNamedCurveTable.getParameterSpec("prime192v1")); - ecParameters.put(Integers.valueOf(239), - ECNamedCurveTable.getParameterSpec("prime239v1")); - ecParameters.put(Integers.valueOf(256), - ECNamedCurveTable.getParameterSpec("prime256v1")); - } - - public EC() - { - super("EC"); - this.algorithm = "EC"; - this.configuration = BouncyCastleProvider.CONFIGURATION; - } - - public EC( - String algorithm, - ProviderConfiguration configuration) - { - super(algorithm); - this.algorithm = algorithm; - this.configuration = configuration; - } - - public void initialize( - int strength, - SecureRandom random) - { - this.strength = strength; - this.random = random; - this.ecParams = (ECParameterSpec)ecParameters.get(Integers.valueOf(strength)); - - if (ecParams != null) - { - param = new ECKeyGenerationParameters(new ECDomainParameters(ecParams.getCurve(), ecParams.getG(), ecParams.getN()), random); - - engine.init(param); - initialised = true; - } - else - { - throw new InvalidParameterException("unknown key size."); - } - } - - public void initialize( - AlgorithmParameterSpec params, - SecureRandom random) - throws InvalidAlgorithmParameterException - { - if (params instanceof ECParameterSpec) - { - ECParameterSpec p = (ECParameterSpec)params; - this.ecParams = (ECParameterSpec)params; - - param = new ECKeyGenerationParameters(new ECDomainParameters(p.getCurve(), p.getG(), p.getN()), random); - - engine.init(param); - initialised = true; - } - else if (params instanceof ECNamedCurveGenParameterSpec) - { - String curveName; - - curveName = ((ECNamedCurveGenParameterSpec)params).getName(); - - X9ECParameters ecP = X962NamedCurves.getByName(curveName); - if (ecP == null) - { - ecP = SECNamedCurves.getByName(curveName); - if (ecP == null) - { - ecP = NISTNamedCurves.getByName(curveName); - } - if (ecP == null) - { - ecP = TeleTrusTNamedCurves.getByName(curveName); - } - if (ecP == null) - { - // See if it's actually an OID string (SunJSSE ServerHandshaker setupEphemeralECDHKeys bug) - try - { - ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(curveName); - ecP = X962NamedCurves.getByOID(oid); - if (ecP == null) - { - ecP = SECNamedCurves.getByOID(oid); - } - if (ecP == null) - { - ecP = NISTNamedCurves.getByOID(oid); - } - if (ecP == null) - { - ecP = TeleTrusTNamedCurves.getByOID(oid); - } - if (ecP == null) - { - throw new InvalidAlgorithmParameterException("unknown curve OID: " + curveName); - } - } - catch (IllegalArgumentException ex) - { - throw new InvalidAlgorithmParameterException("unknown curve name: " + curveName); - } - } - } - - this.ecParams = new ECNamedCurveParameterSpec( - curveName, - ecP.getCurve(), - ecP.getG(), - ecP.getN(), - ecP.getH(), - null); // ecP.getSeed()); Work-around JDK bug -- it won't look up named curves properly if seed is present - - param = new ECKeyGenerationParameters(new ECDomainParameters(ecParams.getCurve(), ecParams.getG(), ecParams.getN()), random); - - engine.init(param); - initialised = true; - } - else if (params == null && configuration.getEcImplicitlyCa() != null) - { - ECParameterSpec p = configuration.getEcImplicitlyCa(); - this.ecParams = (ECParameterSpec)params; - - param = new ECKeyGenerationParameters(new ECDomainParameters(p.getCurve(), p.getG(), p.getN()), random); - - engine.init(param); - initialised = true; - } - else if (params == null && configuration.getEcImplicitlyCa() == null) - { - throw new InvalidAlgorithmParameterException("null parameter passed but no implicitCA set"); - } - else - { - throw new InvalidAlgorithmParameterException("parameter object not a ECParameterSpec"); - } - } - - public KeyPair generateKeyPair() - { - if (!initialised) - { - throw new IllegalStateException("EC Key Pair Generator not initialised"); - } - - AsymmetricCipherKeyPair pair = engine.generateKeyPair(); - ECPublicKeyParameters pub = (ECPublicKeyParameters)pair.getPublic(); - ECPrivateKeyParameters priv = (ECPrivateKeyParameters)pair.getPrivate(); - - if (ecParams == null) - { - return new KeyPair(new BCECPublicKey(algorithm, pub, configuration), - new BCECPrivateKey(algorithm, priv, configuration)); - } - else - { - ECParameterSpec p = (ECParameterSpec)ecParams; - BCECPublicKey pubKey = new BCECPublicKey(algorithm, pub, p, configuration); - - return new KeyPair(pubKey, new BCECPrivateKey(algorithm, priv, pubKey, p, configuration)); - } - } - } - - public static class ECDSA - extends EC - { - public ECDSA() - { - super("ECDSA", BouncyCastleProvider.CONFIGURATION); - } - } - - public static class ECDH - extends EC - { - public ECDH() - { - super("ECDH", BouncyCastleProvider.CONFIGURATION); - } - } - - public static class ECDHC - extends EC - { - public ECDHC() - { - super("ECDHC", BouncyCastleProvider.CONFIGURATION); - } - } - - public static class ECMQV - extends EC - { - public ECMQV() - { - super("ECMQV", BouncyCastleProvider.CONFIGURATION); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/SignatureSpi.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/SignatureSpi.java deleted file mode 100644 index 9d61a76bc..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ec/SignatureSpi.java +++ /dev/null @@ -1,355 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.ec; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; - -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.crypto.CipherParameters; -import org.spongycastle.crypto.DSA; -import org.spongycastle.crypto.Digest; -import org.spongycastle.crypto.digests.NullDigest; -import org.spongycastle.crypto.digests.RIPEMD160Digest; -import org.spongycastle.crypto.digests.SHA1Digest; -import org.spongycastle.crypto.digests.SHA224Digest; -import org.spongycastle.crypto.digests.SHA256Digest; -import org.spongycastle.crypto.digests.SHA384Digest; -import org.spongycastle.crypto.digests.SHA512Digest; -import org.spongycastle.crypto.params.ParametersWithRandom; -import org.spongycastle.crypto.signers.ECDSASigner; -import org.spongycastle.crypto.signers.ECNRSigner; -import org.spongycastle.jcajce.provider.asymmetric.util.DSABase; -import org.spongycastle.jcajce.provider.asymmetric.util.DSAEncoder; -import org.spongycastle.jcajce.provider.asymmetric.util.ECUtil; -import org.spongycastle.jce.interfaces.ECKey; -import org.spongycastle.jce.interfaces.ECPublicKey; -import org.spongycastle.jce.provider.BouncyCastleProvider; - -public class SignatureSpi - extends DSABase -{ - SignatureSpi(Digest digest, DSA signer, DSAEncoder encoder) - { - super("ECDSA", digest, signer, encoder); - } - - protected void engineInitVerify(PublicKey publicKey) - throws InvalidKeyException - { - CipherParameters param; - - if (publicKey instanceof ECPublicKey) - { - param = ECUtil.generatePublicKeyParameter(publicKey); - } - else - { - try - { - byte[] bytes = publicKey.getEncoded(); - - publicKey = BouncyCastleProvider.getPublicKey(SubjectPublicKeyInfo.getInstance(bytes)); - - if (publicKey instanceof ECPublicKey) - { - param = ECUtil.generatePublicKeyParameter(publicKey); - } - else - { - throw new InvalidKeyException("can't recognise key type in ECDSA based signer"); - } - } - catch (Exception e) - { - throw new InvalidKeyException("can't recognise key type in ECDSA based signer"); - } - } - - digest.reset(); - - signer.init(false, param); - } - - protected void doEngineInitSign( - PrivateKey privateKey, - SecureRandom random) - throws InvalidKeyException - { - CipherParameters param; - - if (privateKey instanceof ECKey) - { - param = ECUtil.generatePrivateKeyParameter(privateKey); - } - else - { - throw new InvalidKeyException("can't recognise key type in ECDSA based signer"); - } - - digest.reset(); - - if (random != null) - { - signer.init(true, new ParametersWithRandom(param, random)); - } - else - { - signer.init(true, param); - } - } - - static public class ecDSA - extends SignatureSpi - { - public ecDSA() - { - super(new SHA1Digest(), new ECDSASigner(), new StdDSAEncoder()); - } - } - - static public class ecDSAnone - extends SignatureSpi - { - public ecDSAnone() - { - super(new NullDigest(), new ECDSASigner(), new StdDSAEncoder()); - } - } - - static public class ecDSA224 - extends SignatureSpi - { - public ecDSA224() - { - super(new SHA224Digest(), new ECDSASigner(), new StdDSAEncoder()); - } - } - - static public class ecDSA256 - extends SignatureSpi - { - public ecDSA256() - { - super(new SHA256Digest(), new ECDSASigner(), new StdDSAEncoder()); - } - } - - static public class ecDSA384 - extends SignatureSpi - { - public ecDSA384() - { - super(new SHA384Digest(), new ECDSASigner(), new StdDSAEncoder()); - } - } - - static public class ecDSA512 - extends SignatureSpi - { - public ecDSA512() - { - super(new SHA512Digest(), new ECDSASigner(), new StdDSAEncoder()); - } - } - - static public class ecDSARipeMD160 - extends SignatureSpi - { - public ecDSARipeMD160() - { - super(new RIPEMD160Digest(), new ECDSASigner(), new StdDSAEncoder()); - } - } - - static public class ecNR - extends SignatureSpi - { - public ecNR() - { - super(new SHA1Digest(), new ECNRSigner(), new StdDSAEncoder()); - } - } - - static public class ecNR224 - extends SignatureSpi - { - public ecNR224() - { - super(new SHA224Digest(), new ECNRSigner(), new StdDSAEncoder()); - } - } - - static public class ecNR256 - extends SignatureSpi - { - public ecNR256() - { - super(new SHA256Digest(), new ECNRSigner(), new StdDSAEncoder()); - } - } - - static public class ecNR384 - extends SignatureSpi - { - public ecNR384() - { - super(new SHA384Digest(), new ECNRSigner(), new StdDSAEncoder()); - } - } - - static public class ecNR512 - extends SignatureSpi - { - public ecNR512() - { - super(new SHA512Digest(), new ECNRSigner(), new StdDSAEncoder()); - } - } - - static public class ecCVCDSA - extends SignatureSpi - { - public ecCVCDSA() - { - super(new SHA1Digest(), new ECDSASigner(), new CVCDSAEncoder()); - } - } - - static public class ecCVCDSA224 - extends SignatureSpi - { - public ecCVCDSA224() - { - super(new SHA224Digest(), new ECDSASigner(), new CVCDSAEncoder()); - } - } - - static public class ecCVCDSA256 - extends SignatureSpi - { - public ecCVCDSA256() - { - super(new SHA256Digest(), new ECDSASigner(), new CVCDSAEncoder()); - } - } - - static public class ecCVCDSA384 - extends SignatureSpi - { - public ecCVCDSA384() - { - super(new SHA384Digest(), new ECDSASigner(), new CVCDSAEncoder()); - } - } - - static public class ecCVCDSA512 - extends SignatureSpi - { - public ecCVCDSA512() - { - super(new SHA512Digest(), new ECDSASigner(), new CVCDSAEncoder()); - } - } - - private static class StdDSAEncoder - implements DSAEncoder - { - public byte[] encode( - BigInteger r, - BigInteger s) - throws IOException - { - ASN1EncodableVector v = new ASN1EncodableVector(); - - v.add(new ASN1Integer(r)); - v.add(new ASN1Integer(s)); - - return new DERSequence(v).getEncoded(ASN1Encoding.DER); - } - - public BigInteger[] decode( - byte[] encoding) - throws IOException - { - ASN1Sequence s = (ASN1Sequence)ASN1Primitive.fromByteArray(encoding); - BigInteger[] sig = new BigInteger[2]; - - sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue(); - sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue(); - - return sig; - } - } - - private static class CVCDSAEncoder - implements DSAEncoder - { - public byte[] encode( - BigInteger r, - BigInteger s) - throws IOException - { - byte[] first = makeUnsigned(r); - byte[] second = makeUnsigned(s); - byte[] res; - - if (first.length > second.length) - { - res = new byte[first.length * 2]; - } - else - { - res = new byte[second.length * 2]; - } - - System.arraycopy(first, 0, res, res.length / 2 - first.length, first.length); - System.arraycopy(second, 0, res, res.length - second.length, second.length); - - return res; - } - - - private byte[] makeUnsigned(BigInteger val) - { - byte[] res = val.toByteArray(); - - if (res[0] == 0) - { - byte[] tmp = new byte[res.length - 1]; - - System.arraycopy(res, 1, tmp, 0, tmp.length); - - return tmp; - } - - return res; - } - - public BigInteger[] decode( - byte[] encoding) - throws IOException - { - BigInteger[] sig = new BigInteger[2]; - - byte[] first = new byte[encoding.length / 2]; - byte[] second = new byte[encoding.length / 2]; - - System.arraycopy(encoding, 0, first, 0, first.length); - System.arraycopy(encoding, first.length, second, 0, second.length); - - sig[0] = new BigInteger(1, first); - sig[1] = new BigInteger(1, second); - - return sig; - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/BCECGOST3410PrivateKey.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/BCECGOST3410PrivateKey.java deleted file mode 100644 index d322a172e..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/BCECGOST3410PrivateKey.java +++ /dev/null @@ -1,359 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.ecgost; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.math.BigInteger; -import java.util.Enumeration; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.DERBitString; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.DEROutputStream; -import org.spongycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.spongycastle.asn1.cryptopro.ECGOST3410NamedCurves; -import org.spongycastle.asn1.pkcs.PrivateKeyInfo; -import org.spongycastle.asn1.sec.ECPrivateKeyStructure; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x9.X962Parameters; -import org.spongycastle.asn1.x9.X9ECParameters; -import org.spongycastle.asn1.x9.X9ObjectIdentifiers; -import org.spongycastle.crypto.params.ECDomainParameters; -import org.spongycastle.crypto.params.ECPrivateKeyParameters; -import org.spongycastle.jcajce.provider.asymmetric.util.ECUtil; -import org.spongycastle.jcajce.provider.asymmetric.util.KeyUtil; -import org.spongycastle.jcajce.provider.asymmetric.util.PKCS12BagAttributeCarrierImpl; -import org.spongycastle.jce.interfaces.ECPointEncoder; -import org.spongycastle.jce.interfaces.ECPrivateKey; -import org.spongycastle.jce.interfaces.PKCS12BagAttributeCarrier; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.jce.spec.ECNamedCurveParameterSpec; -import org.spongycastle.jce.spec.ECParameterSpec; -import org.spongycastle.jce.spec.ECPrivateKeySpec; -import org.spongycastle.math.ec.ECCurve; -import org.spongycastle.math.ec.ECPoint; - -public class BCECGOST3410PrivateKey - implements ECPrivateKey, PKCS12BagAttributeCarrier, ECPointEncoder -{ - private String algorithm = "ECGOST3410"; - private boolean withCompression; - - private transient BigInteger d; - private transient ECParameterSpec ecSpec; - private transient DERBitString publicKey; - private transient PKCS12BagAttributeCarrierImpl attrCarrier = new PKCS12BagAttributeCarrierImpl(); - - protected BCECGOST3410PrivateKey() - { - } - - BCECGOST3410PrivateKey( - ECPrivateKey key) - { - this.d = key.getD(); - this.algorithm = key.getAlgorithm(); - this.ecSpec = key.getParameters(); - } - - public BCECGOST3410PrivateKey( - ECPrivateKeySpec spec) - { - this.d = spec.getD(); - this.ecSpec = spec.getParams(); - } - - public BCECGOST3410PrivateKey( - String algorithm, - ECPrivateKeyParameters params, - BCECGOST3410PublicKey pubKey, - ECParameterSpec spec) - { - ECDomainParameters dp = params.getParameters(); - - this.algorithm = algorithm; - this.d = params.getD(); - - if (spec == null) - { - this.ecSpec = new ECParameterSpec( - dp.getCurve(), - dp.getG(), - dp.getN(), - dp.getH(), - dp.getSeed()); - } - else - { - this.ecSpec = spec; - } - - publicKey = getPublicKeyDetails(pubKey); - } - - public BCECGOST3410PrivateKey( - String algorithm, - ECPrivateKeyParameters params) - { - this.algorithm = algorithm; - this.d = params.getD(); - this.ecSpec = null; - } - - public BCECGOST3410PrivateKey( - String algorithm, - BCECGOST3410PrivateKey key) - { - this.algorithm = algorithm; - this.d = key.d; - this.ecSpec = key.ecSpec; - this.withCompression = key.withCompression; - this.publicKey = key.publicKey; - this.attrCarrier = key.attrCarrier; - } - - BCECGOST3410PrivateKey( - PrivateKeyInfo info) - { - populateFromPrivKeyInfo(info); - } - - private void populateFromPrivKeyInfo(PrivateKeyInfo info) - { - X962Parameters params = X962Parameters.getInstance(info.getAlgorithmId().getParameters()); - - if (params.isNamedCurve()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)params.getParameters(); - ECDomainParameters ecP = ECGOST3410NamedCurves.getByOID(oid); - - ecSpec = new ECNamedCurveParameterSpec( - ECUtil.getCurveName(oid), - ecP.getCurve(), - ecP.getG(), - ecP.getN(), - ecP.getH(), - ecP.getSeed()); - } - else if (params.isImplicitlyCA()) - { - ecSpec = null; - } - else - { - X9ECParameters ecP = X9ECParameters.getInstance(params.getParameters()); - ecSpec = new ECParameterSpec(ecP.getCurve(), - ecP.getG(), - ecP.getN(), - ecP.getH(), - ecP.getSeed()); - } - - if (info.getPrivateKey() instanceof ASN1Integer) - { - ASN1Integer derD = ASN1Integer.getInstance(info.getPrivateKey()); - - this.d = derD.getValue(); - } - else - { - ECPrivateKeyStructure ec = new ECPrivateKeyStructure((ASN1Sequence)info.getPrivateKey()); - - this.d = ec.getKey(); - this.publicKey = ec.getPublicKey(); - } - } - - public String getAlgorithm() - { - return algorithm; - } - - /** - * return the encoding format we produce in getEncoded(). - * - * @return the string "PKCS#8" - */ - public String getFormat() - { - return "PKCS#8"; - } - - /** - * Return a PKCS8 representation of the key. The sequence returned - * represents a full PrivateKeyInfo object. - * - * @return a PKCS8 representation of the key. - */ - public byte[] getEncoded() - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - DEROutputStream dOut = new DEROutputStream(bOut); - X962Parameters params = null; - - if (ecSpec instanceof ECNamedCurveParameterSpec) - { - ASN1ObjectIdentifier curveOid = ECUtil.getNamedCurveOid(((ECNamedCurveParameterSpec)ecSpec).getName()); - - params = new X962Parameters(curveOid); - } - else if (ecSpec == null) - { - params = new X962Parameters(DERNull.INSTANCE); - } - else - { - ECParameterSpec p = (ECParameterSpec)ecSpec; - - ECPoint pG = p.getG().normalize(); - ECPoint g = pG.getCurve().createPoint(pG.getAffineXCoord().toBigInteger(), pG.getAffineYCoord().toBigInteger()); - - X9ECParameters ecP = new X9ECParameters( - p.getCurve(), - g, - p.getN(), - p.getH(), - p.getSeed()); - - params = new X962Parameters(ecP); - } - - PrivateKeyInfo info; - ECPrivateKeyStructure keyStructure; - - if (publicKey != null) - { - keyStructure = new ECPrivateKeyStructure(this.getD(), publicKey, params); - } - else - { - keyStructure = new ECPrivateKeyStructure(this.getD(), params); - } - - try - { - if (algorithm.equals("ECGOST3410")) - { - info = new PrivateKeyInfo(new AlgorithmIdentifier(CryptoProObjectIdentifiers.gostR3410_2001, params), keyStructure); - } - else - { - info = new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params), keyStructure); - } - - return KeyUtil.getEncodedPrivateKeyInfo(info); - } - catch (IOException e) - { - return null; - } - } - - public ECParameterSpec getParams() - { - return (ECParameterSpec)ecSpec; - } - - public ECParameterSpec getParameters() - { - return (ECParameterSpec)ecSpec; - } - - public BigInteger getD() - { - return d; - } - - public void setBagAttribute( - ASN1ObjectIdentifier oid, - ASN1Encodable attribute) - { - attrCarrier.setBagAttribute(oid, attribute); - } - - public ASN1Encodable getBagAttribute( - ASN1ObjectIdentifier oid) - { - return attrCarrier.getBagAttribute(oid); - } - - public Enumeration getBagAttributeKeys() - { - return attrCarrier.getBagAttributeKeys(); - } - - public void setPointFormat(String style) - { - withCompression = !("UNCOMPRESSED".equalsIgnoreCase(style)); - } - - ECParameterSpec engineGetSpec() - { - if (ecSpec != null) - { - return ecSpec; - } - - return BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa(); - } - - public boolean equals(Object o) - { - if (!(o instanceof BCECGOST3410PrivateKey)) - { - return false; - } - - BCECGOST3410PrivateKey other = (BCECGOST3410PrivateKey)o; - - return getD().equals(other.getD()) && (engineGetSpec().equals(other.engineGetSpec())); - } - - public int hashCode() - { - return getD().hashCode() ^ engineGetSpec().hashCode(); - } - - private DERBitString getPublicKeyDetails(BCECGOST3410PublicKey pub) - { - try - { - SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(pub.getEncoded())); - - return info.getPublicKeyData(); - } - catch (IOException e) - { // should never happen - return null; - } - } - - - private void readObject( - ObjectInputStream in) - throws IOException, ClassNotFoundException - { - in.defaultReadObject(); - - byte[] enc = (byte[])in.readObject(); - - populateFromPrivKeyInfo(PrivateKeyInfo.getInstance(ASN1Primitive.fromByteArray(enc))); - - this.attrCarrier = new PKCS12BagAttributeCarrierImpl(); - } - - private void writeObject( - ObjectOutputStream out) - throws IOException - { - out.defaultWriteObject(); - - out.writeObject(this.getEncoded()); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/BCECGOST3410PublicKey.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/BCECGOST3410PublicKey.java deleted file mode 100644 index 75e6e1155..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/BCECGOST3410PublicKey.java +++ /dev/null @@ -1,454 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.ecgost; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.math.BigInteger; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.DERBitString; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.spongycastle.asn1.cryptopro.ECGOST3410NamedCurves; -import org.spongycastle.asn1.cryptopro.GOST3410PublicKeyAlgParameters; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x9.X962Parameters; -import org.spongycastle.asn1.x9.X9ECParameters; -import org.spongycastle.asn1.x9.X9ECPoint; -import org.spongycastle.asn1.x9.X9IntegerConverter; -import org.spongycastle.asn1.x9.X9ObjectIdentifiers; -import org.spongycastle.crypto.params.ECDomainParameters; -import org.spongycastle.crypto.params.ECPublicKeyParameters; -import org.spongycastle.jcajce.provider.asymmetric.util.ECUtil; -import org.spongycastle.jcajce.provider.asymmetric.util.KeyUtil; -import org.spongycastle.jce.ECGOST3410NamedCurveTable; -import org.spongycastle.jce.interfaces.ECPointEncoder; -import org.spongycastle.jce.interfaces.ECPublicKey; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.jce.spec.ECNamedCurveParameterSpec; -import org.spongycastle.jce.spec.ECParameterSpec; -import org.spongycastle.jce.spec.ECPublicKeySpec; -import org.spongycastle.math.ec.ECCurve; -import org.spongycastle.math.ec.ECPoint; - -public class BCECGOST3410PublicKey - implements ECPublicKey, ECPointEncoder -{ - private String algorithm = "ECGOST3410"; - private boolean withCompression; - - private transient org.spongycastle.math.ec.ECPoint q; - private transient ECParameterSpec ecSpec; - private transient GOST3410PublicKeyAlgParameters gostParams; - - public BCECGOST3410PublicKey( - String algorithm, - BCECGOST3410PublicKey key) - { - this.algorithm = algorithm; - this.q = key.q; - this.ecSpec = key.ecSpec; - this.withCompression = key.withCompression; - this.gostParams = key.gostParams; - } - - public BCECGOST3410PublicKey( - ECPublicKeySpec spec) - { - this.q = spec.getQ(); - - if (spec.getParams() != null) - { - this.ecSpec = spec.getParams(); - } - else - { - if (q.getCurve() == null) - { - org.spongycastle.jce.spec.ECParameterSpec s = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa(); - - q = s.getCurve().createPoint(q.getX().toBigInteger(), q.getY().toBigInteger(), false); - } - this.ecSpec = null; - } - } - - public BCECGOST3410PublicKey( - String algorithm, - ECPublicKeyParameters params, - ECParameterSpec spec) - { - ECDomainParameters dp = params.getParameters(); - - this.algorithm = algorithm; - this.q = params.getQ(); - - if (spec == null) - { - this.ecSpec = new ECParameterSpec( - dp.getCurve(), - dp.getG(), - dp.getN(), - dp.getH(), - dp.getSeed()); - } - else - { - this.ecSpec = spec; - } - } - - public BCECGOST3410PublicKey( - String algorithm, - ECPublicKeyParameters params) - { - this.algorithm = algorithm; - this.q = params.getQ(); - this.ecSpec = null; - } - - BCECGOST3410PublicKey( - ECPublicKey key) - { - this.q = key.getQ(); - this.algorithm = key.getAlgorithm(); - this.ecSpec = key.getParameters(); - } - - BCECGOST3410PublicKey( - String algorithm, - ECPoint q, - ECParameterSpec ecSpec) - { - this.algorithm = algorithm; - this.q = q; - this.ecSpec = ecSpec; - } - - BCECGOST3410PublicKey( - SubjectPublicKeyInfo info) - { - populateFromPubKeyInfo(info); - } - - private void populateFromPubKeyInfo(SubjectPublicKeyInfo info) - { - if (info.getAlgorithmId().getObjectId().equals(CryptoProObjectIdentifiers.gostR3410_2001)) - { - DERBitString bits = info.getPublicKeyData(); - ASN1OctetString key; - this.algorithm = "ECGOST3410"; - - try - { - key = (ASN1OctetString)ASN1Primitive.fromByteArray(bits.getBytes()); - } - catch (IOException ex) - { - throw new IllegalArgumentException("error recovering public key"); - } - - byte[] keyEnc = key.getOctets(); - byte[] x = new byte[32]; - byte[] y = new byte[32]; - - for (int i = 0; i != x.length; i++) - { - x[i] = keyEnc[32 - 1 - i]; - } - - for (int i = 0; i != y.length; i++) - { - y[i] = keyEnc[64 - 1 - i]; - } - - gostParams = new GOST3410PublicKeyAlgParameters((ASN1Sequence)info.getAlgorithmId().getParameters()); - - ECNamedCurveParameterSpec spec = ECGOST3410NamedCurveTable.getParameterSpec(ECGOST3410NamedCurves.getName(gostParams.getPublicKeyParamSet())); - - ecSpec = spec; - - this.q = spec.getCurve().createPoint(new BigInteger(1, x), new BigInteger(1, y), false); - } - else - { - X962Parameters params = X962Parameters.getInstance(info.getAlgorithmId().getParameters()); - ECCurve curve; - - if (params.isNamedCurve()) - { - ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(params.getParameters()); - X9ECParameters ecP = ECUtil.getNamedCurveByOid(oid); - - ecSpec = new ECNamedCurveParameterSpec( - ECUtil.getCurveName(oid), - ecP.getCurve(), - ecP.getG(), - ecP.getN(), - ecP.getH(), - ecP.getSeed()); - curve = ((ECParameterSpec)ecSpec).getCurve(); - } - else if (params.isImplicitlyCA()) - { - ecSpec = null; - curve = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa().getCurve(); - } - else - { - X9ECParameters ecP = X9ECParameters.getInstance(params.getParameters()); - ecSpec = new ECParameterSpec( - ecP.getCurve(), - ecP.getG(), - ecP.getN(), - ecP.getH(), - ecP.getSeed()); - curve = ((ECParameterSpec)ecSpec).getCurve(); - } - - DERBitString bits = info.getPublicKeyData(); - byte[] data = bits.getBytes(); - ASN1OctetString key = new DEROctetString(data); - - // - // extra octet string - one of our old certs... - // - if (data[0] == 0x04 && data[1] == data.length - 2 - && (data[2] == 0x02 || data[2] == 0x03)) - { - int qLength = new X9IntegerConverter().getByteLength(curve); - - if (qLength >= data.length - 3) - { - try - { - key = (ASN1OctetString)ASN1Primitive.fromByteArray(data); - } - catch (IOException ex) - { - throw new IllegalArgumentException("error recovering public key"); - } - } - } - - X9ECPoint derQ = new X9ECPoint(curve, key); - - this.q = derQ.getPoint(); - } - } - - public String getAlgorithm() - { - return algorithm; - } - - public String getFormat() - { - return "X.509"; - } - - public byte[] getEncoded() - { - SubjectPublicKeyInfo info; - - if (algorithm.equals("ECGOST3410")) - { - ASN1Encodable params = null; - if (gostParams != null) - { - params = gostParams; - } - else if (ecSpec instanceof ECNamedCurveParameterSpec) - { - params = new GOST3410PublicKeyAlgParameters( - ECGOST3410NamedCurves.getOID(((ECNamedCurveParameterSpec)ecSpec).getName()), - CryptoProObjectIdentifiers.gostR3411_94_CryptoProParamSet); - } - else - { - ECParameterSpec p = (ECParameterSpec)ecSpec; - - ECCurve curve = p.getG().getCurve(); - ECPoint generator = curve.createPoint(p.getG().getX().toBigInteger(), p.getG().getY().toBigInteger(), withCompression); - - X9ECParameters ecP = new X9ECParameters( - p.getCurve(), generator, p.getN(), p.getH(), p.getSeed()); - - params = new X962Parameters(ecP); - } - - ECPoint qq = this.getQ(); - ECPoint point = qq.getCurve().createPoint(qq.getX().toBigInteger(), qq.getY().toBigInteger(), false); - ASN1OctetString p = ASN1OctetString.getInstance(new X9ECPoint(point)); - - BigInteger bX = this.q.getX().toBigInteger(); - BigInteger bY = this.q.getY().toBigInteger(); - byte[] encKey = new byte[64]; - - byte[] val = bX.toByteArray(); - - for (int i = 0; i != 32; i++) - { - encKey[i] = val[val.length - 1 - i]; - } - - val = bY.toByteArray(); - - for (int i = 0; i != 32; i++) - { - encKey[32 + i] = val[val.length - 1 - i]; - } - - try - { - info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(CryptoProObjectIdentifiers.gostR3410_2001, params), new DEROctetString(encKey)); - } - catch (IOException e) - { - return null; - } - } - else - { - X962Parameters params = null; - if (ecSpec instanceof ECNamedCurveParameterSpec) - { - ASN1ObjectIdentifier curveOid = ECUtil.getNamedCurveOid(((ECNamedCurveParameterSpec)ecSpec).getName()); - - if (curveOid == null) - { - curveOid = new ASN1ObjectIdentifier(((ECNamedCurveParameterSpec)ecSpec).getName()); - } - params = new X962Parameters(curveOid); - } - else if (ecSpec == null) - { - params = new X962Parameters(DERNull.INSTANCE); - } - else - { - ECParameterSpec p = (ECParameterSpec)ecSpec; - - ECCurve curve = p.getG().getCurve(); - ECPoint generator = curve.createPoint(p.getG().getX().toBigInteger(), p.getG().getY().toBigInteger(), withCompression); - - X9ECParameters ecP = new X9ECParameters( - p.getCurve(), generator, p.getN(), p.getH(), p.getSeed()); - - params = new X962Parameters(ecP); - } - - ECCurve curve = this.engineGetQ().getCurve(); - ECPoint point = curve.createPoint(this.getQ().getX().toBigInteger(), this.getQ().getY().toBigInteger(), withCompression); - ASN1OctetString p = ASN1OctetString.getInstance(new X9ECPoint(point)); - - info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params), p.getOctets()); - } - - return KeyUtil.getEncodedSubjectPublicKeyInfo(info); - } - - public ECParameterSpec getParams() - { - return (ECParameterSpec)ecSpec; - } - - public ECParameterSpec getParameters() - { - return (ECParameterSpec)ecSpec; - } - - public org.spongycastle.math.ec.ECPoint getQ() - { - if (ecSpec == null) - { - if (q instanceof org.spongycastle.math.ec.ECPoint.Fp) - { - return new org.spongycastle.math.ec.ECPoint.Fp(null, q.getX(), q.getY()); - } - else - { - return new org.spongycastle.math.ec.ECPoint.F2m(null, q.getX(), q.getY()); - } - } - - return q; - } - - public org.spongycastle.math.ec.ECPoint engineGetQ() - { - return q; - } - - public String toString() - { - StringBuffer buf = new StringBuffer(); - String nl = System.getProperty("line.separator"); - - buf.append("EC Public Key").append(nl); - buf.append(" X: ").append(this.getQ().getX().toBigInteger().toString(16)).append(nl); - buf.append(" Y: ").append(this.getQ().getY().toBigInteger().toString(16)).append(nl); - - return buf.toString(); - - } - - public void setPointFormat(String style) - { - withCompression = !("UNCOMPRESSED".equalsIgnoreCase(style)); - } - - ECParameterSpec engineGetSpec() - { - if (ecSpec != null) - { - return (ECParameterSpec)ecSpec; - } - - return BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa(); - } - - public boolean equals(Object o) - { - if (!(o instanceof BCECGOST3410PublicKey)) - { - return false; - } - - BCECGOST3410PublicKey other = (BCECGOST3410PublicKey)o; - - return getQ().equals(other.getQ()) && (engineGetSpec().equals(other.engineGetSpec())); - } - - public int hashCode() - { - return getQ().hashCode() ^ engineGetSpec().hashCode(); - } - - private void readObject( - ObjectInputStream in) - throws IOException, ClassNotFoundException - { - in.defaultReadObject(); - - byte[] enc = (byte[])in.readObject(); - - populateFromPubKeyInfo(SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(enc))); - } - - private void writeObject( - ObjectOutputStream out) - throws IOException - { - out.defaultWriteObject(); - - out.writeObject(this.getEncoded()); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/KeyFactorySpi.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/KeyFactorySpi.java deleted file mode 100644 index 36847af27..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/KeyFactorySpi.java +++ /dev/null @@ -1,128 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.ecgost; - -import java.io.IOException; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.KeySpec; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.spongycastle.asn1.pkcs.PrivateKeyInfo; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.jcajce.provider.asymmetric.util.BaseKeyFactorySpi; -import org.spongycastle.jce.interfaces.ECPrivateKey; -import org.spongycastle.jce.interfaces.ECPublicKey; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.jce.spec.ECParameterSpec; -import org.spongycastle.jce.spec.ECPrivateKeySpec; -import org.spongycastle.jce.spec.ECPublicKeySpec; - -public class KeyFactorySpi - extends BaseKeyFactorySpi -{ - public KeyFactorySpi() - { - } - - protected KeySpec engineGetKeySpec( - Key key, - Class spec) - throws InvalidKeySpecException - { - if (spec.isAssignableFrom(org.spongycastle.jce.spec.ECPublicKeySpec.class) && key instanceof ECPublicKey) - { - ECPublicKey k = (ECPublicKey)key; - if (k.getParams() != null) - { - return new org.spongycastle.jce.spec.ECPublicKeySpec(k.getQ(), k.getParameters()); - } - else - { - ECParameterSpec implicitSpec = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa(); - - return new org.spongycastle.jce.spec.ECPublicKeySpec(k.getQ(), implicitSpec); - } - } - else if (spec.isAssignableFrom(org.spongycastle.jce.spec.ECPrivateKeySpec.class) && key instanceof ECPrivateKey) - { - ECPrivateKey k = (ECPrivateKey)key; - - if (k.getParams() != null) - { - return new org.spongycastle.jce.spec.ECPrivateKeySpec(k.getD(), k.getParameters()); - } - else - { - ECParameterSpec implicitSpec = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa(); - - return new org.spongycastle.jce.spec.ECPrivateKeySpec(k.getD(), implicitSpec); - } - } - - return super.engineGetKeySpec(key, spec); - } - - protected Key engineTranslateKey( - Key key) - throws InvalidKeyException - { - throw new InvalidKeyException("key type unknown"); - } - - protected PrivateKey engineGeneratePrivate( - KeySpec keySpec) - throws InvalidKeySpecException - { - if (keySpec instanceof ECPrivateKeySpec) - { - return new BCECGOST3410PrivateKey((ECPrivateKeySpec)keySpec); - } - - return super.engineGeneratePrivate(keySpec); - } - - protected PublicKey engineGeneratePublic( - KeySpec keySpec) - throws InvalidKeySpecException - { - if (keySpec instanceof ECPublicKeySpec) - { - return new BCECGOST3410PublicKey((ECPublicKeySpec)keySpec); - } - - return super.engineGeneratePublic(keySpec); - } - - public PrivateKey generatePrivate(PrivateKeyInfo keyInfo) - throws IOException - { - ASN1ObjectIdentifier algOid = keyInfo.getPrivateKeyAlgorithm().getAlgorithm(); - - if (algOid.equals(CryptoProObjectIdentifiers.gostR3410_2001)) - { - return new BCECGOST3410PrivateKey(keyInfo); - } - else - { - throw new IOException("algorithm identifier " + algOid + " in key not recognised"); - } - } - - public PublicKey generatePublic(SubjectPublicKeyInfo keyInfo) - throws IOException - { - ASN1ObjectIdentifier algOid = keyInfo.getAlgorithm().getAlgorithm(); - - if (algOid.equals(CryptoProObjectIdentifiers.gostR3410_2001)) - { - return new BCECGOST3410PublicKey(keyInfo); - } - else - { - throw new IOException("algorithm identifier " + algOid + " in key not recognised"); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/KeyPairGeneratorSpi.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/KeyPairGeneratorSpi.java deleted file mode 100644 index f950260e3..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/KeyPairGeneratorSpi.java +++ /dev/null @@ -1,144 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.ecgost; - -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidParameterException; -import java.security.KeyPair; -import java.security.SecureRandom; -import java.security.spec.AlgorithmParameterSpec; - -import org.spongycastle.asn1.cryptopro.ECGOST3410NamedCurves; -import org.spongycastle.crypto.AsymmetricCipherKeyPair; -import org.spongycastle.crypto.generators.ECKeyPairGenerator; -import org.spongycastle.crypto.params.ECDomainParameters; -import org.spongycastle.crypto.params.ECKeyGenerationParameters; -import org.spongycastle.crypto.params.ECPrivateKeyParameters; -import org.spongycastle.crypto.params.ECPublicKeyParameters; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.jce.spec.ECNamedCurveGenParameterSpec; -import org.spongycastle.jce.spec.ECNamedCurveParameterSpec; -import org.spongycastle.jce.spec.ECParameterSpec; - -public class KeyPairGeneratorSpi - extends java.security.KeyPairGenerator -{ - ECParameterSpec ecParams = null; - ECKeyPairGenerator engine = new ECKeyPairGenerator(); - - String algorithm = "ECGOST3410"; - ECKeyGenerationParameters param; - int strength = 239; - SecureRandom random = null; - boolean initialised = false; - - public KeyPairGeneratorSpi() - { - super("ECGOST3410"); - } - - public void initialize( - int strength, - SecureRandom random) - { - this.strength = strength; - this.random = random; - - if (ecParams != null) - { - param = new ECKeyGenerationParameters(new ECDomainParameters(ecParams.getCurve(), ecParams.getG(), ecParams.getN()), random); - - engine.init(param); - initialised = true; - } - else - { - throw new InvalidParameterException("unknown key size."); - } - } - - public void initialize( - AlgorithmParameterSpec params, - SecureRandom random) - throws InvalidAlgorithmParameterException - { - if (params instanceof ECParameterSpec) - { - ECParameterSpec p = (ECParameterSpec)params; - this.ecParams = p; - - param = new ECKeyGenerationParameters(new ECDomainParameters(p.getCurve(), p.getG(), p.getN()), random); - - engine.init(param); - initialised = true; - } - else if (params instanceof ECNamedCurveGenParameterSpec) - { - String curveName; - - curveName = ((ECNamedCurveGenParameterSpec)params).getName(); - - ECDomainParameters ecP = ECGOST3410NamedCurves.getByName(curveName); - if (ecP == null) - { - throw new InvalidAlgorithmParameterException("unknown curve name: " + curveName); - } - - this.ecParams = new ECNamedCurveParameterSpec( - curveName, - ecP.getCurve(), - ecP.getG(), - ecP.getN(), - ecP.getH(), - ecP.getSeed()); - - param = new ECKeyGenerationParameters(new ECDomainParameters(ecParams.getCurve(), ecParams.getG(), ecParams.getN()), random); - - engine.init(param); - initialised = true; - } - else if (params == null && BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa() != null) - { - ECParameterSpec p = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa(); - this.ecParams = null; - - param = new ECKeyGenerationParameters(new ECDomainParameters(p.getCurve(), p.getG(), p.getN()), random); - - engine.init(param); - initialised = true; - } - else if (params == null && BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa() == null) - { - throw new InvalidAlgorithmParameterException("null parameter passed but no implicitCA set"); - } - else - { - throw new InvalidAlgorithmParameterException("parameter object not a ECParameterSpec: " + params.getClass().getName()); - } - } - - public KeyPair generateKeyPair() - { - if (!initialised) - { - throw new IllegalStateException("EC Key Pair Generator not initialised"); - } - - AsymmetricCipherKeyPair pair = engine.generateKeyPair(); - ECPublicKeyParameters pub = (ECPublicKeyParameters)pair.getPublic(); - ECPrivateKeyParameters priv = (ECPrivateKeyParameters)pair.getPrivate(); - - if (ecParams == null) - { - return new KeyPair(new BCECGOST3410PublicKey(algorithm, pub), - new BCECGOST3410PrivateKey(algorithm, priv)); - } - else - { - ECParameterSpec p = (ECParameterSpec)ecParams; - - BCECGOST3410PublicKey pubKey = new BCECGOST3410PublicKey(algorithm, pub, p); - return new KeyPair(pubKey, - new BCECGOST3410PrivateKey(algorithm, priv, pubKey, p)); - } - } -} - diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/SignatureSpi.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/SignatureSpi.java deleted file mode 100644 index c3660fb1a..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/ecgost/SignatureSpi.java +++ /dev/null @@ -1,219 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.ecgost; - -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SignatureException; -import java.security.spec.AlgorithmParameterSpec; - -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x509.X509ObjectIdentifiers; -import org.spongycastle.crypto.CipherParameters; -import org.spongycastle.crypto.DSA; -import org.spongycastle.crypto.Digest; -import org.spongycastle.crypto.digests.GOST3411Digest; -import org.spongycastle.crypto.params.ParametersWithRandom; -import org.spongycastle.crypto.signers.ECGOST3410Signer; -import org.spongycastle.jcajce.provider.asymmetric.util.ECUtil; -import org.spongycastle.jce.interfaces.ECKey; -import org.spongycastle.jce.interfaces.ECPublicKey; -import org.spongycastle.jce.interfaces.GOST3410Key; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.jcajce.provider.asymmetric.util.GOST3410Util; - -public class SignatureSpi - extends java.security.Signature - implements PKCSObjectIdentifiers, X509ObjectIdentifiers -{ - private Digest digest; - private DSA signer; - - public SignatureSpi() - { - super("ECGOST3410"); - this.digest = new GOST3411Digest(); - this.signer = new ECGOST3410Signer(); - } - - protected void engineInitVerify( - PublicKey publicKey) - throws InvalidKeyException - { - CipherParameters param; - - if (publicKey instanceof ECPublicKey) - { - param = ECUtil.generatePublicKeyParameter(publicKey); - } - else if (publicKey instanceof GOST3410Key) - { - param = GOST3410Util.generatePublicKeyParameter(publicKey); - } - else - { - try - { - byte[] bytes = publicKey.getEncoded(); - - publicKey = BouncyCastleProvider.getPublicKey(SubjectPublicKeyInfo.getInstance(bytes)); - - if (publicKey instanceof ECPublicKey) - { - param = ECUtil.generatePublicKeyParameter(publicKey); - } - else - { - throw new InvalidKeyException("can't recognise key type in DSA based signer"); - } - } - catch (Exception e) - { - throw new InvalidKeyException("can't recognise key type in DSA based signer"); - } - } - - digest.reset(); - signer.init(false, param); - } - - protected void engineInitSign( - PrivateKey privateKey) - throws InvalidKeyException - { - CipherParameters param; - - if (privateKey instanceof ECKey) - { - param = ECUtil.generatePrivateKeyParameter(privateKey); - } - else - { - param = GOST3410Util.generatePrivateKeyParameter(privateKey); - } - - digest.reset(); - - if (appRandom != null) - { - signer.init(true, new ParametersWithRandom(param, appRandom)); - } - else - { - signer.init(true, param); - } - } - - protected void engineUpdate( - byte b) - throws SignatureException - { - digest.update(b); - } - - protected void engineUpdate( - byte[] b, - int off, - int len) - throws SignatureException - { - digest.update(b, off, len); - } - - protected byte[] engineSign() - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - try - { - byte[] sigBytes = new byte[64]; - BigInteger[] sig = signer.generateSignature(hash); - byte[] r = sig[0].toByteArray(); - byte[] s = sig[1].toByteArray(); - - if (s[0] != 0) - { - System.arraycopy(s, 0, sigBytes, 32 - s.length, s.length); - } - else - { - System.arraycopy(s, 1, sigBytes, 32 - (s.length - 1), s.length - 1); - } - - if (r[0] != 0) - { - System.arraycopy(r, 0, sigBytes, 64 - r.length, r.length); - } - else - { - System.arraycopy(r, 1, sigBytes, 64 - (r.length - 1), r.length - 1); - } - - return sigBytes; - } - catch (Exception e) - { - throw new SignatureException(e.toString()); - } - } - - protected boolean engineVerify( - byte[] sigBytes) - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - BigInteger[] sig; - - try - { - byte[] r = new byte[32]; - byte[] s = new byte[32]; - - System.arraycopy(sigBytes, 0, s, 0, 32); - - System.arraycopy(sigBytes, 32, r, 0, 32); - - sig = new BigInteger[2]; - sig[0] = new BigInteger(1, r); - sig[1] = new BigInteger(1, s); - } - catch (Exception e) - { - throw new SignatureException("error decoding signature bytes."); - } - - return signer.verifySignature(hash, sig[0], sig[1]); - } - - protected void engineSetParameter( - AlgorithmParameterSpec params) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated replaced with - */ - protected void engineSetParameter( - String param, - Object value) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated - */ - protected Object engineGetParameter( - String param) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/elgamal/CipherSpi.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/elgamal/CipherSpi.java deleted file mode 100644 index 7a6e69d3e..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/elgamal/CipherSpi.java +++ /dev/null @@ -1,299 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.elgamal; - -import java.security.AlgorithmParameters; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.InvalidParameterException; -import java.security.Key; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.spec.AlgorithmParameterSpec; - -import javax.crypto.BadPaddingException; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.interfaces.DHKey; - -import org.spongycastle.crypto.AsymmetricBlockCipher; -import org.spongycastle.crypto.BufferedAsymmetricBlockCipher; -import org.spongycastle.crypto.CipherParameters; -import org.spongycastle.crypto.InvalidCipherTextException; -import org.spongycastle.crypto.encodings.ISO9796d1Encoding; -import org.spongycastle.crypto.encodings.OAEPEncoding; -import org.spongycastle.crypto.encodings.PKCS1Encoding; -import org.spongycastle.crypto.engines.ElGamalEngine; -import org.spongycastle.crypto.params.ParametersWithRandom; -import org.spongycastle.jcajce.provider.asymmetric.util.BaseCipherSpi; -import org.spongycastle.jce.interfaces.ElGamalKey; -import org.spongycastle.jce.interfaces.ElGamalPrivateKey; -import org.spongycastle.jce.interfaces.ElGamalPublicKey; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.util.Strings; - -public class CipherSpi - extends BaseCipherSpi -{ - private BufferedAsymmetricBlockCipher cipher; - private AlgorithmParameterSpec paramSpec; - private AlgorithmParameters engineParams; - - public CipherSpi( - AsymmetricBlockCipher engine) - { - cipher = new BufferedAsymmetricBlockCipher(engine); - } - - protected int engineGetBlockSize() - { - return cipher.getInputBlockSize(); - } - - protected int engineGetKeySize( - Key key) - { - if (key instanceof ElGamalKey) - { - ElGamalKey k = (ElGamalKey)key; - - return k.getParameters().getP().bitLength(); - } - else if (key instanceof DHKey) - { - DHKey k = (DHKey)key; - - return k.getParams().getP().bitLength(); - } - - throw new IllegalArgumentException("not an ElGamal key!"); - } - - protected int engineGetOutputSize( - int inputLen) - { - return cipher.getOutputBlockSize(); - } - - protected AlgorithmParameters engineGetParameters() - { - if (engineParams == null) - { - if (paramSpec != null) - { - try - { - engineParams = AlgorithmParameters.getInstance("OAEP", BouncyCastleProvider.PROVIDER_NAME); - engineParams.init(paramSpec); - } - catch (Exception e) - { - throw new RuntimeException(e.toString()); - } - } - } - - return engineParams; - } - - protected void engineSetMode( - String mode) - throws NoSuchAlgorithmException - { - String md = Strings.toUpperCase(mode); - - if (md.equals("NONE") || md.equals("ECB")) - { - return; - } - - throw new NoSuchAlgorithmException("can't support mode " + mode); - } - - protected void engineSetPadding( - String padding) - throws NoSuchPaddingException - { - String pad = Strings.toUpperCase(padding); - - if (pad.equals("NOPADDING")) - { - cipher = new BufferedAsymmetricBlockCipher(new ElGamalEngine()); - } - else if (pad.equals("PKCS1PADDING")) - { - cipher = new BufferedAsymmetricBlockCipher(new PKCS1Encoding(new ElGamalEngine())); - } - else if (pad.equals("ISO9796-1PADDING")) - { - cipher = new BufferedAsymmetricBlockCipher(new ISO9796d1Encoding(new ElGamalEngine())); - } - else if (pad.equals("OAEPPADDING")) - { - cipher = new BufferedAsymmetricBlockCipher(new OAEPEncoding(new ElGamalEngine())); - } - else if (pad.equals("OAEPWITHSHA1ANDMGF1PADDING")) - { - cipher = new BufferedAsymmetricBlockCipher(new OAEPEncoding(new ElGamalEngine())); - } - else - { - throw new NoSuchPaddingException(padding + " unavailable with ElGamal."); - } - } - - protected void engineInit( - int opmode, - Key key, - AlgorithmParameterSpec params, - SecureRandom random) - throws InvalidKeyException - { - CipherParameters param; - - if (params == null) - { - if (key instanceof ElGamalPublicKey) - { - param = ElGamalUtil.generatePublicKeyParameter((PublicKey)key); - } - else if (key instanceof ElGamalPrivateKey) - { - param = ElGamalUtil.generatePrivateKeyParameter((PrivateKey)key); - } - else - { - throw new InvalidKeyException("unknown key type passed to ElGamal"); - } - } - else - { - throw new IllegalArgumentException("unknown parameter type."); - } - - if (random != null) - { - param = new ParametersWithRandom(param, random); - } - - switch (opmode) - { - case javax.crypto.Cipher.ENCRYPT_MODE: - case javax.crypto.Cipher.WRAP_MODE: - cipher.init(true, param); - break; - case javax.crypto.Cipher.DECRYPT_MODE: - case javax.crypto.Cipher.UNWRAP_MODE: - cipher.init(false, param); - break; - default: - throw new InvalidParameterException("unknown opmode " + opmode + " passed to ElGamal"); - } - } - - protected void engineInit( - int opmode, - Key key, - AlgorithmParameters params, - SecureRandom random) - throws InvalidKeyException, InvalidAlgorithmParameterException - { - throw new InvalidAlgorithmParameterException("can't handle parameters in ElGamal"); - } - - protected void engineInit( - int opmode, - Key key, - SecureRandom random) - throws InvalidKeyException - { - engineInit(opmode, key, (AlgorithmParameterSpec)null, random); - } - - protected byte[] engineUpdate( - byte[] input, - int inputOffset, - int inputLen) - { - cipher.processBytes(input, inputOffset, inputLen); - return null; - } - - protected int engineUpdate( - byte[] input, - int inputOffset, - int inputLen, - byte[] output, - int outputOffset) - { - cipher.processBytes(input, inputOffset, inputLen); - return 0; - } - - protected byte[] engineDoFinal( - byte[] input, - int inputOffset, - int inputLen) - throws IllegalBlockSizeException, BadPaddingException - { - cipher.processBytes(input, inputOffset, inputLen); - try - { - return cipher.doFinal(); - } - catch (InvalidCipherTextException e) - { - throw new BadPaddingException(e.getMessage()); - } - } - - protected int engineDoFinal( - byte[] input, - int inputOffset, - int inputLen, - byte[] output, - int outputOffset) - throws IllegalBlockSizeException, BadPaddingException - { - byte[] out; - - cipher.processBytes(input, inputOffset, inputLen); - - try - { - out = cipher.doFinal(); - } - catch (InvalidCipherTextException e) - { - throw new BadPaddingException(e.getMessage()); - } - - for (int i = 0; i != out.length; i++) - { - output[outputOffset + i] = out[i]; - } - - return out.length; - } - - /** - * classes that inherit from us. - */ - static public class NoPadding - extends CipherSpi - { - public NoPadding() - { - super(new ElGamalEngine()); - } - } - - static public class PKCS1v1_5Padding - extends CipherSpi - { - public PKCS1v1_5Padding() - { - super(new PKCS1Encoding(new ElGamalEngine())); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/rsa/AlgorithmParametersSpi.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/rsa/AlgorithmParametersSpi.java deleted file mode 100644 index eb66bcf36..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/rsa/AlgorithmParametersSpi.java +++ /dev/null @@ -1,217 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.rsa; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.security.spec.AlgorithmParameterSpec; -import java.security.spec.InvalidParameterSpecException; -import java.security.spec.PSSParameterSpec; - -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.DEROutputStream; -import org.spongycastle.asn1.pkcs.RSAESOAEPparams; -import org.spongycastle.asn1.pkcs.RSASSAPSSparams; - -public abstract class AlgorithmParametersSpi - extends java.security.AlgorithmParametersSpi -{ - protected boolean isASN1FormatString(String format) - { - return format == null || format.equals("ASN.1"); - } - - protected AlgorithmParameterSpec engineGetParameterSpec( - Class paramSpec) - throws InvalidParameterSpecException - { - if (paramSpec == null) - { - throw new NullPointerException("argument to getParameterSpec must not be null"); - } - - return localEngineGetParameterSpec(paramSpec); - } - - protected abstract AlgorithmParameterSpec localEngineGetParameterSpec(Class paramSpec) - throws InvalidParameterSpecException; - - public static class OAEP - extends AlgorithmParametersSpi - { - AlgorithmParameterSpec currentSpec; - - /** - * Return the PKCS#1 ASN.1 structure RSAES-OAEP-params. - */ - protected byte[] engineGetEncoded() - { - return null; - } - - protected byte[] engineGetEncoded( - String format) - { - if (isASN1FormatString(format) || format.equalsIgnoreCase("X.509")) - { - return engineGetEncoded(); - } - - return null; - } - - protected AlgorithmParameterSpec localEngineGetParameterSpec( - Class paramSpec) - throws InvalidParameterSpecException - { - throw new InvalidParameterSpecException("unknown parameter spec passed to OAEP parameters object."); - } - - protected void engineInit( - AlgorithmParameterSpec paramSpec) - throws InvalidParameterSpecException - { - this.currentSpec = paramSpec; - } - - protected void engineInit( - byte[] params) - throws IOException - { - try - { - RSAESOAEPparams oaepP = RSAESOAEPparams.getInstance(params); - - throw new IOException("Operation not supported"); - } - catch (ClassCastException e) - { - throw new IOException("Not a valid OAEP Parameter encoding."); - } - catch (ArrayIndexOutOfBoundsException e) - { - throw new IOException("Not a valid OAEP Parameter encoding."); - } - } - - protected void engineInit( - byte[] params, - String format) - throws IOException - { - if (format.equalsIgnoreCase("X.509") - || format.equalsIgnoreCase("ASN.1")) - { - engineInit(params); - } - else - { - throw new IOException("Unknown parameter format " + format); - } - } - - protected String engineToString() - { - return "OAEP Parameters"; - } - } - - public static class PSS - extends AlgorithmParametersSpi - { - PSSParameterSpec currentSpec; - - /** - * Return the PKCS#1 ASN.1 structure RSASSA-PSS-params. - */ - protected byte[] engineGetEncoded() - throws IOException - { - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - DEROutputStream dOut = new DEROutputStream(bOut); - PSSParameterSpec pssSpec = (PSSParameterSpec)currentSpec; - RSASSAPSSparams pssP = new RSASSAPSSparams(RSASSAPSSparams.DEFAULT_HASH_ALGORITHM, RSASSAPSSparams.DEFAULT_MASK_GEN_FUNCTION, new ASN1Integer(pssSpec.getSaltLength()), RSASSAPSSparams.DEFAULT_TRAILER_FIELD); - - dOut.writeObject(pssP); - dOut.close(); - - return bOut.toByteArray(); - } - - protected byte[] engineGetEncoded( - String format) - throws IOException - { - if (format.equalsIgnoreCase("X.509") - || format.equalsIgnoreCase("ASN.1")) - { - return engineGetEncoded(); - } - - return null; - } - - protected AlgorithmParameterSpec localEngineGetParameterSpec( - Class paramSpec) - throws InvalidParameterSpecException - { - if (paramSpec == PSSParameterSpec.class && currentSpec != null) - { - return currentSpec; - } - - throw new InvalidParameterSpecException("unknown parameter spec passed to PSS parameters object."); - } - - protected void engineInit( - AlgorithmParameterSpec paramSpec) - throws InvalidParameterSpecException - { - if (!(paramSpec instanceof PSSParameterSpec)) - { - throw new InvalidParameterSpecException("PSSParameterSpec required to initialise an PSS algorithm parameters object"); - } - - this.currentSpec = (PSSParameterSpec)paramSpec; - } - - protected void engineInit( - byte[] params) - throws IOException - { - try - { - RSASSAPSSparams pssP = RSASSAPSSparams.getInstance(params); - - currentSpec = new PSSParameterSpec( - pssP.getSaltLength().intValue()); - } - catch (ClassCastException e) - { - throw new IOException("Not a valid PSS Parameter encoding."); - } - catch (ArrayIndexOutOfBoundsException e) - { - throw new IOException("Not a valid PSS Parameter encoding."); - } - } - - protected void engineInit( - byte[] params, - String format) - throws IOException - { - if (isASN1FormatString(format) || format.equalsIgnoreCase("X.509")) - { - engineInit(params); - } - else - { - throw new IOException("Unknown parameter format " + format); - } - } - - protected String engineToString() - { - return "PSS Parameters"; - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/rsa/CipherSpi.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/rsa/CipherSpi.java deleted file mode 100644 index 7609b4a74..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/rsa/CipherSpi.java +++ /dev/null @@ -1,509 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.rsa; - -import java.io.ByteArrayOutputStream; -import java.security.AlgorithmParameters; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.InvalidParameterException; -import java.security.Key; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.AlgorithmParameterSpec; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; - -import org.spongycastle.crypto.AsymmetricBlockCipher; -import org.spongycastle.crypto.CipherParameters; -import org.spongycastle.crypto.InvalidCipherTextException; -import org.spongycastle.crypto.digests.MD5Digest; -import org.spongycastle.crypto.digests.SHA224Digest; -import org.spongycastle.crypto.digests.SHA256Digest; -import org.spongycastle.crypto.digests.SHA384Digest; -import org.spongycastle.crypto.digests.SHA512Digest; -import org.spongycastle.crypto.encodings.ISO9796d1Encoding; -import org.spongycastle.crypto.encodings.OAEPEncoding; -import org.spongycastle.crypto.encodings.PKCS1Encoding; -import org.spongycastle.crypto.engines.RSABlindedEngine; -import org.spongycastle.crypto.params.ParametersWithRandom; -import org.spongycastle.jcajce.provider.asymmetric.util.BaseCipherSpi; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.util.Strings; - -public class CipherSpi - extends BaseCipherSpi -{ - private AsymmetricBlockCipher cipher; - private AlgorithmParameterSpec paramSpec; - private AlgorithmParameters engineParams; - private boolean publicKeyOnly = false; - private boolean privateKeyOnly = false; - private ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - - public CipherSpi( - AsymmetricBlockCipher engine) - { - cipher = engine; - } - - public CipherSpi( - boolean publicKeyOnly, - boolean privateKeyOnly, - AsymmetricBlockCipher engine) - { - this.publicKeyOnly = publicKeyOnly; - this.privateKeyOnly = privateKeyOnly; - cipher = engine; - } - - protected int engineGetBlockSize() - { - try - { - return cipher.getInputBlockSize(); - } - catch (NullPointerException e) - { - throw new IllegalStateException("RSA Cipher not initialised"); - } - } - - protected int engineGetKeySize( - Key key) - { - if (key instanceof RSAPrivateKey) - { - RSAPrivateKey k = (RSAPrivateKey)key; - - return k.getModulus().bitLength(); - } - else if (key instanceof RSAPublicKey) - { - RSAPublicKey k = (RSAPublicKey)key; - - return k.getModulus().bitLength(); - } - - throw new IllegalArgumentException("not an RSA key!"); - } - - protected int engineGetOutputSize( - int inputLen) - { - try - { - return cipher.getOutputBlockSize(); - } - catch (NullPointerException e) - { - throw new IllegalStateException("RSA Cipher not initialised"); - } - } - - protected AlgorithmParameters engineGetParameters() - { - if (engineParams == null) - { - if (paramSpec != null) - { - try - { - engineParams = AlgorithmParameters.getInstance("OAEP", BouncyCastleProvider.PROVIDER_NAME); - engineParams.init(paramSpec); - } - catch (Exception e) - { - throw new RuntimeException(e.toString()); - } - } - } - - return engineParams; - } - - protected void engineSetMode( - String mode) - throws NoSuchAlgorithmException - { - String md = Strings.toUpperCase(mode); - - if (md.equals("NONE") || md.equals("ECB")) - { - return; - } - - if (md.equals("1")) - { - privateKeyOnly = true; - publicKeyOnly = false; - return; - } - else if (md.equals("2")) - { - privateKeyOnly = false; - publicKeyOnly = true; - return; - } - - throw new NoSuchAlgorithmException("can't support mode " + mode); - } - - protected void engineSetPadding( - String padding) - throws NoSuchPaddingException - { - String pad = Strings.toUpperCase(padding); - - if (pad.equals("NOPADDING")) - { - cipher = new RSABlindedEngine(); - } - else if (pad.equals("PKCS1PADDING")) - { - cipher = new PKCS1Encoding(new RSABlindedEngine()); - } - else if (pad.equals("ISO9796-1PADDING")) - { - cipher = new ISO9796d1Encoding(new RSABlindedEngine()); - } - else if (pad.equals("OAEPPADDING")) - { - cipher = new OAEPEncoding(new RSABlindedEngine()); - } - else if (pad.equals("OAEPWITHSHA1ANDMGF1PADDING")) - { - cipher = new OAEPEncoding(new RSABlindedEngine()); - } - else if (pad.equals("OAEPWITHSHA224ANDMGF1PADDING")) - { - cipher = new OAEPEncoding(new RSABlindedEngine(), new SHA224Digest()); - } - else if (pad.equals("OAEPWITHSHA256ANDMGF1PADDING")) - { - cipher = new OAEPEncoding(new RSABlindedEngine(), new SHA256Digest()); - } - else if (pad.equals("OAEPWITHSHA384ANDMGF1PADDING")) - { - cipher = new OAEPEncoding(new RSABlindedEngine(), new SHA384Digest()); - } - else if (pad.equals("OAEPWITHSHA512ANDMGF1PADDING")) - { - cipher = new OAEPEncoding(new RSABlindedEngine(), new SHA512Digest()); - } - else if (pad.equals("OAEPWITHMD5ANDMGF1PADDING")) - { - cipher = new OAEPEncoding(new RSABlindedEngine(), new MD5Digest()); - } - else - { - throw new NoSuchPaddingException(padding + " unavailable with RSA."); - } - } - - protected void engineInit( - int opmode, - Key key, - AlgorithmParameterSpec params, - SecureRandom random) - throws InvalidKeyException, InvalidAlgorithmParameterException - { - CipherParameters param; - - if (params == null) - { - if (key instanceof RSAPublicKey) - { - if (privateKeyOnly && opmode == Cipher.ENCRYPT_MODE) - { - throw new InvalidKeyException( - "mode 1 requires RSAPrivateKey"); - } - - param = RSAUtil.generatePublicKeyParameter((RSAPublicKey)key); - } - else if (key instanceof RSAPrivateKey) - { - if (publicKeyOnly && opmode == Cipher.ENCRYPT_MODE) - { - throw new InvalidKeyException( - "mode 2 requires RSAPublicKey"); - } - - param = RSAUtil.generatePrivateKeyParameter((RSAPrivateKey)key); - } - else - { - throw new InvalidKeyException("unknown key type passed to RSA"); - } - } - else - { - throw new IllegalArgumentException("unknown parameter type."); - } - - if (!(cipher instanceof RSABlindedEngine)) - { - if (random != null) - { - param = new ParametersWithRandom(param, random); - } - else - { - param = new ParametersWithRandom(param, new SecureRandom()); - } - } - - switch (opmode) - { - case javax.crypto.Cipher.ENCRYPT_MODE: - case javax.crypto.Cipher.WRAP_MODE: - cipher.init(true, param); - break; - case javax.crypto.Cipher.DECRYPT_MODE: - case javax.crypto.Cipher.UNWRAP_MODE: - cipher.init(false, param); - break; - default: - throw new InvalidParameterException("unknown opmode " + opmode + " passed to RSA"); - } - } - - protected void engineInit( - int opmode, - Key key, - AlgorithmParameters params, - SecureRandom random) - throws InvalidKeyException, InvalidAlgorithmParameterException - { - AlgorithmParameterSpec paramSpec = null; - - if (params != null) - { - throw new InvalidAlgorithmParameterException("cannot recognise parameters."); - } - - engineParams = params; - engineInit(opmode, key, paramSpec, random); - } - - protected void engineInit( - int opmode, - Key key, - SecureRandom random) - throws InvalidKeyException - { - try - { - engineInit(opmode, key, (AlgorithmParameterSpec)null, random); - } - catch (InvalidAlgorithmParameterException e) - { - // this shouldn't happen - throw new InvalidKeyException("Eeeek! " + e.toString()); - } - } - - protected byte[] engineUpdate( - byte[] input, - int inputOffset, - int inputLen) - { - bOut.write(input, inputOffset, inputLen); - - if (cipher instanceof RSABlindedEngine) - { - if (bOut.size() > cipher.getInputBlockSize() + 1) - { - throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); - } - } - else - { - if (bOut.size() > cipher.getInputBlockSize()) - { - throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); - } - } - - return null; - } - - protected int engineUpdate( - byte[] input, - int inputOffset, - int inputLen, - byte[] output, - int outputOffset) - { - bOut.write(input, inputOffset, inputLen); - - if (cipher instanceof RSABlindedEngine) - { - if (bOut.size() > cipher.getInputBlockSize() + 1) - { - throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); - } - } - else - { - if (bOut.size() > cipher.getInputBlockSize()) - { - throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); - } - } - - return 0; - } - - protected byte[] engineDoFinal( - byte[] input, - int inputOffset, - int inputLen) - throws IllegalBlockSizeException, BadPaddingException - { - if (input != null) - { - bOut.write(input, inputOffset, inputLen); - } - - if (cipher instanceof RSABlindedEngine) - { - if (bOut.size() > cipher.getInputBlockSize() + 1) - { - throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); - } - } - else - { - if (bOut.size() > cipher.getInputBlockSize()) - { - throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); - } - } - - try - { - byte[] bytes = bOut.toByteArray(); - - bOut.reset(); - - return cipher.processBlock(bytes, 0, bytes.length); - } - catch (InvalidCipherTextException e) - { - throw new BadPaddingException(e.getMessage()); - } - } - - protected int engineDoFinal( - byte[] input, - int inputOffset, - int inputLen, - byte[] output, - int outputOffset) - throws IllegalBlockSizeException, BadPaddingException - { - if (input != null) - { - bOut.write(input, inputOffset, inputLen); - } - - if (cipher instanceof RSABlindedEngine) - { - if (bOut.size() > cipher.getInputBlockSize() + 1) - { - throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); - } - } - else - { - if (bOut.size() > cipher.getInputBlockSize()) - { - throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); - } - } - - byte[] out; - - try - { - byte[] bytes = bOut.toByteArray(); - bOut.reset(); - - out = cipher.processBlock(bytes, 0, bytes.length); - } - catch (InvalidCipherTextException e) - { - throw new BadPaddingException(e.getMessage()); - } - - for (int i = 0; i != out.length; i++) - { - output[outputOffset + i] = out[i]; - } - - return out.length; - } - - /** - * classes that inherit from us. - */ - - static public class NoPadding - extends CipherSpi - { - public NoPadding() - { - super(new RSABlindedEngine()); - } - } - - static public class PKCS1v1_5Padding - extends CipherSpi - { - public PKCS1v1_5Padding() - { - super(new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class PKCS1v1_5Padding_PrivateOnly - extends CipherSpi - { - public PKCS1v1_5Padding_PrivateOnly() - { - super(false, true, new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class PKCS1v1_5Padding_PublicOnly - extends CipherSpi - { - public PKCS1v1_5Padding_PublicOnly() - { - super(true, false, new PKCS1Encoding(new RSABlindedEngine())); - } - } - - static public class OAEPPadding - extends CipherSpi - { - public OAEPPadding() - { - super(new OAEPEncoding(new RSABlindedEngine())); - } - } - - static public class ISO9796d1Padding - extends CipherSpi - { - public ISO9796d1Padding() - { - super(new ISO9796d1Encoding(new RSABlindedEngine())); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/rsa/PSSSignatureSpi.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/rsa/PSSSignatureSpi.java deleted file mode 100644 index 23dd01004..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/rsa/PSSSignatureSpi.java +++ /dev/null @@ -1,405 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.rsa; - -import java.io.ByteArrayOutputStream; -import java.security.AlgorithmParameters; -import java.security.InvalidKeyException; -import java.security.InvalidParameterException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.Signature; -import java.security.SignatureException; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.AlgorithmParameterSpec; -import java.security.spec.PSSParameterSpec; - -import org.spongycastle.crypto.AsymmetricBlockCipher; -import org.spongycastle.crypto.CryptoException; -import org.spongycastle.crypto.Digest; -import org.spongycastle.crypto.digests.SHA1Digest; -import org.spongycastle.crypto.digests.SHA224Digest; -import org.spongycastle.crypto.digests.SHA256Digest; -import org.spongycastle.crypto.digests.SHA384Digest; -import org.spongycastle.crypto.digests.SHA512Digest; -import org.spongycastle.crypto.engines.RSABlindedEngine; -import org.spongycastle.crypto.params.ParametersWithRandom; -import org.spongycastle.jce.provider.BouncyCastleProvider; - -public class PSSSignatureSpi - extends Signature -{ - private AlgorithmParameters engineParams; - private PSSParameterSpec paramSpec; - private AsymmetricBlockCipher signer; - private Digest contentDigest; - private Digest mgfDigest; - private int saltLength; - private byte trailer; - private boolean isRaw; - - private org.spongycastle.crypto.signers.PSSSigner pss; - - private byte getTrailer( - int trailerField) - { - if (trailerField == 1) - { - return org.spongycastle.crypto.signers.PSSSigner.TRAILER_IMPLICIT; - } - - throw new IllegalArgumentException("unknown trailer field"); - } - - private void setupContentDigest() - { - if (isRaw) - { - this.contentDigest = new NullPssDigest(mgfDigest); - } - else - { - this.contentDigest = mgfDigest; - } - } - - protected PSSSignatureSpi( - String name, - AsymmetricBlockCipher signer, - Digest digest) - { - super(name); - - this.signer = signer; - this.mgfDigest = digest; - - if (digest != null) - { - this.saltLength = digest.getDigestSize(); - } - else - { - this.saltLength = 20; - } - - if (paramSpec != null) - { - this.saltLength = paramSpec.getSaltLength(); - } - this.isRaw = false; - - setupContentDigest(); - } - - // care - this constructor is actually used by outside organisations - protected PSSSignatureSpi( - String name, - AsymmetricBlockCipher signer, - Digest digest, - boolean isRaw) - { - super(name); - - this.signer = signer; - this.mgfDigest = digest; - - if (digest != null) - { - this.saltLength = digest.getDigestSize(); - } - else - { - this.saltLength = 20; - } - - if (paramSpec != null) - { - this.saltLength = paramSpec.getSaltLength(); - } - - this.isRaw = isRaw; - - setupContentDigest(); - } - - protected void engineInitVerify( - PublicKey publicKey) - throws InvalidKeyException - { - if (!(publicKey instanceof RSAPublicKey)) - { - throw new InvalidKeyException("Supplied key is not a RSAPublicKey instance"); - } - - pss = new org.spongycastle.crypto.signers.PSSSigner(signer, contentDigest, mgfDigest, saltLength); - pss.init(false, - RSAUtil.generatePublicKeyParameter((RSAPublicKey)publicKey)); - } - - protected void engineInitSign( - PrivateKey privateKey, - SecureRandom random) - throws InvalidKeyException - { - if (!(privateKey instanceof RSAPrivateKey)) - { - throw new InvalidKeyException("Supplied key is not a RSAPrivateKey instance"); - } - - pss = new org.spongycastle.crypto.signers.PSSSigner(signer, contentDigest, mgfDigest, saltLength); - pss.init(true, new ParametersWithRandom(RSAUtil.generatePrivateKeyParameter((RSAPrivateKey)privateKey), random)); - } - - protected void engineInitSign( - PrivateKey privateKey) - throws InvalidKeyException - { - if (!(privateKey instanceof RSAPrivateKey)) - { - throw new InvalidKeyException("Supplied key is not a RSAPrivateKey instance"); - } - - pss = new org.spongycastle.crypto.signers.PSSSigner(signer, contentDigest, mgfDigest, saltLength); - pss.init(true, RSAUtil.generatePrivateKeyParameter((RSAPrivateKey)privateKey)); - } - - protected void engineUpdate( - byte b) - throws SignatureException - { - pss.update(b); - } - - protected void engineUpdate( - byte[] b, - int off, - int len) - throws SignatureException - { - pss.update(b, off, len); - } - - protected byte[] engineSign() - throws SignatureException - { - try - { - return pss.generateSignature(); - } - catch (CryptoException e) - { - throw new SignatureException(e.getMessage()); - } - } - - protected boolean engineVerify( - byte[] sigBytes) - throws SignatureException - { - return pss.verifySignature(sigBytes); - } - - protected void engineSetParameter( - AlgorithmParameterSpec params) - throws InvalidParameterException - { - if (params instanceof PSSParameterSpec) - { - PSSParameterSpec newParamSpec = (PSSParameterSpec)params; - - this.engineParams = null; - this.paramSpec = newParamSpec; - this.saltLength = paramSpec.getSaltLength(); - - if (mgfDigest == null) - { - switch (saltLength) - { - case 20: - this.mgfDigest = new SHA1Digest(); - break; - case 28: - this.mgfDigest = new SHA224Digest(); - break; - case 32: - this.mgfDigest = new SHA256Digest(); - break; - case 48: - this.mgfDigest = new SHA384Digest(); - break; - case 64: - this.mgfDigest = new SHA512Digest(); - break; - } - setupContentDigest(); - } - } - else - { - throw new InvalidParameterException("Only PSSParameterSpec supported"); - } - } - - protected AlgorithmParameters engineGetParameters() - { - if (engineParams == null) - { - try - { - engineParams = AlgorithmParameters.getInstance("PSS", BouncyCastleProvider.PROVIDER_NAME); - engineParams.init(new PSSParameterSpec(saltLength)); - } - catch (Exception e) - { - throw new RuntimeException(e.toString()); - } - } - - return engineParams; - } - - /** - * @deprecated replaced with - */ - protected void engineSetParameter( - String param, - Object value) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - protected Object engineGetParameter( - String param) - { - throw new UnsupportedOperationException("engineGetParameter unsupported"); - } - - static public class nonePSS - extends PSSSignatureSpi - { - public nonePSS() - { - super("NONEwithRSAandMGF1", new RSABlindedEngine(), null, true); - } - } - - static public class PSSwithRSA - extends PSSSignatureSpi - { - public PSSwithRSA() - { - super("SHA1withRSAandMGF1", new RSABlindedEngine(), null); - } - } - - static public class SHA1withRSA - extends PSSSignatureSpi - { - public SHA1withRSA() - { - super("SHA1withRSAandMGF1", new RSABlindedEngine(), new SHA1Digest()); - } - } - - static public class SHA224withRSA - extends PSSSignatureSpi - { - public SHA224withRSA() - { - super("SHA224withRSAandMGF1", new RSABlindedEngine(), new SHA224Digest()); - } - } - - static public class SHA256withRSA - extends PSSSignatureSpi - { - public SHA256withRSA() - { - super("SHA256withRSAandMGF1", new RSABlindedEngine(), new SHA256Digest()); - } - } - - static public class SHA384withRSA - extends PSSSignatureSpi - { - public SHA384withRSA() - { - super("SHA384withRSAandMGF1", new RSABlindedEngine(), new SHA384Digest()); - } - } - - static public class SHA512withRSA - extends PSSSignatureSpi - { - public SHA512withRSA() - { - super("SHA512withRSAandMGF1", new RSABlindedEngine(), new SHA512Digest()); - } - } - - private class NullPssDigest - implements Digest - { - private ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - private Digest baseDigest; - private boolean oddTime = true; - - public NullPssDigest(Digest mgfDigest) - { - this.baseDigest = mgfDigest; - } - - public String getAlgorithmName() - { - return "NULL"; - } - - public int getDigestSize() - { - return baseDigest.getDigestSize(); - } - - public void update(byte in) - { - bOut.write(in); - } - - public void update(byte[] in, int inOff, int len) - { - bOut.write(in, inOff, len); - } - - public int doFinal(byte[] out, int outOff) - { - byte[] res = bOut.toByteArray(); - - if (oddTime) - { - System.arraycopy(res, 0, out, outOff, res.length); - } - else - { - baseDigest.update(res, 0, res.length); - - baseDigest.doFinal(out, outOff); - } - - reset(); - - oddTime = !oddTime; - - return res.length; - } - - public void reset() - { - bOut.reset(); - baseDigest.reset(); - } - - public int getByteLength() - { - return 0; - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/util/DSABase.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/util/DSABase.java deleted file mode 100644 index bdc65b044..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/util/DSABase.java +++ /dev/null @@ -1,128 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.util; - -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.Signature; -import java.security.SignatureException; -import java.security.spec.AlgorithmParameterSpec; - -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.x509.X509ObjectIdentifiers; -import org.spongycastle.crypto.DSA; -import org.spongycastle.crypto.Digest; - -public abstract class DSABase - extends Signature - implements PKCSObjectIdentifiers, X509ObjectIdentifiers -{ - protected Digest digest; - protected DSA signer; - protected DSAEncoder encoder; - - protected DSABase( - String name, - Digest digest, - DSA signer, - DSAEncoder encoder) - { - super(name); - - this.digest = digest; - this.signer = signer; - this.encoder = encoder; - } - - protected void engineInitSign( - PrivateKey privateKey) - throws InvalidKeyException - { - doEngineInitSign(privateKey, appRandom); - } - - protected void engineUpdate( - byte b) - throws SignatureException - { - digest.update(b); - } - - protected void engineUpdate( - byte[] b, - int off, - int len) - throws SignatureException - { - digest.update(b, off, len); - } - - protected byte[] engineSign() - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - try - { - BigInteger[] sig = signer.generateSignature(hash); - - return encoder.encode(sig[0], sig[1]); - } - catch (Exception e) - { - throw new SignatureException(e.toString()); - } - } - - protected boolean engineVerify( - byte[] sigBytes) - throws SignatureException - { - byte[] hash = new byte[digest.getDigestSize()]; - - digest.doFinal(hash, 0); - - BigInteger[] sig; - - try - { - sig = encoder.decode(sigBytes); - } - catch (Exception e) - { - throw new SignatureException("error decoding signature bytes."); - } - - return signer.verifySignature(hash, sig[0], sig[1]); - } - - protected void engineSetParameter( - AlgorithmParameterSpec params) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated replaced with - */ - protected void engineSetParameter( - String param, - Object value) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - /** - * @deprecated - */ - protected Object engineGetParameter( - String param) - { - throw new UnsupportedOperationException("engineSetParameter unsupported"); - } - - protected abstract void doEngineInitSign(PrivateKey privateKey, SecureRandom random) - throws InvalidKeyException; -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/util/ECUtil.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/util/ECUtil.java deleted file mode 100644 index 8cfba71fa..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/asymmetric/util/ECUtil.java +++ /dev/null @@ -1,220 +0,0 @@ -package org.spongycastle.jcajce.provider.asymmetric.util; - -import java.security.InvalidKeyException; -import java.security.PrivateKey; -import java.security.PublicKey; - -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.cryptopro.ECGOST3410NamedCurves; -import org.spongycastle.asn1.nist.NISTNamedCurves; -import org.spongycastle.asn1.sec.SECNamedCurves; -import org.spongycastle.asn1.teletrust.TeleTrusTNamedCurves; -import org.spongycastle.asn1.x9.X962NamedCurves; -import org.spongycastle.asn1.x9.X9ECParameters; -import org.spongycastle.crypto.params.AsymmetricKeyParameter; -import org.spongycastle.crypto.params.ECDomainParameters; -import org.spongycastle.crypto.params.ECPrivateKeyParameters; -import org.spongycastle.crypto.params.ECPublicKeyParameters; -import org.spongycastle.jce.interfaces.ECPrivateKey; -import org.spongycastle.jce.interfaces.ECPublicKey; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.jcajce.provider.asymmetric.ec.BCECPublicKey; -import org.spongycastle.jce.spec.ECParameterSpec; - -/** - * utility class for converting jce/jca ECDSA, ECDH, and ECDHC - * objects into their org.spongycastle.crypto counterparts. - */ -public class ECUtil -{ - /** - * Returns a sorted array of middle terms of the reduction polynomial. - * @param k The unsorted array of middle terms of the reduction polynomial - * of length 1 or 3. - * @return the sorted array of middle terms of the reduction polynomial. - * This array always has length 3. - */ - static int[] convertMidTerms( - int[] k) - { - int[] res = new int[3]; - - if (k.length == 1) - { - res[0] = k[0]; - } - else - { - if (k.length != 3) - { - throw new IllegalArgumentException("Only Trinomials and pentanomials supported"); - } - - if (k[0] < k[1] && k[0] < k[2]) - { - res[0] = k[0]; - if (k[1] < k[2]) - { - res[1] = k[1]; - res[2] = k[2]; - } - else - { - res[1] = k[2]; - res[2] = k[1]; - } - } - else if (k[1] < k[2]) - { - res[0] = k[1]; - if (k[0] < k[2]) - { - res[1] = k[0]; - res[2] = k[2]; - } - else - { - res[1] = k[2]; - res[2] = k[0]; - } - } - else - { - res[0] = k[2]; - if (k[0] < k[1]) - { - res[1] = k[0]; - res[2] = k[1]; - } - else - { - res[1] = k[1]; - res[2] = k[0]; - } - } - } - - return res; - } - - public static AsymmetricKeyParameter generatePublicKeyParameter( - PublicKey key) - throws InvalidKeyException - { - if (key instanceof ECPublicKey) - { - ECPublicKey k = (ECPublicKey)key; - ECParameterSpec s = k.getParameters(); - - if (s == null) - { - s = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa(); - - return new ECPublicKeyParameters( - ((BCECPublicKey)k).engineGetQ(), - new ECDomainParameters(s.getCurve(), s.getG(), s.getN(), s.getH(), s.getSeed())); - } - else - { - return new ECPublicKeyParameters( - k.getQ(), - new ECDomainParameters(s.getCurve(), s.getG(), s.getN(), s.getH(), s.getSeed())); - } - } - - throw new InvalidKeyException("cannot identify EC public key."); - } - - public static AsymmetricKeyParameter generatePrivateKeyParameter( - PrivateKey key) - throws InvalidKeyException - { - if (key instanceof ECPrivateKey) - { - ECPrivateKey k = (ECPrivateKey)key; - ECParameterSpec s = k.getParameters(); - - if (s == null) - { - s = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa(); - } - - return new ECPrivateKeyParameters( - k.getD(), - new ECDomainParameters(s.getCurve(), s.getG(), s.getN(), s.getH(), s.getSeed())); - } - - throw new InvalidKeyException("can't identify EC private key."); - } - - public static ASN1ObjectIdentifier getNamedCurveOid( - String name) - { - ASN1ObjectIdentifier oid = X962NamedCurves.getOID(name); - - if (oid == null) - { - oid = SECNamedCurves.getOID(name); - if (oid == null) - { - oid = NISTNamedCurves.getOID(name); - } - if (oid == null) - { - oid = TeleTrusTNamedCurves.getOID(name); - } - if (oid == null) - { - oid = ECGOST3410NamedCurves.getOID(name); - } - } - - return oid; - } - - public static X9ECParameters getNamedCurveByOid( - ASN1ObjectIdentifier oid) - { - X9ECParameters params = X962NamedCurves.getByOID(oid); - - if (params == null) - { - params = SECNamedCurves.getByOID(oid); - if (params == null) - { - params = NISTNamedCurves.getByOID(oid); - } - if (params == null) - { - params = TeleTrusTNamedCurves.getByOID(oid); - } - } - - return params; - } - - public static String getCurveName( - ASN1ObjectIdentifier oid) - { - String name = X962NamedCurves.getName(oid); - - if (name == null) - { - name = SECNamedCurves.getName(oid); - if (name == null) - { - name = NISTNamedCurves.getName(oid); - } - if (name == null) - { - name = TeleTrusTNamedCurves.getName(oid); - } - if (name == null) - { - name = ECGOST3410NamedCurves.getName(oid); - } - } - - return name; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java deleted file mode 100644 index dbad77728..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jcajce/provider/keystore/pkcs12/PKCS12KeyStoreSpi.java +++ /dev/null @@ -1,1637 +0,0 @@ -package org.spongycastle.jcajce.provider.keystore.pkcs12; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.Key; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.KeyStoreSpi; -import java.security.NoSuchAlgorithmException; -import java.security.Principal; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.UnrecoverableKeyException; -import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.Date; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Vector; - -import javax.crypto.Cipher; -import javax.crypto.Mac; -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.PBEParameterSpec; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1EncodableVector; -import org.spongycastle.asn1.ASN1Encoding; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1Set; -import org.spongycastle.asn1.BEROctetString; -import org.spongycastle.asn1.BEROutputStream; -import org.spongycastle.asn1.DERBMPString; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.DEROctetString; -import org.spongycastle.asn1.DEROutputStream; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.DERSet; -import org.spongycastle.asn1.pkcs.AuthenticatedSafe; -import org.spongycastle.asn1.pkcs.CertBag; -import org.spongycastle.asn1.pkcs.ContentInfo; -import org.spongycastle.asn1.pkcs.EncryptedData; -import org.spongycastle.asn1.pkcs.MacData; -import org.spongycastle.asn1.pkcs.PBES2Parameters; -import org.spongycastle.asn1.pkcs.PBKDF2Params; -import org.spongycastle.asn1.pkcs.PKCS12PBEParams; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.pkcs.Pfx; -import org.spongycastle.asn1.pkcs.SafeBag; -import org.spongycastle.asn1.util.ASN1Dump; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.AuthorityKeyIdentifier; -import org.spongycastle.asn1.x509.DigestInfo; -import org.spongycastle.asn1.x509.Extension; -import org.spongycastle.asn1.x509.SubjectKeyIdentifier; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x509.X509ObjectIdentifiers; -import org.spongycastle.crypto.Digest; -import org.spongycastle.crypto.digests.SHA1Digest; -import org.spongycastle.jcajce.provider.symmetric.util.BCPBEKey; -import org.spongycastle.jcajce.provider.util.SecretKeyUtil; -import org.spongycastle.jce.interfaces.BCKeyStore; -import org.spongycastle.jce.interfaces.PKCS12BagAttributeCarrier; -import org.spongycastle.jce.provider.BouncyCastleProvider; -import org.spongycastle.util.Arrays; -import org.spongycastle.util.Strings; -import org.spongycastle.util.encoders.Hex; - -public class PKCS12KeyStoreSpi - extends KeyStoreSpi - implements PKCSObjectIdentifiers, X509ObjectIdentifiers, BCKeyStore -{ - private static final int SALT_SIZE = 20; - private static final int MIN_ITERATIONS = 1024; - - private static final Provider bcProvider = new BouncyCastleProvider(); - - private IgnoresCaseHashtable keys = new IgnoresCaseHashtable(); - private Hashtable localIds = new Hashtable(); - private IgnoresCaseHashtable certs = new IgnoresCaseHashtable(); - private Hashtable chainCerts = new Hashtable(); - private Hashtable keyCerts = new Hashtable(); - - // - // generic object types - // - static final int NULL = 0; - static final int CERTIFICATE = 1; - static final int KEY = 2; - static final int SECRET = 3; - static final int SEALED = 4; - - // - // key types - // - static final int KEY_PRIVATE = 0; - static final int KEY_PUBLIC = 1; - static final int KEY_SECRET = 2; - - protected SecureRandom random = new SecureRandom(); - - // use of final causes problems with JDK 1.2 compiler - private CertificateFactory certFact; - private ASN1ObjectIdentifier keyAlgorithm; - private ASN1ObjectIdentifier certAlgorithm; - - private class CertId - { - byte[] id; - - CertId( - PublicKey key) - { - this.id = createSubjectKeyId(key).getKeyIdentifier(); - } - - CertId( - byte[] id) - { - this.id = id; - } - - public int hashCode() - { - return Arrays.hashCode(id); - } - - public boolean equals( - Object o) - { - if (o == this) - { - return true; - } - - if (!(o instanceof CertId)) - { - return false; - } - - CertId cId = (CertId)o; - - return Arrays.areEqual(id, cId.id); - } - } - - public PKCS12KeyStoreSpi( - Provider provider, - ASN1ObjectIdentifier keyAlgorithm, - ASN1ObjectIdentifier certAlgorithm) - { - this.keyAlgorithm = keyAlgorithm; - this.certAlgorithm = certAlgorithm; - - try - { - if (provider != null) - { - certFact = CertificateFactory.getInstance("X.509", provider); - } - else - { - certFact = CertificateFactory.getInstance("X.509"); - } - } - catch (Exception e) - { - throw new IllegalArgumentException("can't create cert factory - " + e.toString()); - } - } - - private SubjectKeyIdentifier createSubjectKeyId( - PublicKey pubKey) - { - try - { - SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( - (ASN1Sequence)ASN1Primitive.fromByteArray(pubKey.getEncoded())); - - return new SubjectKeyIdentifier(getDigest(info)); - } - catch (Exception e) - { - throw new RuntimeException("error creating key"); - } - } - - private static byte[] getDigest(SubjectPublicKeyInfo spki) - { - Digest digest = new SHA1Digest(); - byte[] resBuf = new byte[digest.getDigestSize()]; - - byte[] bytes = spki.getPublicKeyData().getBytes(); - digest.update(bytes, 0, bytes.length); - digest.doFinal(resBuf, 0); - return resBuf; - } - - public void setRandom( - SecureRandom rand) - { - this.random = rand; - } - - public Enumeration engineAliases() - { - Hashtable tab = new Hashtable(); - - Enumeration e = certs.keys(); - while (e.hasMoreElements()) - { - tab.put(e.nextElement(), "cert"); - } - - e = keys.keys(); - while (e.hasMoreElements()) - { - String a = (String)e.nextElement(); - if (tab.get(a) == null) - { - tab.put(a, "key"); - } - } - - return tab.keys(); - } - - public boolean engineContainsAlias( - String alias) - { - return (certs.get(alias) != null || keys.get(alias) != null); - } - - /** - * this is not quite complete - we should follow up on the chain, a bit - * tricky if a certificate appears in more than one chain... - */ - public void engineDeleteEntry( - String alias) - throws KeyStoreException - { - Key k = (Key)keys.remove(alias); - - Certificate c = (Certificate)certs.remove(alias); - - if (c != null) - { - chainCerts.remove(new CertId(c.getPublicKey())); - } - - if (k != null) - { - String id = (String)localIds.remove(alias); - if (id != null) - { - c = (Certificate)keyCerts.remove(id); - } - if (c != null) - { - chainCerts.remove(new CertId(c.getPublicKey())); - } - } - } - - /** - * simply return the cert for the private key - */ - public Certificate engineGetCertificate( - String alias) - { - if (alias == null) - { - throw new IllegalArgumentException("null alias passed to getCertificate."); - } - - Certificate c = (Certificate)certs.get(alias); - - // - // look up the key table - and try the local key id - // - if (c == null) - { - String id = (String)localIds.get(alias); - if (id != null) - { - c = (Certificate)keyCerts.get(id); - } - else - { - c = (Certificate)keyCerts.get(alias); - } - } - - return c; - } - - public String engineGetCertificateAlias( - Certificate cert) - { - Enumeration c = certs.elements(); - Enumeration k = certs.keys(); - - while (c.hasMoreElements()) - { - Certificate tc = (Certificate)c.nextElement(); - String ta = (String)k.nextElement(); - - if (tc.equals(cert)) - { - return ta; - } - } - - c = keyCerts.elements(); - k = keyCerts.keys(); - - while (c.hasMoreElements()) - { - Certificate tc = (Certificate)c.nextElement(); - String ta = (String)k.nextElement(); - - if (tc.equals(cert)) - { - return ta; - } - } - - return null; - } - - public Certificate[] engineGetCertificateChain( - String alias) - { - if (alias == null) - { - throw new IllegalArgumentException("null alias passed to getCertificateChain."); - } - - if (!engineIsKeyEntry(alias)) - { - return null; - } - - Certificate c = engineGetCertificate(alias); - - if (c != null) - { - Vector cs = new Vector(); - - while (c != null) - { - X509Certificate x509c = (X509Certificate)c; - Certificate nextC = null; - - byte[] bytes = x509c.getExtensionValue(Extension.authorityKeyIdentifier.getId()); - if (bytes != null) - { - try - { - ASN1InputStream aIn = new ASN1InputStream(bytes); - - byte[] authBytes = ((ASN1OctetString)aIn.readObject()).getOctets(); - aIn = new ASN1InputStream(authBytes); - - AuthorityKeyIdentifier id = AuthorityKeyIdentifier.getInstance(aIn.readObject()); - if (id.getKeyIdentifier() != null) - { - nextC = (Certificate)chainCerts.get(new CertId(id.getKeyIdentifier())); - } - - } - catch (IOException e) - { - throw new RuntimeException(e.toString()); - } - } - - if (nextC == null) - { - // - // no authority key id, try the Issuer DN - // - Principal i = x509c.getIssuerDN(); - Principal s = x509c.getSubjectDN(); - - if (!i.equals(s)) - { - Enumeration e = chainCerts.keys(); - - while (e.hasMoreElements()) - { - X509Certificate crt = (X509Certificate)chainCerts.get(e.nextElement()); - Principal sub = crt.getSubjectDN(); - if (sub.equals(i)) - { - try - { - x509c.verify(crt.getPublicKey()); - nextC = crt; - break; - } - catch (Exception ex) - { - // continue - } - } - } - } - } - - cs.addElement(c); - if (nextC != c) // self signed - end of the chain - { - c = nextC; - } - else - { - c = null; - } - } - - Certificate[] certChain = new Certificate[cs.size()]; - - for (int i = 0; i != certChain.length; i++) - { - certChain[i] = (Certificate)cs.elementAt(i); - } - - return certChain; - } - - return null; - } - - public Date engineGetCreationDate(String alias) - { - if (alias == null) - { - throw new NullPointerException("alias == null"); - } - if (keys.get(alias) == null && certs.get(alias) == null) - { - return null; - } - return new Date(); - } - - public Key engineGetKey( - String alias, - char[] password) - throws NoSuchAlgorithmException, UnrecoverableKeyException - { - if (alias == null) - { - throw new IllegalArgumentException("null alias passed to getKey."); - } - - return (Key)keys.get(alias); - } - - public boolean engineIsCertificateEntry( - String alias) - { - return (certs.get(alias) != null && keys.get(alias) == null); - } - - public boolean engineIsKeyEntry( - String alias) - { - return (keys.get(alias) != null); - } - - public void engineSetCertificateEntry( - String alias, - Certificate cert) - throws KeyStoreException - { - if (keys.get(alias) != null) - { - throw new KeyStoreException("There is a key entry with the name " + alias + "."); - } - - certs.put(alias, cert); - chainCerts.put(new CertId(cert.getPublicKey()), cert); - } - - public void engineSetKeyEntry( - String alias, - byte[] key, - Certificate[] chain) - throws KeyStoreException - { - throw new RuntimeException("operation not supported"); - } - - public void engineSetKeyEntry( - String alias, - Key key, - char[] password, - Certificate[] chain) - throws KeyStoreException - { - if (!(key instanceof PrivateKey)) - { - throw new KeyStoreException("PKCS12 does not support non-PrivateKeys"); - } - - if ((key instanceof PrivateKey) && (chain == null)) - { - throw new KeyStoreException("no certificate chain for private key"); - } - - if (keys.get(alias) != null) - { - engineDeleteEntry(alias); - } - - keys.put(alias, key); - if (chain != null) - { - certs.put(alias, chain[0]); - - for (int i = 0; i != chain.length; i++) - { - chainCerts.put(new CertId(chain[i].getPublicKey()), chain[i]); - } - } - } - - public int engineSize() - { - Hashtable tab = new Hashtable(); - - Enumeration e = certs.keys(); - while (e.hasMoreElements()) - { - tab.put(e.nextElement(), "cert"); - } - - e = keys.keys(); - while (e.hasMoreElements()) - { - String a = (String)e.nextElement(); - if (tab.get(a) == null) - { - tab.put(a, "key"); - } - } - - return tab.size(); - } - - protected PrivateKey unwrapKey( - AlgorithmIdentifier algId, - byte[] data, - char[] password, - boolean wrongPKCS12Zero) - throws IOException - { - ASN1ObjectIdentifier algorithm = algId.getAlgorithm(); - try - { - if (algorithm.on(PKCSObjectIdentifiers.pkcs_12PbeIds)) - { - PKCS12PBEParams pbeParams = PKCS12PBEParams.getInstance(algId.getParameters()); - - PBEKeySpec pbeSpec = new PBEKeySpec(password); - PrivateKey out; - - SecretKeyFactory keyFact = SecretKeyFactory.getInstance( - algorithm.getId(), bcProvider); - PBEParameterSpec defParams = new PBEParameterSpec( - pbeParams.getIV(), - pbeParams.getIterations().intValue()); - - SecretKey k = keyFact.generateSecret(pbeSpec); - - ((BCPBEKey)k).setTryWrongPKCS12Zero(wrongPKCS12Zero); - - Cipher cipher = Cipher.getInstance(algorithm.getId(), bcProvider); - - cipher.init(Cipher.UNWRAP_MODE, k, defParams); - - // we pass "" as the key algorithm type as it is unknown at this point - return (PrivateKey)cipher.unwrap(data, "", Cipher.PRIVATE_KEY); - } - else if (algorithm.equals(PKCSObjectIdentifiers.id_PBES2)) - { - PBES2Parameters alg = PBES2Parameters.getInstance(algId.getParameters()); - PBKDF2Params func = PBKDF2Params.getInstance(alg.getKeyDerivationFunc().getParameters()); - - SecretKeyFactory keyFact = SecretKeyFactory.getInstance(alg.getKeyDerivationFunc().getAlgorithm().getId(), bcProvider); - - SecretKey k = keyFact.generateSecret(new PBEKeySpec(password, func.getSalt(), func.getIterationCount().intValue(), SecretKeyUtil.getKeySize(alg.getEncryptionScheme().getAlgorithm()))); - - Cipher cipher = Cipher.getInstance(alg.getEncryptionScheme().getAlgorithm().getId(), bcProvider); - - cipher.init(Cipher.UNWRAP_MODE, k, new IvParameterSpec(ASN1OctetString.getInstance(alg.getEncryptionScheme().getParameters()).getOctets())); - - // we pass "" as the key algorithm type as it is unknown at this point - return (PrivateKey)cipher.unwrap(data, "", Cipher.PRIVATE_KEY); - } - } - catch (Exception e) - { - throw new IOException("exception unwrapping private key - " + e.toString()); - } - - throw new IOException("exception unwrapping private key - cannot recognise: " + algorithm); - } - - protected byte[] wrapKey( - String algorithm, - Key key, - PKCS12PBEParams pbeParams, - char[] password) - throws IOException - { - PBEKeySpec pbeSpec = new PBEKeySpec(password); - byte[] out; - - try - { - SecretKeyFactory keyFact = SecretKeyFactory.getInstance( - algorithm, bcProvider); - PBEParameterSpec defParams = new PBEParameterSpec( - pbeParams.getIV(), - pbeParams.getIterations().intValue()); - - Cipher cipher = Cipher.getInstance(algorithm, bcProvider); - - cipher.init(Cipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), defParams); - - out = cipher.wrap(key); - } - catch (Exception e) - { - throw new IOException("exception encrypting data - " + e.toString()); - } - - return out; - } - - protected byte[] cryptData( - boolean forEncryption, - AlgorithmIdentifier algId, - char[] password, - boolean wrongPKCS12Zero, - byte[] data) - throws IOException - { - String algorithm = algId.getAlgorithm().getId(); - PKCS12PBEParams pbeParams = PKCS12PBEParams.getInstance(algId.getParameters()); - PBEKeySpec pbeSpec = new PBEKeySpec(password); - - try - { - SecretKeyFactory keyFact = SecretKeyFactory.getInstance(algorithm, bcProvider); - PBEParameterSpec defParams = new PBEParameterSpec( - pbeParams.getIV(), - pbeParams.getIterations().intValue()); - BCPBEKey key = (BCPBEKey)keyFact.generateSecret(pbeSpec); - - key.setTryWrongPKCS12Zero(wrongPKCS12Zero); - - Cipher cipher = Cipher.getInstance(algorithm, bcProvider); - int mode = forEncryption ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE; - cipher.init(mode, key, defParams); - return cipher.doFinal(data); - } - catch (Exception e) - { - throw new IOException("exception decrypting data - " + e.toString()); - } - } - - public void engineLoad( - InputStream stream, - char[] password) - throws IOException - { - if (stream == null) // just initialising - { - return; - } - - if (password == null) - { - throw new NullPointerException("No password supplied for PKCS#12 KeyStore."); - } - - BufferedInputStream bufIn = new BufferedInputStream(stream); - - bufIn.mark(10); - - int head = bufIn.read(); - - if (head != 0x30) - { - throw new IOException("stream does not represent a PKCS12 key store"); - } - - bufIn.reset(); - - ASN1InputStream bIn = new ASN1InputStream(bufIn); - ASN1Sequence obj = (ASN1Sequence)bIn.readObject(); - Pfx bag = Pfx.getInstance(obj); - ContentInfo info = bag.getAuthSafe(); - Vector chain = new Vector(); - boolean unmarkedKey = false; - boolean wrongPKCS12Zero = false; - - if (bag.getMacData() != null) // check the mac code - { - MacData mData = bag.getMacData(); - DigestInfo dInfo = mData.getMac(); - AlgorithmIdentifier algId = dInfo.getAlgorithmId(); - byte[] salt = mData.getSalt(); - int itCount = mData.getIterationCount().intValue(); - - byte[] data = ((ASN1OctetString)info.getContent()).getOctets(); - - try - { - byte[] res = calculatePbeMac(algId.getAlgorithm(), salt, itCount, password, false, data); - byte[] dig = dInfo.getDigest(); - - if (!Arrays.constantTimeAreEqual(res, dig)) - { - if (password.length > 0) - { - throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file."); - } - - // Try with incorrect zero length password - res = calculatePbeMac(algId.getAlgorithm(), salt, itCount, password, true, data); - - if (!Arrays.constantTimeAreEqual(res, dig)) - { - throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file."); - } - - wrongPKCS12Zero = true; - } - } - catch (IOException e) - { - throw e; - } - catch (Exception e) - { - throw new IOException("error constructing MAC: " + e.toString()); - } - } - - keys = new IgnoresCaseHashtable(); - localIds = new Hashtable(); - - if (info.getContentType().equals(data)) - { - bIn = new ASN1InputStream(((ASN1OctetString)info.getContent()).getOctets()); - - AuthenticatedSafe authSafe = AuthenticatedSafe.getInstance(bIn.readObject()); - ContentInfo[] c = authSafe.getContentInfo(); - - for (int i = 0; i != c.length; i++) - { - if (c[i].getContentType().equals(data)) - { - ASN1InputStream dIn = new ASN1InputStream(((ASN1OctetString)c[i].getContent()).getOctets()); - ASN1Sequence seq = (ASN1Sequence)dIn.readObject(); - - for (int j = 0; j != seq.size(); j++) - { - SafeBag b = SafeBag.getInstance(seq.getObjectAt(j)); - if (b.getBagId().equals(pkcs8ShroudedKeyBag)) - { - org.spongycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = org.spongycastle.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(b.getBagValue()); - PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero); - - // - // set the attributes on the key - // - PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)privKey; - String alias = null; - ASN1OctetString localId = null; - - if (b.getBagAttributes() != null) - { - Enumeration e = b.getBagAttributes().getObjects(); - while (e.hasMoreElements()) - { - ASN1Sequence sq = (ASN1Sequence)e.nextElement(); - ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier)sq.getObjectAt(0); - ASN1Set attrSet = (ASN1Set)sq.getObjectAt(1); - ASN1Primitive attr = null; - - if (attrSet.size() > 0) - { - attr = (ASN1Primitive)attrSet.getObjectAt(0); - - ASN1Encodable existing = bagAttr.getBagAttribute(aOid); - if (existing != null) - { - // OK, but the value has to be the same - if (!existing.toASN1Primitive().equals(attr)) - { - throw new IOException( - "attempt to add existing attribute with different value"); - } - } - else - { - bagAttr.setBagAttribute(aOid, attr); - } - } - - if (aOid.equals(pkcs_9_at_friendlyName)) - { - alias = ((DERBMPString)attr).getString(); - keys.put(alias, privKey); - } - else if (aOid.equals(pkcs_9_at_localKeyId)) - { - localId = (ASN1OctetString)attr; - } - } - } - - if (localId != null) - { - String name = new String(Hex.encode(localId.getOctets())); - - if (alias == null) - { - keys.put(name, privKey); - } - else - { - localIds.put(alias, name); - } - } - else - { - unmarkedKey = true; - keys.put("unmarked", privKey); - } - } - else if (b.getBagId().equals(certBag)) - { - chain.addElement(b); - } - else - { - System.out.println("extra in data " + b.getBagId()); - System.out.println(ASN1Dump.dumpAsString(b)); - } - } - } - else if (c[i].getContentType().equals(encryptedData)) - { - EncryptedData d = EncryptedData.getInstance(c[i].getContent()); - byte[] octets = cryptData(false, d.getEncryptionAlgorithm(), - password, wrongPKCS12Zero, d.getContent().getOctets()); - ASN1Sequence seq = (ASN1Sequence)ASN1Primitive.fromByteArray(octets); - - for (int j = 0; j != seq.size(); j++) - { - SafeBag b = SafeBag.getInstance(seq.getObjectAt(j)); - - if (b.getBagId().equals(certBag)) - { - chain.addElement(b); - } - else if (b.getBagId().equals(pkcs8ShroudedKeyBag)) - { - org.spongycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = org.spongycastle.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(b.getBagValue()); - PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero); - - // - // set the attributes on the key - // - PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)privKey; - String alias = null; - ASN1OctetString localId = null; - - Enumeration e = b.getBagAttributes().getObjects(); - while (e.hasMoreElements()) - { - ASN1Sequence sq = (ASN1Sequence)e.nextElement(); - ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier)sq.getObjectAt(0); - ASN1Set attrSet = (ASN1Set)sq.getObjectAt(1); - ASN1Primitive attr = null; - - if (attrSet.size() > 0) - { - attr = (ASN1Primitive)attrSet.getObjectAt(0); - - ASN1Encodable existing = bagAttr.getBagAttribute(aOid); - if (existing != null) - { - // OK, but the value has to be the same - if (!existing.toASN1Primitive().equals(attr)) - { - throw new IOException( - "attempt to add existing attribute with different value"); - } - } - else - { - bagAttr.setBagAttribute(aOid, attr); - } - } - - if (aOid.equals(pkcs_9_at_friendlyName)) - { - alias = ((DERBMPString)attr).getString(); - keys.put(alias, privKey); - } - else if (aOid.equals(pkcs_9_at_localKeyId)) - { - localId = (ASN1OctetString)attr; - } - } - - String name = new String(Hex.encode(localId.getOctets())); - - if (alias == null) - { - keys.put(name, privKey); - } - else - { - localIds.put(alias, name); - } - } - else if (b.getBagId().equals(keyBag)) - { - org.spongycastle.asn1.pkcs.PrivateKeyInfo kInfo = org.spongycastle.asn1.pkcs.PrivateKeyInfo.getInstance(b.getBagValue()); - PrivateKey privKey = BouncyCastleProvider.getPrivateKey(kInfo); - - // - // set the attributes on the key - // - PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)privKey; - String alias = null; - ASN1OctetString localId = null; - - Enumeration e = b.getBagAttributes().getObjects(); - while (e.hasMoreElements()) - { - ASN1Sequence sq = (ASN1Sequence)e.nextElement(); - ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier)sq.getObjectAt(0); - ASN1Set attrSet = (ASN1Set)sq.getObjectAt(1); - ASN1Primitive attr = null; - - if (attrSet.size() > 0) - { - attr = (ASN1Primitive)attrSet.getObjectAt(0); - - ASN1Encodable existing = bagAttr.getBagAttribute(aOid); - if (existing != null) - { - // OK, but the value has to be the same - if (!existing.toASN1Primitive().equals(attr)) - { - throw new IOException( - "attempt to add existing attribute with different value"); - } - } - else - { - bagAttr.setBagAttribute(aOid, attr); - } - } - - if (aOid.equals(pkcs_9_at_friendlyName)) - { - alias = ((DERBMPString)attr).getString(); - keys.put(alias, privKey); - } - else if (aOid.equals(pkcs_9_at_localKeyId)) - { - localId = (ASN1OctetString)attr; - } - } - - String name = new String(Hex.encode(localId.getOctets())); - - if (alias == null) - { - keys.put(name, privKey); - } - else - { - localIds.put(alias, name); - } - } - else - { - System.out.println("extra in encryptedData " + b.getBagId()); - System.out.println(ASN1Dump.dumpAsString(b)); - } - } - } - else - { - System.out.println("extra " + c[i].getContentType().getId()); - System.out.println("extra " + ASN1Dump.dumpAsString(c[i].getContent())); - } - } - } - - certs = new IgnoresCaseHashtable(); - chainCerts = new Hashtable(); - keyCerts = new Hashtable(); - - for (int i = 0; i != chain.size(); i++) - { - SafeBag b = (SafeBag)chain.elementAt(i); - CertBag cb = CertBag.getInstance(b.getBagValue()); - - if (!cb.getCertId().equals(x509Certificate)) - { - throw new RuntimeException("Unsupported certificate type: " + cb.getCertId()); - } - - Certificate cert; - - try - { - ByteArrayInputStream cIn = new ByteArrayInputStream( - ((ASN1OctetString)cb.getCertValue()).getOctets()); - cert = certFact.generateCertificate(cIn); - } - catch (Exception e) - { - throw new RuntimeException(e.toString()); - } - - // - // set the attributes - // - ASN1OctetString localId = null; - String alias = null; - - if (b.getBagAttributes() != null) - { - Enumeration e = b.getBagAttributes().getObjects(); - while (e.hasMoreElements()) - { - ASN1Sequence sq = (ASN1Sequence)e.nextElement(); - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)sq.getObjectAt(0); - ASN1Primitive attr = (ASN1Primitive)((ASN1Set)sq.getObjectAt(1)).getObjectAt(0); - PKCS12BagAttributeCarrier bagAttr = null; - - if (cert instanceof PKCS12BagAttributeCarrier) - { - bagAttr = (PKCS12BagAttributeCarrier)cert; - - ASN1Encodable existing = bagAttr.getBagAttribute(oid); - if (existing != null) - { - // OK, but the value has to be the same - if (!existing.toASN1Primitive().equals(attr)) - { - throw new IOException( - "attempt to add existing attribute with different value"); - } - } - else - { - bagAttr.setBagAttribute(oid, attr); - } - } - - if (oid.equals(pkcs_9_at_friendlyName)) - { - alias = ((DERBMPString)attr).getString(); - } - else if (oid.equals(pkcs_9_at_localKeyId)) - { - localId = (ASN1OctetString)attr; - } - } - } - - chainCerts.put(new CertId(cert.getPublicKey()), cert); - - if (unmarkedKey) - { - if (keyCerts.isEmpty()) - { - String name = new String(Hex.encode(createSubjectKeyId(cert.getPublicKey()).getKeyIdentifier())); - - keyCerts.put(name, cert); - keys.put(name, keys.remove("unmarked")); - } - } - else - { - // - // the local key id needs to override the friendly name - // - if (localId != null) - { - String name = new String(Hex.encode(localId.getOctets())); - - keyCerts.put(name, cert); - } - if (alias != null) - { - certs.put(alias, cert); - } - } - } - } - - public void engineStore(OutputStream stream, char[] password) - throws IOException - { - doStore(stream, password, false); - } - - private void doStore(OutputStream stream, char[] password, boolean useDEREncoding) - throws IOException - { - if (password == null) - { - throw new NullPointerException("No password supplied for PKCS#12 KeyStore."); - } - - // - // handle the key - // - ASN1EncodableVector keyS = new ASN1EncodableVector(); - - - Enumeration ks = keys.keys(); - - while (ks.hasMoreElements()) - { - byte[] kSalt = new byte[SALT_SIZE]; - - random.nextBytes(kSalt); - - String name = (String)ks.nextElement(); - PrivateKey privKey = (PrivateKey)keys.get(name); - PKCS12PBEParams kParams = new PKCS12PBEParams(kSalt, MIN_ITERATIONS); - byte[] kBytes = wrapKey(keyAlgorithm.getId(), privKey, kParams, password); - AlgorithmIdentifier kAlgId = new AlgorithmIdentifier(keyAlgorithm, kParams.toASN1Primitive()); - org.spongycastle.asn1.pkcs.EncryptedPrivateKeyInfo kInfo = new org.spongycastle.asn1.pkcs.EncryptedPrivateKeyInfo(kAlgId, kBytes); - boolean attrSet = false; - ASN1EncodableVector kName = new ASN1EncodableVector(); - - if (privKey instanceof PKCS12BagAttributeCarrier) - { - PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier)privKey; - // - // make sure we are using the local alias on store - // - DERBMPString nm = (DERBMPString)bagAttrs.getBagAttribute(pkcs_9_at_friendlyName); - if (nm == null || !nm.getString().equals(name)) - { - bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name)); - } - - // - // make sure we have a local key-id - // - if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) - { - Certificate ct = engineGetCertificate(name); - - bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(ct.getPublicKey())); - } - - Enumeration e = bagAttrs.getBagAttributeKeys(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - ASN1EncodableVector kSeq = new ASN1EncodableVector(); - - kSeq.add(oid); - kSeq.add(new DERSet(bagAttrs.getBagAttribute(oid))); - - attrSet = true; - - kName.add(new DERSequence(kSeq)); - } - } - - if (!attrSet) - { - // - // set a default friendly name (from the key id) and local id - // - ASN1EncodableVector kSeq = new ASN1EncodableVector(); - Certificate ct = engineGetCertificate(name); - - kSeq.add(pkcs_9_at_localKeyId); - kSeq.add(new DERSet(createSubjectKeyId(ct.getPublicKey()))); - - kName.add(new DERSequence(kSeq)); - - kSeq = new ASN1EncodableVector(); - - kSeq.add(pkcs_9_at_friendlyName); - kSeq.add(new DERSet(new DERBMPString(name))); - - kName.add(new DERSequence(kSeq)); - } - - SafeBag kBag = new SafeBag(pkcs8ShroudedKeyBag, kInfo.toASN1Primitive(), new DERSet(kName)); - keyS.add(kBag); - } - - byte[] keySEncoded = new DERSequence(keyS).getEncoded(ASN1Encoding.DER); - BEROctetString keyString = new BEROctetString(keySEncoded); - - // - // certificate processing - // - byte[] cSalt = new byte[SALT_SIZE]; - - random.nextBytes(cSalt); - - ASN1EncodableVector certSeq = new ASN1EncodableVector(); - PKCS12PBEParams cParams = new PKCS12PBEParams(cSalt, MIN_ITERATIONS); - AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.toASN1Primitive()); - Hashtable doneCerts = new Hashtable(); - - Enumeration cs = keys.keys(); - while (cs.hasMoreElements()) - { - try - { - String name = (String)cs.nextElement(); - Certificate cert = engineGetCertificate(name); - boolean cAttrSet = false; - CertBag cBag = new CertBag( - x509Certificate, - new DEROctetString(cert.getEncoded())); - ASN1EncodableVector fName = new ASN1EncodableVector(); - - if (cert instanceof PKCS12BagAttributeCarrier) - { - PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier)cert; - // - // make sure we are using the local alias on store - // - DERBMPString nm = (DERBMPString)bagAttrs.getBagAttribute(pkcs_9_at_friendlyName); - if (nm == null || !nm.getString().equals(name)) - { - bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name)); - } - - // - // make sure we have a local key-id - // - if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) - { - bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(cert.getPublicKey())); - } - - Enumeration e = bagAttrs.getBagAttributeKeys(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - ASN1EncodableVector fSeq = new ASN1EncodableVector(); - - fSeq.add(oid); - fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid))); - fName.add(new DERSequence(fSeq)); - - cAttrSet = true; - } - } - - if (!cAttrSet) - { - ASN1EncodableVector fSeq = new ASN1EncodableVector(); - - fSeq.add(pkcs_9_at_localKeyId); - fSeq.add(new DERSet(createSubjectKeyId(cert.getPublicKey()))); - fName.add(new DERSequence(fSeq)); - - fSeq = new ASN1EncodableVector(); - - fSeq.add(pkcs_9_at_friendlyName); - fSeq.add(new DERSet(new DERBMPString(name))); - - fName.add(new DERSequence(fSeq)); - } - - SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName)); - - certSeq.add(sBag); - - doneCerts.put(cert, cert); - } - catch (CertificateEncodingException e) - { - throw new IOException("Error encoding certificate: " + e.toString()); - } - } - - cs = certs.keys(); - while (cs.hasMoreElements()) - { - try - { - String certId = (String)cs.nextElement(); - Certificate cert = (Certificate)certs.get(certId); - boolean cAttrSet = false; - - if (keys.get(certId) != null) - { - continue; - } - - CertBag cBag = new CertBag( - x509Certificate, - new DEROctetString(cert.getEncoded())); - ASN1EncodableVector fName = new ASN1EncodableVector(); - - if (cert instanceof PKCS12BagAttributeCarrier) - { - PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier)cert; - // - // make sure we are using the local alias on store - // - DERBMPString nm = (DERBMPString)bagAttrs.getBagAttribute(pkcs_9_at_friendlyName); - if (nm == null || !nm.getString().equals(certId)) - { - bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(certId)); - } - - Enumeration e = bagAttrs.getBagAttributeKeys(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - - // a certificate not immediately linked to a key doesn't require - // a localKeyID and will confuse some PKCS12 implementations. - // - // If we find one, we'll prune it out. - if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) - { - continue; - } - - ASN1EncodableVector fSeq = new ASN1EncodableVector(); - - fSeq.add(oid); - fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid))); - fName.add(new DERSequence(fSeq)); - - cAttrSet = true; - } - } - - if (!cAttrSet) - { - ASN1EncodableVector fSeq = new ASN1EncodableVector(); - - fSeq.add(pkcs_9_at_friendlyName); - fSeq.add(new DERSet(new DERBMPString(certId))); - - fName.add(new DERSequence(fSeq)); - } - - SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName)); - - certSeq.add(sBag); - - doneCerts.put(cert, cert); - } - catch (CertificateEncodingException e) - { - throw new IOException("Error encoding certificate: " + e.toString()); - } - } - - cs = chainCerts.keys(); - while (cs.hasMoreElements()) - { - try - { - CertId certId = (CertId)cs.nextElement(); - Certificate cert = (Certificate)chainCerts.get(certId); - - if (doneCerts.get(cert) != null) - { - continue; - } - - CertBag cBag = new CertBag( - x509Certificate, - new DEROctetString(cert.getEncoded())); - ASN1EncodableVector fName = new ASN1EncodableVector(); - - if (cert instanceof PKCS12BagAttributeCarrier) - { - PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier)cert; - Enumeration e = bagAttrs.getBagAttributeKeys(); - - while (e.hasMoreElements()) - { - ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); - - // a certificate not immediately linked to a key doesn't require - // a localKeyID and will confuse some PKCS12 implementations. - // - // If we find one, we'll prune it out. - if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) - { - continue; - } - - ASN1EncodableVector fSeq = new ASN1EncodableVector(); - - fSeq.add(oid); - fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid))); - fName.add(new DERSequence(fSeq)); - } - } - - SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName)); - - certSeq.add(sBag); - } - catch (CertificateEncodingException e) - { - throw new IOException("Error encoding certificate: " + e.toString()); - } - } - - byte[] certSeqEncoded = new DERSequence(certSeq).getEncoded(ASN1Encoding.DER); - byte[] certBytes = cryptData(true, cAlgId, password, false, certSeqEncoded); - EncryptedData cInfo = new EncryptedData(data, cAlgId, new BEROctetString(certBytes)); - - ContentInfo[] info = new ContentInfo[] - { - new ContentInfo(data, keyString), - new ContentInfo(encryptedData, cInfo.toASN1Primitive()) - }; - - AuthenticatedSafe auth = new AuthenticatedSafe(info); - - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - DEROutputStream asn1Out; - if (useDEREncoding) - { - asn1Out = new DEROutputStream(bOut); - } - else - { - asn1Out = new BEROutputStream(bOut); - } - - asn1Out.writeObject(auth); - - byte[] pkg = bOut.toByteArray(); - - ContentInfo mainInfo = new ContentInfo(data, new BEROctetString(pkg)); - - // - // create the mac - // - byte[] mSalt = new byte[20]; - int itCount = MIN_ITERATIONS; - - random.nextBytes(mSalt); - - byte[] data = ((ASN1OctetString)mainInfo.getContent()).getOctets(); - - MacData mData; - - try - { - byte[] res = calculatePbeMac(id_SHA1, mSalt, itCount, password, false, data); - - AlgorithmIdentifier algId = new AlgorithmIdentifier(id_SHA1, DERNull.INSTANCE); - DigestInfo dInfo = new DigestInfo(algId, res); - - mData = new MacData(dInfo, mSalt, itCount); - } - catch (Exception e) - { - throw new IOException("error constructing MAC: " + e.toString()); - } - - // - // output the Pfx - // - Pfx pfx = new Pfx(mainInfo, mData); - - if (useDEREncoding) - { - asn1Out = new DEROutputStream(stream); - } - else - { - asn1Out = new BEROutputStream(stream); - } - - asn1Out.writeObject(pfx); - } - - private static byte[] calculatePbeMac( - ASN1ObjectIdentifier oid, - byte[] salt, - int itCount, - char[] password, - boolean wrongPkcs12Zero, - byte[] data) - throws Exception - { - SecretKeyFactory keyFact = SecretKeyFactory.getInstance(oid.getId(), bcProvider); - PBEParameterSpec defParams = new PBEParameterSpec(salt, itCount); - PBEKeySpec pbeSpec = new PBEKeySpec(password); - BCPBEKey key = (BCPBEKey)keyFact.generateSecret(pbeSpec); - key.setTryWrongPKCS12Zero(wrongPkcs12Zero); - - Mac mac = Mac.getInstance(oid.getId(), bcProvider); - mac.init(key, defParams); - mac.update(data); - return mac.doFinal(); - } - - public static class BCPKCS12KeyStore - extends PKCS12KeyStoreSpi - { - public BCPKCS12KeyStore() - { - super(bcProvider, pbeWithSHAAnd3_KeyTripleDES_CBC, pbeWithSHAAnd40BitRC2_CBC); - } - } - - public static class BCPKCS12KeyStore3DES - extends PKCS12KeyStoreSpi - { - public BCPKCS12KeyStore3DES() - { - super(bcProvider, pbeWithSHAAnd3_KeyTripleDES_CBC, pbeWithSHAAnd3_KeyTripleDES_CBC); - } - } - - public static class DefPKCS12KeyStore - extends PKCS12KeyStoreSpi - { - public DefPKCS12KeyStore() - { - super(null, pbeWithSHAAnd3_KeyTripleDES_CBC, pbeWithSHAAnd40BitRC2_CBC); - } - } - - public static class DefPKCS12KeyStore3DES - extends PKCS12KeyStoreSpi - { - public DefPKCS12KeyStore3DES() - { - super(null, pbeWithSHAAnd3_KeyTripleDES_CBC, pbeWithSHAAnd3_KeyTripleDES_CBC); - } - } - - private static class IgnoresCaseHashtable - { - private Hashtable orig = new Hashtable(); - private Hashtable keys = new Hashtable(); - - public void put(String key, Object value) - { - String lower = (key == null) ? null : Strings.toLowerCase(key); - String k = (String)keys.get(lower); - if (k != null) - { - orig.remove(k); - } - - keys.put(lower, key); - orig.put(key, value); - } - - public Enumeration keys() - { - return orig.keys(); - } - - public Object remove(String alias) - { - String k = (String)keys.remove(alias == null ? null : Strings.toLowerCase(alias)); - if (k == null) - { - return null; - } - - return orig.remove(k); - } - - public Object get(String alias) - { - String k = (String)keys.get(alias == null ? null : Strings.toLowerCase(alias)); - if (k == null) - { - return null; - } - - return orig.get(k); - } - - public Enumeration elements() - { - return orig.elements(); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jce/interfaces/ECKey.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jce/interfaces/ECKey.java deleted file mode 100644 index 1cee721d2..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jce/interfaces/ECKey.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.spongycastle.jce.interfaces; - -import org.spongycastle.jce.spec.ECParameterSpec; - -/** - * generic interface for an Elliptic Curve Key. - */ -public interface ECKey -{ - /** - * return a parameter specification representing the EC domain parameters - * for the key. - * @deprecated this method vanises in JDK 1.5. Use getParameters(). - */ - public ECParameterSpec getParams(); - - /** - * return a parameter specification representing the EC domain parameters - * for the key. - */ - public ECParameterSpec getParameters(); -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jce/provider/BouncyCastleProviderConfiguration.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jce/provider/BouncyCastleProviderConfiguration.java deleted file mode 100644 index 17adb3116..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jce/provider/BouncyCastleProviderConfiguration.java +++ /dev/null @@ -1,166 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.security.Permission; - -import javax.crypto.spec.DHParameterSpec; - -import org.spongycastle.jcajce.provider.config.ConfigurableProvider; -import org.spongycastle.jcajce.provider.config.ProviderConfiguration; -import org.spongycastle.jcajce.provider.config.ProviderConfigurationPermission; -import org.spongycastle.jce.spec.ECParameterSpec; - -class BouncyCastleProviderConfiguration - implements ProviderConfiguration -{ - private static Permission BC_EC_LOCAL_PERMISSION = new ProviderConfigurationPermission( - BouncyCastleProvider.PROVIDER_NAME, ConfigurableProvider.THREAD_LOCAL_EC_IMPLICITLY_CA); - private static Permission BC_EC_PERMISSION = new ProviderConfigurationPermission( - BouncyCastleProvider.PROVIDER_NAME, ConfigurableProvider.EC_IMPLICITLY_CA); - private static Permission BC_DH_LOCAL_PERMISSION = new ProviderConfigurationPermission( - BouncyCastleProvider.PROVIDER_NAME, ConfigurableProvider.THREAD_LOCAL_DH_DEFAULT_PARAMS); - private static Permission BC_DH_PERMISSION = new ProviderConfigurationPermission( - BouncyCastleProvider.PROVIDER_NAME, ConfigurableProvider.DH_DEFAULT_PARAMS); - - private ThreadLocal ecThreadSpec = new ThreadLocal(); - private ThreadLocal dhThreadSpec = new ThreadLocal(); - - private volatile ECParameterSpec ecImplicitCaParams; - private volatile Object dhDefaultParams; - - void setParameter(String parameterName, Object parameter) - { - SecurityManager securityManager = System.getSecurityManager(); - - if (parameterName.equals(ConfigurableProvider.THREAD_LOCAL_EC_IMPLICITLY_CA)) - { - ECParameterSpec curveSpec; - - if (securityManager != null) - { - securityManager.checkPermission(BC_EC_LOCAL_PERMISSION); - } - - if (parameter instanceof ECParameterSpec || parameter == null) - { - curveSpec = (ECParameterSpec)parameter; - } - else - { - throw new IllegalArgumentException("not a valid ECParameterSpec"); - } - - if (curveSpec == null) - { - ecThreadSpec.set(null); - } - else - { - ecThreadSpec.set(curveSpec); - } - } - else if (parameterName.equals(ConfigurableProvider.EC_IMPLICITLY_CA)) - { - if (securityManager != null) - { - securityManager.checkPermission(BC_EC_PERMISSION); - } - - if (parameter instanceof ECParameterSpec || parameter == null) - { - ecImplicitCaParams = (ECParameterSpec)parameter; - } - else // assume java.security.spec - { - throw new IllegalArgumentException("not a valid ECParameterSpec"); - } - } - else if (parameterName.equals(ConfigurableProvider.THREAD_LOCAL_DH_DEFAULT_PARAMS)) - { - Object dhSpec; - - if (securityManager != null) - { - securityManager.checkPermission(BC_DH_LOCAL_PERMISSION); - } - - if (parameter instanceof DHParameterSpec || parameter instanceof DHParameterSpec[] || parameter == null) - { - dhSpec = parameter; - } - else - { - throw new IllegalArgumentException("not a valid DHParameterSpec"); - } - - if (dhSpec == null) - { - dhThreadSpec.set(null); - } - else - { - dhThreadSpec.set(dhSpec); - } - } - else if (parameterName.equals(ConfigurableProvider.DH_DEFAULT_PARAMS)) - { - if (securityManager != null) - { - securityManager.checkPermission(BC_DH_PERMISSION); - } - - if (parameter instanceof DHParameterSpec || parameter instanceof DHParameterSpec[] || parameter == null) - { - dhDefaultParams = parameter; - } - else - { - throw new IllegalArgumentException("not a valid DHParameterSpec or DHParameterSpec[]"); - } - } - } - - public ECParameterSpec getEcImplicitlyCa() - { - ECParameterSpec spec = (ECParameterSpec)ecThreadSpec.get(); - - if (spec != null) - { - return spec; - } - - return ecImplicitCaParams; - } - - public DHParameterSpec getDHDefaultParameters(int keySize) - { - Object params = dhThreadSpec.get(); - if (params == null) - { - params = dhDefaultParams; - } - - if (params instanceof DHParameterSpec) - { - DHParameterSpec spec = (DHParameterSpec)params; - - if (spec.getP().bitLength() == keySize) - { - return spec; - } - } - else if (params instanceof DHParameterSpec[]) - { - DHParameterSpec[] specs = (DHParameterSpec[])params; - - for (int i = 0; i != specs.length; i++) - { - if (specs[i].getP().bitLength() == keySize) - { - return specs[i]; - } - } - } - - return null; - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jce/provider/CertPathValidatorUtilities.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jce/provider/CertPathValidatorUtilities.java deleted file mode 100644 index e90b38954..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jce/provider/CertPathValidatorUtilities.java +++ /dev/null @@ -1,1439 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.security.GeneralSecurityException; -import java.security.KeyFactory; -import java.security.PublicKey; -import java.security.cert.CRLException; -import java.security.cert.CertPath; -import java.security.cert.CertPathValidatorException; -import java.security.cert.CertStore; -import java.security.cert.CertStoreException; -import java.security.cert.Certificate; -import java.security.cert.CertificateParsingException; -import java.security.cert.PKIXParameters; -import java.security.cert.PolicyQualifierInfo; -import java.security.cert.TrustAnchor; -import java.security.cert.X509CRL; -import java.security.cert.X509CRLEntry; -import java.security.cert.X509CRLSelector; -import java.security.cert.X509CertSelector; -import java.security.cert.X509Certificate; -import java.security.interfaces.DSAParams; -import java.security.interfaces.DSAPublicKey; -import java.security.spec.DSAPublicKeySpec; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.security.auth.x500.X500Principal; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.ASN1OctetString; -import org.spongycastle.asn1.ASN1OutputStream; -import org.spongycastle.asn1.ASN1Primitive; -import org.spongycastle.asn1.ASN1Sequence; -import org.spongycastle.asn1.ASN1Enumerated; -import org.spongycastle.asn1.ASN1GeneralizedTime; -import org.spongycastle.asn1.DERIA5String; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.DERSequence; -import org.spongycastle.asn1.isismtt.ISISMTTObjectIdentifiers; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; -import org.spongycastle.asn1.x509.CRLDistPoint; -import org.spongycastle.asn1.x509.CRLReason; -import org.spongycastle.asn1.x509.CertificateList; -import org.spongycastle.asn1.x509.DistributionPoint; -import org.spongycastle.asn1.x509.DistributionPointName; -import org.spongycastle.asn1.x509.GeneralName; -import org.spongycastle.asn1.x509.GeneralNames; -import org.spongycastle.asn1.x509.PolicyInformation; -import org.spongycastle.asn1.x509.SubjectPublicKeyInfo; -import org.spongycastle.asn1.x509.X509Extension; -import org.spongycastle.asn1.x509.X509Extensions; -import org.spongycastle.jce.X509LDAPCertStoreParameters; -import org.spongycastle.jce.exception.ExtCertPathValidatorException; -import org.spongycastle.util.Selector; -import org.spongycastle.util.StoreException; -import org.spongycastle.util.Integers; -import org.spongycastle.x509.ExtendedPKIXBuilderParameters; -import org.spongycastle.x509.ExtendedPKIXParameters; -import org.spongycastle.x509.X509AttributeCertStoreSelector; -import org.spongycastle.x509.X509AttributeCertificate; -import org.spongycastle.x509.X509CRLStoreSelector; -import org.spongycastle.x509.X509CertStoreSelector; -import org.spongycastle.x509.X509Store; - -public class CertPathValidatorUtilities -{ - protected static final PKIXCRLUtil CRL_UTIL = new PKIXCRLUtil(); - - protected static final String CERTIFICATE_POLICIES = X509Extensions.CertificatePolicies.getId(); - protected static final String BASIC_CONSTRAINTS = X509Extensions.BasicConstraints.getId(); - protected static final String POLICY_MAPPINGS = X509Extensions.PolicyMappings.getId(); - protected static final String SUBJECT_ALTERNATIVE_NAME = X509Extensions.SubjectAlternativeName.getId(); - protected static final String NAME_CONSTRAINTS = X509Extensions.NameConstraints.getId(); - protected static final String KEY_USAGE = X509Extensions.KeyUsage.getId(); - protected static final String INHIBIT_ANY_POLICY = X509Extensions.InhibitAnyPolicy.getId(); - protected static final String ISSUING_DISTRIBUTION_POINT = X509Extensions.IssuingDistributionPoint.getId(); - protected static final String DELTA_CRL_INDICATOR = X509Extensions.DeltaCRLIndicator.getId(); - protected static final String POLICY_CONSTRAINTS = X509Extensions.PolicyConstraints.getId(); - protected static final String FRESHEST_CRL = X509Extensions.FreshestCRL.getId(); - protected static final String CRL_DISTRIBUTION_POINTS = X509Extensions.CRLDistributionPoints.getId(); - protected static final String AUTHORITY_KEY_IDENTIFIER = X509Extensions.AuthorityKeyIdentifier.getId(); - - protected static final String ANY_POLICY = "2.5.29.32.0"; - - protected static final String CRL_NUMBER = X509Extensions.CRLNumber.getId(); - - /* - * key usage bits - */ - protected static final int KEY_CERT_SIGN = 5; - protected static final int CRL_SIGN = 6; - - protected static final String[] crlReasons = new String[]{ - "unspecified", - "keyCompromise", - "cACompromise", - "affiliationChanged", - "superseded", - "cessationOfOperation", - "certificateHold", - "unknown", - "removeFromCRL", - "privilegeWithdrawn", - "aACompromise"}; - - /** - * Search the given Set of TrustAnchor's for one that is the - * issuer of the given X509 certificate. Uses the default provider - * for signature verification. - * - * @param cert the X509 certificate - * @param trustAnchors a Set of TrustAnchor's - * @return the TrustAnchor object if found or - * null if not. - * @throws AnnotatedException if a TrustAnchor was found but the signature verification - * on the given certificate has thrown an exception. - */ - protected static TrustAnchor findTrustAnchor( - X509Certificate cert, - Set trustAnchors) - throws AnnotatedException - { - return findTrustAnchor(cert, trustAnchors, null); - } - - /** - * Search the given Set of TrustAnchor's for one that is the - * issuer of the given X509 certificate. Uses the specified - * provider for signature verification, or the default provider - * if null. - * - * @param cert the X509 certificate - * @param trustAnchors a Set of TrustAnchor's - * @param sigProvider the provider to use for signature verification - * @return the TrustAnchor object if found or - * null if not. - * @throws AnnotatedException if a TrustAnchor was found but the signature verification - * on the given certificate has thrown an exception. - */ - protected static TrustAnchor findTrustAnchor( - X509Certificate cert, - Set trustAnchors, - String sigProvider) - throws AnnotatedException - { - TrustAnchor trust = null; - PublicKey trustPublicKey = null; - Exception invalidKeyEx = null; - - X509CertSelector certSelectX509 = new X509CertSelector(); - X500Principal certIssuer = getEncodedIssuerPrincipal(cert); - - try - { - certSelectX509.setSubject(certIssuer.getEncoded()); - } - catch (IOException ex) - { - throw new AnnotatedException("Cannot set subject search criteria for trust anchor.", ex); - } - - Iterator iter = trustAnchors.iterator(); - while (iter.hasNext() && trust == null) - { - trust = (TrustAnchor)iter.next(); - if (trust.getTrustedCert() != null) - { - if (certSelectX509.match(trust.getTrustedCert())) - { - trustPublicKey = trust.getTrustedCert().getPublicKey(); - } - else - { - trust = null; - } - } - else if (trust.getCAName() != null - && trust.getCAPublicKey() != null) - { - try - { - X500Principal caName = new X500Principal(trust.getCAName()); - if (certIssuer.equals(caName)) - { - trustPublicKey = trust.getCAPublicKey(); - } - else - { - trust = null; - } - } - catch (IllegalArgumentException ex) - { - trust = null; - } - } - else - { - trust = null; - } - - if (trustPublicKey != null) - { - try - { - verifyX509Certificate(cert, trustPublicKey, sigProvider); - } - catch (Exception ex) - { - invalidKeyEx = ex; - trust = null; - trustPublicKey = null; - } - } - } - - if (trust == null && invalidKeyEx != null) - { - throw new AnnotatedException("TrustAnchor found but certificate validation failed.", invalidKeyEx); - } - - return trust; - } - - protected static void addAdditionalStoresFromAltNames( - X509Certificate cert, - ExtendedPKIXParameters pkixParams) - throws CertificateParsingException - { - // if in the IssuerAltName extension an URI - // is given, add an additinal X.509 store - if (cert.getIssuerAlternativeNames() != null) - { - Iterator it = cert.getIssuerAlternativeNames().iterator(); - while (it.hasNext()) - { - // look for URI - List list = (List)it.next(); - if (list.get(0).equals(Integers.valueOf(GeneralName.uniformResourceIdentifier))) - { - // found - String temp = (String)list.get(1); - CertPathValidatorUtilities.addAdditionalStoreFromLocation(temp, pkixParams); - } - } - } - } - - /** - * Returns the issuer of an attribute certificate or certificate. - * - * @param cert The attribute certificate or certificate. - * @return The issuer as X500Principal. - */ - protected static X500Principal getEncodedIssuerPrincipal( - Object cert) - { - if (cert instanceof X509Certificate) - { - return ((X509Certificate)cert).getIssuerX500Principal(); - } - else - { - return (X500Principal)((X509AttributeCertificate)cert).getIssuer().getPrincipals()[0]; - } - } - - protected static Date getValidDate(PKIXParameters paramsPKIX) - { - Date validDate = paramsPKIX.getDate(); - - if (validDate == null) - { - validDate = new Date(); - } - - return validDate; - } - - protected static X500Principal getSubjectPrincipal(X509Certificate cert) - { - return cert.getSubjectX500Principal(); - } - - protected static boolean isSelfIssued(X509Certificate cert) - { - return cert.getSubjectDN().equals(cert.getIssuerDN()); - } - - - /** - * Extract the value of the given extension, if it exists. - * - * @param ext The extension object. - * @param oid The object identifier to obtain. - * @throws AnnotatedException if the extension cannot be read. - */ - protected static ASN1Primitive getExtensionValue( - java.security.cert.X509Extension ext, - String oid) - throws AnnotatedException - { - byte[] bytes = ext.getExtensionValue(oid); - if (bytes == null) - { - return null; - } - - return getObject(oid, bytes); - } - - private static ASN1Primitive getObject( - String oid, - byte[] ext) - throws AnnotatedException - { - try - { - ASN1InputStream aIn = new ASN1InputStream(ext); - ASN1OctetString octs = (ASN1OctetString)aIn.readObject(); - - aIn = new ASN1InputStream(octs.getOctets()); - return aIn.readObject(); - } - catch (Exception e) - { - throw new AnnotatedException("exception processing extension " + oid, e); - } - } - - protected static X500Principal getIssuerPrincipal(X509CRL crl) - { - return crl.getIssuerX500Principal(); - } - - protected static AlgorithmIdentifier getAlgorithmIdentifier( - PublicKey key) - throws CertPathValidatorException - { - try - { - ASN1InputStream aIn = new ASN1InputStream(key.getEncoded()); - - SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); - - return info.getAlgorithmId(); - } - catch (Exception e) - { - throw new ExtCertPathValidatorException("Subject public key cannot be decoded.", e); - } - } - - // crl checking - - - // - // policy checking - // - - protected static final Set getQualifierSet(ASN1Sequence qualifiers) - throws CertPathValidatorException - { - Set pq = new HashSet(); - - if (qualifiers == null) - { - return pq; - } - - ByteArrayOutputStream bOut = new ByteArrayOutputStream(); - ASN1OutputStream aOut = new ASN1OutputStream(bOut); - - Enumeration e = qualifiers.getObjects(); - - while (e.hasMoreElements()) - { - try - { - aOut.writeObject((ASN1Encodable)e.nextElement()); - - pq.add(new PolicyQualifierInfo(bOut.toByteArray())); - } - catch (IOException ex) - { - throw new ExtCertPathValidatorException("Policy qualifier info cannot be decoded.", ex); - } - - bOut.reset(); - } - - return pq; - } - - protected static PKIXPolicyNode removePolicyNode( - PKIXPolicyNode validPolicyTree, - List[] policyNodes, - PKIXPolicyNode _node) - { - PKIXPolicyNode _parent = (PKIXPolicyNode)_node.getParent(); - - if (validPolicyTree == null) - { - return null; - } - - if (_parent == null) - { - for (int j = 0; j < policyNodes.length; j++) - { - policyNodes[j] = new ArrayList(); - } - - return null; - } - else - { - _parent.removeChild(_node); - removePolicyNodeRecurse(policyNodes, _node); - - return validPolicyTree; - } - } - - private static void removePolicyNodeRecurse( - List[] policyNodes, - PKIXPolicyNode _node) - { - policyNodes[_node.getDepth()].remove(_node); - - if (_node.hasChildren()) - { - Iterator _iter = _node.getChildren(); - while (_iter.hasNext()) - { - PKIXPolicyNode _child = (PKIXPolicyNode)_iter.next(); - removePolicyNodeRecurse(policyNodes, _child); - } - } - } - - - protected static boolean processCertD1i( - int index, - List[] policyNodes, - ASN1ObjectIdentifier pOid, - Set pq) - { - List policyNodeVec = policyNodes[index - 1]; - - for (int j = 0; j < policyNodeVec.size(); j++) - { - PKIXPolicyNode node = (PKIXPolicyNode)policyNodeVec.get(j); - Set expectedPolicies = node.getExpectedPolicies(); - - if (expectedPolicies.contains(pOid.getId())) - { - Set childExpectedPolicies = new HashSet(); - childExpectedPolicies.add(pOid.getId()); - - PKIXPolicyNode child = new PKIXPolicyNode(new ArrayList(), - index, - childExpectedPolicies, - node, - pq, - pOid.getId(), - false); - node.addChild(child); - policyNodes[index].add(child); - - return true; - } - } - - return false; - } - - protected static void processCertD1ii( - int index, - List[] policyNodes, - ASN1ObjectIdentifier _poid, - Set _pq) - { - List policyNodeVec = policyNodes[index - 1]; - - for (int j = 0; j < policyNodeVec.size(); j++) - { - PKIXPolicyNode _node = (PKIXPolicyNode)policyNodeVec.get(j); - - if (ANY_POLICY.equals(_node.getValidPolicy())) - { - Set _childExpectedPolicies = new HashSet(); - _childExpectedPolicies.add(_poid.getId()); - - PKIXPolicyNode _child = new PKIXPolicyNode(new ArrayList(), - index, - _childExpectedPolicies, - _node, - _pq, - _poid.getId(), - false); - _node.addChild(_child); - policyNodes[index].add(_child); - return; - } - } - } - - protected static void prepareNextCertB1( - int i, - List[] policyNodes, - String id_p, - Map m_idp, - X509Certificate cert - ) - throws AnnotatedException, CertPathValidatorException - { - boolean idp_found = false; - Iterator nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (node.getValidPolicy().equals(id_p)) - { - idp_found = true; - node.expectedPolicies = (Set)m_idp.get(id_p); - break; - } - } - - if (!idp_found) - { - nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (ANY_POLICY.equals(node.getValidPolicy())) - { - Set pq = null; - ASN1Sequence policies = null; - try - { - policies = DERSequence.getInstance(getExtensionValue(cert, CERTIFICATE_POLICIES)); - } - catch (Exception e) - { - throw new AnnotatedException("Certificate policies cannot be decoded.", e); - } - Enumeration e = policies.getObjects(); - while (e.hasMoreElements()) - { - PolicyInformation pinfo = null; - - try - { - pinfo = PolicyInformation.getInstance(e.nextElement()); - } - catch (Exception ex) - { - throw new AnnotatedException("Policy information cannot be decoded.", ex); - } - if (ANY_POLICY.equals(pinfo.getPolicyIdentifier().getId())) - { - try - { - pq = getQualifierSet(pinfo.getPolicyQualifiers()); - } - catch (CertPathValidatorException ex) - { - throw new ExtCertPathValidatorException( - "Policy qualifier info set could not be built.", ex); - } - break; - } - } - boolean ci = false; - if (cert.getCriticalExtensionOIDs() != null) - { - ci = cert.getCriticalExtensionOIDs().contains(CERTIFICATE_POLICIES); - } - - PKIXPolicyNode p_node = (PKIXPolicyNode)node.getParent(); - if (ANY_POLICY.equals(p_node.getValidPolicy())) - { - PKIXPolicyNode c_node = new PKIXPolicyNode( - new ArrayList(), i, - (Set)m_idp.get(id_p), - p_node, pq, id_p, ci); - p_node.addChild(c_node); - policyNodes[i].add(c_node); - } - break; - } - } - } - } - - protected static PKIXPolicyNode prepareNextCertB2( - int i, - List[] policyNodes, - String id_p, - PKIXPolicyNode validPolicyTree) - { - Iterator nodes_i = policyNodes[i].iterator(); - while (nodes_i.hasNext()) - { - PKIXPolicyNode node = (PKIXPolicyNode)nodes_i.next(); - if (node.getValidPolicy().equals(id_p)) - { - PKIXPolicyNode p_node = (PKIXPolicyNode)node.getParent(); - p_node.removeChild(node); - nodes_i.remove(); - for (int k = (i - 1); k >= 0; k--) - { - List nodes = policyNodes[k]; - for (int l = 0; l < nodes.size(); l++) - { - PKIXPolicyNode node2 = (PKIXPolicyNode)nodes.get(l); - if (!node2.hasChildren()) - { - validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, node2); - if (validPolicyTree == null) - { - break; - } - } - } - } - } - } - return validPolicyTree; - } - - protected static boolean isAnyPolicy( - Set policySet) - { - return policySet == null || policySet.contains(ANY_POLICY) || policySet.isEmpty(); - } - - protected static void addAdditionalStoreFromLocation(String location, - ExtendedPKIXParameters pkixParams) - { - if (pkixParams.isAdditionalLocationsEnabled()) - { - try - { - if (location.startsWith("ldap://")) - { - // ldap://directory.d-trust.net/CN=D-TRUST - // Qualified CA 2003 1:PN,O=D-Trust GmbH,C=DE - // skip "ldap://" - location = location.substring(7); - // after first / baseDN starts - String base = null; - String url = null; - if (location.indexOf("/") != -1) - { - base = location.substring(location.indexOf("/")); - // URL - url = "ldap://" - + location.substring(0, location.indexOf("/")); - } - else - { - url = "ldap://" + location; - } - // use all purpose parameters - X509LDAPCertStoreParameters params = new X509LDAPCertStoreParameters.Builder( - url, base).build(); - pkixParams.addAdditionalStore(X509Store.getInstance( - "CERTIFICATE/LDAP", params, BouncyCastleProvider.PROVIDER_NAME)); - pkixParams.addAdditionalStore(X509Store.getInstance( - "CRL/LDAP", params, BouncyCastleProvider.PROVIDER_NAME)); - pkixParams.addAdditionalStore(X509Store.getInstance( - "ATTRIBUTECERTIFICATE/LDAP", params, BouncyCastleProvider.PROVIDER_NAME)); - pkixParams.addAdditionalStore(X509Store.getInstance( - "CERTIFICATEPAIR/LDAP", params, BouncyCastleProvider.PROVIDER_NAME)); - } - } - catch (Exception e) - { - // cannot happen - throw new RuntimeException("Exception adding X.509 stores."); - } - } - } - - /** - * Return a Collection of all certificates or attribute certificates found - * in the X509Store's that are matching the certSelect criteriums. - * - * @param certSelect a {@link Selector} object that will be used to select - * the certificates - * @param certStores a List containing only {@link X509Store} objects. These - * are used to search for certificates. - * @return a Collection of all found {@link X509Certificate} or - * {@link org.spongycastle.x509.X509AttributeCertificate} objects. - * May be empty but never null. - */ - protected static Collection findCertificates(X509CertStoreSelector certSelect, - List certStores) - throws AnnotatedException - { - Set certs = new HashSet(); - Iterator iter = certStores.iterator(); - - while (iter.hasNext()) - { - Object obj = iter.next(); - - if (obj instanceof X509Store) - { - X509Store certStore = (X509Store)obj; - try - { - certs.addAll(certStore.getMatches(certSelect)); - } - catch (StoreException e) - { - throw new AnnotatedException( - "Problem while picking certificates from X.509 store.", e); - } - } - else - { - CertStore certStore = (CertStore)obj; - - try - { - certs.addAll(certStore.getCertificates(certSelect)); - } - catch (CertStoreException e) - { - throw new AnnotatedException( - "Problem while picking certificates from certificate store.", - e); - } - } - } - return certs; - } - - protected static Collection findCertificates(X509AttributeCertStoreSelector certSelect, - List certStores) - throws AnnotatedException - { - Set certs = new HashSet(); - Iterator iter = certStores.iterator(); - - while (iter.hasNext()) - { - Object obj = iter.next(); - - if (obj instanceof X509Store) - { - X509Store certStore = (X509Store)obj; - try - { - certs.addAll(certStore.getMatches(certSelect)); - } - catch (StoreException e) - { - throw new AnnotatedException( - "Problem while picking certificates from X.509 store.", e); - } - } - } - return certs; - } - - protected static void addAdditionalStoresFromCRLDistributionPoint( - CRLDistPoint crldp, ExtendedPKIXParameters pkixParams) - throws AnnotatedException - { - if (crldp != null) - { - DistributionPoint dps[] = null; - try - { - dps = crldp.getDistributionPoints(); - } - catch (Exception e) - { - throw new AnnotatedException( - "Distribution points could not be read.", e); - } - for (int i = 0; i < dps.length; i++) - { - DistributionPointName dpn = dps[i].getDistributionPoint(); - // look for URIs in fullName - if (dpn != null) - { - if (dpn.getType() == DistributionPointName.FULL_NAME) - { - GeneralName[] genNames = GeneralNames.getInstance( - dpn.getName()).getNames(); - // look for an URI - for (int j = 0; j < genNames.length; j++) - { - if (genNames[j].getTagNo() == GeneralName.uniformResourceIdentifier) - { - String location = DERIA5String.getInstance( - genNames[j].getName()).getString(); - CertPathValidatorUtilities - .addAdditionalStoreFromLocation(location, - pkixParams); - } - } - } - } - } - } - } - - /** - * Add the CRL issuers from the cRLIssuer field of the distribution point or - * from the certificate if not given to the issuer criterion of the - * selector. - *

- * The issuerPrincipals are a collection with a single - * X500Principal for X509Certificates. For - * {@link X509AttributeCertificate}s the issuer may contain more than one - * X500Principal. - * - * @param dp The distribution point. - * @param issuerPrincipals The issuers of the certificate or attribute - * certificate which contains the distribution point. - * @param selector The CRL selector. - * @param pkixParams The PKIX parameters containing the cert stores. - * @throws AnnotatedException if an exception occurs while processing. - * @throws ClassCastException if issuerPrincipals does not - * contain only X500Principals. - */ - protected static void getCRLIssuersFromDistributionPoint( - DistributionPoint dp, - Collection issuerPrincipals, - X509CRLSelector selector, - ExtendedPKIXParameters pkixParams) - throws AnnotatedException - { - List issuers = new ArrayList(); - // indirect CRL - if (dp.getCRLIssuer() != null) - { - GeneralName genNames[] = dp.getCRLIssuer().getNames(); - // look for a DN - for (int j = 0; j < genNames.length; j++) - { - if (genNames[j].getTagNo() == GeneralName.directoryName) - { - try - { - issuers.add(new X500Principal(genNames[j].getName() - .toASN1Primitive().getEncoded())); - } - catch (IOException e) - { - throw new AnnotatedException( - "CRL issuer information from distribution point cannot be decoded.", - e); - } - } - } - } - else - { - /* - * certificate issuer is CRL issuer, distributionPoint field MUST be - * present. - */ - if (dp.getDistributionPoint() == null) - { - throw new AnnotatedException( - "CRL issuer is omitted from distribution point but no distributionPoint field present."); - } - // add and check issuer principals - for (Iterator it = issuerPrincipals.iterator(); it.hasNext(); ) - { - issuers.add((X500Principal)it.next()); - } - } - // TODO: is not found although this should correctly add the rel name. selector of Sun is buggy here or PKI test case is invalid - // distributionPoint -// if (dp.getDistributionPoint() != null) -// { -// // look for nameRelativeToCRLIssuer -// if (dp.getDistributionPoint().getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER) -// { -// // append fragment to issuer, only one -// // issuer can be there, if this is given -// if (issuers.size() != 1) -// { -// throw new AnnotatedException( -// "nameRelativeToCRLIssuer field is given but more than one CRL issuer is given."); -// } -// ASN1Encodable relName = dp.getDistributionPoint().getName(); -// Iterator it = issuers.iterator(); -// List issuersTemp = new ArrayList(issuers.size()); -// while (it.hasNext()) -// { -// Enumeration e = null; -// try -// { -// e = ASN1Sequence.getInstance( -// new ASN1InputStream(((X500Principal) it.next()) -// .getEncoded()).readObject()).getObjects(); -// } -// catch (IOException ex) -// { -// throw new AnnotatedException( -// "Cannot decode CRL issuer information.", ex); -// } -// ASN1EncodableVector v = new ASN1EncodableVector(); -// while (e.hasMoreElements()) -// { -// v.add((ASN1Encodable) e.nextElement()); -// } -// v.add(relName); -// issuersTemp.add(new X500Principal(new DERSequence(v) -// .getDEREncoded())); -// } -// issuers.clear(); -// issuers.addAll(issuersTemp); -// } -// } - Iterator it = issuers.iterator(); - while (it.hasNext()) - { - try - { - selector.addIssuerName(((X500Principal)it.next()).getEncoded()); - } - catch (IOException ex) - { - throw new AnnotatedException( - "Cannot decode CRL issuer information.", ex); - } - } - } - - private static BigInteger getSerialNumber( - Object cert) - { - if (cert instanceof X509Certificate) - { - return ((X509Certificate)cert).getSerialNumber(); - } - else - { - return ((X509AttributeCertificate)cert).getSerialNumber(); - } - } - - protected static void getCertStatus( - Date validDate, - X509CRL crl, - Object cert, - CertStatus certStatus) - throws AnnotatedException - { - X509CRLEntry crl_entry = null; - - boolean isIndirect; - try - { - isIndirect = X509CRLObject.isIndirectCRL(crl); - } - catch (CRLException exception) - { - throw new AnnotatedException("Failed check for indirect CRL.", exception); - } - - if (isIndirect) - { - if (!(crl instanceof X509CRLObject)) - { - try - { - crl = new X509CRLObject(CertificateList.getInstance(crl.getEncoded())); - } - catch (CRLException exception) - { - throw new AnnotatedException("Failed to recode indirect CRL.", exception); - } - } - - crl_entry = crl.getRevokedCertificate(getSerialNumber(cert)); - - if (crl_entry == null) - { - return; - } - - X500Principal certIssuer = ((X509CRLEntryObject)crl_entry).getCertificateIssuer(); - - if (certIssuer == null) - { - certIssuer = getIssuerPrincipal(crl); - } - - if (!getEncodedIssuerPrincipal(cert).equals(certIssuer)) - { - return; - } - } - else if (!getEncodedIssuerPrincipal(cert).equals(getIssuerPrincipal(crl))) - { - return; // not for our issuer, ignore - } - else - { - crl_entry = crl.getRevokedCertificate(getSerialNumber(cert)); - - if (crl_entry == null) - { - return; - } - } - - ASN1Enumerated reasonCode = null; - if (crl_entry.hasExtensions()) - { - try - { - reasonCode = ASN1Enumerated - .getInstance(CertPathValidatorUtilities - .getExtensionValue(crl_entry, - X509Extension.reasonCode.getId())); - } - catch (Exception e) - { - throw new AnnotatedException( - "Reason code CRL entry extension could not be decoded.", - e); - } - } - - // for reason keyCompromise, caCompromise, aACompromise or - // unspecified - if (!(validDate.getTime() < crl_entry.getRevocationDate().getTime()) - || reasonCode == null - || reasonCode.getValue().intValue() == 0 - || reasonCode.getValue().intValue() == 1 - || reasonCode.getValue().intValue() == 2 - || reasonCode.getValue().intValue() == 8) - { - - // (i) or (j) (1) - if (reasonCode != null) - { - certStatus.setCertStatus(reasonCode.getValue().intValue()); - } - // (i) or (j) (2) - else - { - certStatus.setCertStatus(CRLReason.unspecified); - } - certStatus.setRevocationDate(crl_entry.getRevocationDate()); - } - } - - /** - * Fetches delta CRLs according to RFC 3280 section 5.2.4. - * - * @param currentDate The date for which the delta CRLs must be valid. - * @param paramsPKIX The extended PKIX parameters. - * @param completeCRL The complete CRL the delta CRL is for. - * @return A Set of X509CRLs with delta CRLs. - * @throws AnnotatedException if an exception occurs while picking the delta - * CRLs. - */ - protected static Set getDeltaCRLs(Date currentDate, - ExtendedPKIXParameters paramsPKIX, X509CRL completeCRL) - throws AnnotatedException - { - - X509CRLStoreSelector deltaSelect = new X509CRLStoreSelector(); - - // 5.2.4 (a) - try - { - deltaSelect.addIssuerName(CertPathValidatorUtilities - .getIssuerPrincipal(completeCRL).getEncoded()); - } - catch (IOException e) - { - throw new AnnotatedException("Cannot extract issuer from CRL.", e); - } - - BigInteger completeCRLNumber = null; - try - { - ASN1Primitive derObject = CertPathValidatorUtilities.getExtensionValue(completeCRL, - CRL_NUMBER); - if (derObject != null) - { - completeCRLNumber = ASN1Integer.getInstance(derObject).getPositiveValue(); - } - } - catch (Exception e) - { - throw new AnnotatedException( - "CRL number extension could not be extracted from CRL.", e); - } - - // 5.2.4 (b) - byte[] idp = null; - try - { - idp = completeCRL.getExtensionValue(ISSUING_DISTRIBUTION_POINT); - } - catch (Exception e) - { - throw new AnnotatedException( - "Issuing distribution point extension value could not be read.", - e); - } - - // 5.2.4 (d) - - deltaSelect.setMinCRLNumber(completeCRLNumber == null ? null : completeCRLNumber - .add(BigInteger.valueOf(1))); - - deltaSelect.setIssuingDistributionPoint(idp); - deltaSelect.setIssuingDistributionPointEnabled(true); - - // 5.2.4 (c) - deltaSelect.setMaxBaseCRLNumber(completeCRLNumber); - - // find delta CRLs - Set temp = CRL_UTIL.findCRLs(deltaSelect, paramsPKIX, currentDate); - - Set result = new HashSet(); - - for (Iterator it = temp.iterator(); it.hasNext(); ) - { - X509CRL crl = (X509CRL)it.next(); - - if (isDeltaCRL(crl)) - { - result.add(crl); - } - } - - return result; - } - - private static boolean isDeltaCRL(X509CRL crl) - { - Set critical = crl.getCriticalExtensionOIDs(); - - if (critical == null) - { - return false; - } - - return critical.contains(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR); - } - - /** - * Fetches complete CRLs according to RFC 3280. - * - * @param dp The distribution point for which the complete CRL - * @param cert The X509Certificate or - * {@link org.spongycastle.x509.X509AttributeCertificate} for - * which the CRL should be searched. - * @param currentDate The date for which the delta CRLs must be valid. - * @param paramsPKIX The extended PKIX parameters. - * @return A Set of X509CRLs with complete - * CRLs. - * @throws AnnotatedException if an exception occurs while picking the CRLs - * or no CRLs are found. - */ - protected static Set getCompleteCRLs(DistributionPoint dp, Object cert, - Date currentDate, ExtendedPKIXParameters paramsPKIX) - throws AnnotatedException - { - X509CRLStoreSelector crlselect = new X509CRLStoreSelector(); - try - { - Set issuers = new HashSet(); - if (cert instanceof X509AttributeCertificate) - { - issuers.add(((X509AttributeCertificate)cert) - .getIssuer().getPrincipals()[0]); - } - else - { - issuers.add(getEncodedIssuerPrincipal(cert)); - } - CertPathValidatorUtilities.getCRLIssuersFromDistributionPoint(dp, issuers, crlselect, paramsPKIX); - } - catch (AnnotatedException e) - { - throw new AnnotatedException( - "Could not get issuer information from distribution point.", e); - } - if (cert instanceof X509Certificate) - { - crlselect.setCertificateChecking((X509Certificate)cert); - } - else if (cert instanceof X509AttributeCertificate) - { - crlselect.setAttrCertificateChecking((X509AttributeCertificate)cert); - } - - - crlselect.setCompleteCRLEnabled(true); - - Set crls = CRL_UTIL.findCRLs(crlselect, paramsPKIX, currentDate); - - if (crls.isEmpty()) - { - if (cert instanceof X509AttributeCertificate) - { - X509AttributeCertificate aCert = (X509AttributeCertificate)cert; - - throw new AnnotatedException("No CRLs found for issuer \"" + aCert.getIssuer().getPrincipals()[0] + "\""); - } - else - { - X509Certificate xCert = (X509Certificate)cert; - - throw new AnnotatedException("No CRLs found for issuer \"" + xCert.getIssuerX500Principal() + "\""); - } - } - return crls; - } - - protected static Date getValidCertDateFromValidityModel( - ExtendedPKIXParameters paramsPKIX, CertPath certPath, int index) - throws AnnotatedException - { - if (paramsPKIX.getValidityModel() == ExtendedPKIXParameters.CHAIN_VALIDITY_MODEL) - { - // if end cert use given signing/encryption/... time - if (index <= 0) - { - return CertPathValidatorUtilities.getValidDate(paramsPKIX); - // else use time when previous cert was created - } - else - { - if (index - 1 == 0) - { - ASN1GeneralizedTime dateOfCertgen = null; - try - { - byte[] extBytes = ((X509Certificate)certPath.getCertificates().get(index - 1)).getExtensionValue(ISISMTTObjectIdentifiers.id_isismtt_at_dateOfCertGen.getId()); - if (extBytes != null) - { - dateOfCertgen = ASN1GeneralizedTime.getInstance(ASN1Primitive.fromByteArray(extBytes)); - } - } - catch (IOException e) - { - throw new AnnotatedException( - "Date of cert gen extension could not be read."); - } - catch (IllegalArgumentException e) - { - throw new AnnotatedException( - "Date of cert gen extension could not be read."); - } - if (dateOfCertgen != null) - { - try - { - return dateOfCertgen.getDate(); - } - catch (ParseException e) - { - throw new AnnotatedException( - "Date from date of cert gen extension could not be parsed.", - e); - } - } - return ((X509Certificate)certPath.getCertificates().get( - index - 1)).getNotBefore(); - } - else - { - return ((X509Certificate)certPath.getCertificates().get( - index - 1)).getNotBefore(); - } - } - } - else - { - return getValidDate(paramsPKIX); - } - } - - /** - * Return the next working key inheriting DSA parameters if necessary. - *

- * This methods inherits DSA parameters from the indexed certificate or - * previous certificates in the certificate chain to the returned - * PublicKey. The list is searched upwards, meaning the end - * certificate is at position 0 and previous certificates are following. - *

- *

- * If the indexed certificate does not contain a DSA key this method simply - * returns the public key. If the DSA key already contains DSA parameters - * the key is also only returned. - *

- * - * @param certs The certification path. - * @param index The index of the certificate which contains the public key - * which should be extended with DSA parameters. - * @return The public key of the certificate in list position - * index extended with DSA parameters if applicable. - * @throws AnnotatedException if DSA parameters cannot be inherited. - */ - protected static PublicKey getNextWorkingKey(List certs, int index) - throws CertPathValidatorException - { - Certificate cert = (Certificate)certs.get(index); - PublicKey pubKey = cert.getPublicKey(); - if (!(pubKey instanceof DSAPublicKey)) - { - return pubKey; - } - DSAPublicKey dsaPubKey = (DSAPublicKey)pubKey; - if (dsaPubKey.getParams() != null) - { - return dsaPubKey; - } - for (int i = index + 1; i < certs.size(); i++) - { - X509Certificate parentCert = (X509Certificate)certs.get(i); - pubKey = parentCert.getPublicKey(); - if (!(pubKey instanceof DSAPublicKey)) - { - throw new CertPathValidatorException( - "DSA parameters cannot be inherited from previous certificate."); - } - DSAPublicKey prevDSAPubKey = (DSAPublicKey)pubKey; - if (prevDSAPubKey.getParams() == null) - { - continue; - } - DSAParams dsaParams = prevDSAPubKey.getParams(); - DSAPublicKeySpec dsaPubKeySpec = new DSAPublicKeySpec( - dsaPubKey.getY(), dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); - try - { - KeyFactory keyFactory = KeyFactory.getInstance("DSA", BouncyCastleProvider.PROVIDER_NAME); - return keyFactory.generatePublic(dsaPubKeySpec); - } - catch (Exception exception) - { - throw new RuntimeException(exception.getMessage()); - } - } - throw new CertPathValidatorException("DSA parameters cannot be inherited from previous certificate."); - } - - /** - * Find the issuer certificates of a given certificate. - * - * @param cert The certificate for which an issuer should be found. - * @param pkixParams - * @return A Collection object containing the issuer - * X509Certificates. Never null. - * @throws AnnotatedException if an error occurs. - */ - protected static Collection findIssuerCerts( - X509Certificate cert, - ExtendedPKIXBuilderParameters pkixParams) - throws AnnotatedException - { - X509CertStoreSelector certSelect = new X509CertStoreSelector(); - Set certs = new HashSet(); - try - { - certSelect.setSubject(cert.getIssuerX500Principal().getEncoded()); - } - catch (IOException ex) - { - throw new AnnotatedException( - "Subject criteria for certificate selector to find issuer certificate could not be set.", ex); - } - - Iterator iter; - - try - { - List matches = new ArrayList(); - - matches.addAll(CertPathValidatorUtilities.findCertificates(certSelect, pkixParams.getCertStores())); - matches.addAll(CertPathValidatorUtilities.findCertificates(certSelect, pkixParams.getStores())); - matches.addAll(CertPathValidatorUtilities.findCertificates(certSelect, pkixParams.getAdditionalStores())); - - iter = matches.iterator(); - } - catch (AnnotatedException e) - { - throw new AnnotatedException("Issuer certificate cannot be searched.", e); - } - - X509Certificate issuer = null; - while (iter.hasNext()) - { - issuer = (X509Certificate)iter.next(); - // issuer cannot be verified because possible DSA inheritance - // parameters are missing - certs.add(issuer); - } - return certs; - } - - protected static void verifyX509Certificate(X509Certificate cert, PublicKey publicKey, - String sigProvider) - throws GeneralSecurityException - { - if (sigProvider == null) - { - cert.verify(publicKey); - } - else - { - cert.verify(publicKey, sigProvider); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jce/provider/X509SignatureUtil.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jce/provider/X509SignatureUtil.java deleted file mode 100644 index 93cce7a49..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/jce/provider/X509SignatureUtil.java +++ /dev/null @@ -1,125 +0,0 @@ -package org.spongycastle.jce.provider; - -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.Signature; -import java.security.SignatureException; - -import org.spongycastle.asn1.ASN1Encodable; -import org.spongycastle.asn1.ASN1Null; -import org.spongycastle.asn1.DERNull; -import org.spongycastle.asn1.ASN1ObjectIdentifier; -import org.spongycastle.asn1.cryptopro.CryptoProObjectIdentifiers; -import org.spongycastle.asn1.nist.NISTObjectIdentifiers; -import org.spongycastle.asn1.oiw.OIWObjectIdentifiers; -import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers; -import org.spongycastle.asn1.pkcs.RSASSAPSSparams; -import org.spongycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; -import org.spongycastle.asn1.x509.AlgorithmIdentifier; - -class X509SignatureUtil -{ - private static final ASN1Null derNull = new DERNull(); - - static void setSignatureParameters( - Signature signature, - ASN1Encodable params) - throws NoSuchAlgorithmException, SignatureException, InvalidKeyException - { - if (params != null && !derNull.equals(params)) - { - /* - AlgorithmParameters sigParams = AlgorithmParameters.getInstance(signature.getAlgorithm(), signature.getProvider()); - - try - { - sigParams.init(params.getDERObject().getDEREncoded()); - } - catch (IOException e) - { - throw new SignatureException("IOException decoding parameters: " + e.getMessage()); - } - - try - { - signature.setParameters(sigParams.getParameterSpec(PSSParameterSpec.class)); - } - catch (GeneralSecurityException e) - { - throw new SignatureException("Exception extracting parameters: " + e.getMessage()); - } - */ - } - } - - static String getSignatureName( - AlgorithmIdentifier sigAlgId) - { - ASN1Encodable params = sigAlgId.getParameters(); - - if (params != null && !derNull.equals(params)) - { - if (sigAlgId.getObjectId().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) - { - RSASSAPSSparams rsaParams = RSASSAPSSparams.getInstance(params); - - return getDigestAlgName(rsaParams.getHashAlgorithm().getObjectId()) + "withRSAandMGF1"; - } - } - - return sigAlgId.getObjectId().getId(); - } - - /** - * Return the digest algorithm using one of the standard JCA string - * representations rather the the algorithm identifier (if possible). - */ - private static String getDigestAlgName( - ASN1ObjectIdentifier digestAlgOID) - { - if (PKCSObjectIdentifiers.md5.equals(digestAlgOID)) - { - return "MD5"; - } - else if (OIWObjectIdentifiers.idSHA1.equals(digestAlgOID)) - { - return "SHA1"; - } - else if (NISTObjectIdentifiers.id_sha224.equals(digestAlgOID)) - { - return "SHA224"; - } - else if (NISTObjectIdentifiers.id_sha256.equals(digestAlgOID)) - { - return "SHA256"; - } - else if (NISTObjectIdentifiers.id_sha384.equals(digestAlgOID)) - { - return "SHA384"; - } - else if (NISTObjectIdentifiers.id_sha512.equals(digestAlgOID)) - { - return "SHA512"; - } - else if (TeleTrusTObjectIdentifiers.ripemd128.equals(digestAlgOID)) - { - return "RIPEMD128"; - } - else if (TeleTrusTObjectIdentifiers.ripemd160.equals(digestAlgOID)) - { - return "RIPEMD160"; - } - else if (TeleTrusTObjectIdentifiers.ripemd256.equals(digestAlgOID)) - { - return "RIPEMD256"; - } - else if (CryptoProObjectIdentifiers.gostR3411.equals(digestAlgOID)) - { - return "GOST3411"; - } - else - { - return digestAlgOID.getId(); - } - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/x509/X509CRLStoreSelector.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/x509/X509CRLStoreSelector.java deleted file mode 100644 index 4748bfc51..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/x509/X509CRLStoreSelector.java +++ /dev/null @@ -1,330 +0,0 @@ -package org.spongycastle.x509; - -import org.spongycastle.asn1.ASN1Integer; -import org.spongycastle.asn1.x509.X509Extensions; -import org.spongycastle.util.Arrays; -import org.spongycastle.util.Selector; -import org.spongycastle.x509.extension.X509ExtensionUtil; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.cert.CRL; -import java.security.cert.X509CRL; -import java.security.cert.X509CRLSelector; - -/** - * This class is a Selector implementation for X.509 certificate revocation - * lists. - * - * @see org.spongycastle.util.Selector - * @see org.spongycastle.x509.X509Store - * @see org.spongycastle.jce.provider.X509StoreCRLCollection - */ -public class X509CRLStoreSelector - extends X509CRLSelector - implements Selector -{ - private boolean deltaCRLIndicator = false; - - private boolean completeCRLEnabled = false; - - private BigInteger maxBaseCRLNumber = null; - - private byte[] issuingDistributionPoint = null; - - private boolean issuingDistributionPointEnabled = false; - - private X509AttributeCertificate attrCertChecking; - - /** - * Returns if the issuing distribution point criteria should be applied. - * Defaults to false. - *

- * You may also set the issuing distribution point criteria if not a missing - * issuing distribution point should be assumed. - * - * @return Returns if the issuing distribution point check is enabled. - */ - public boolean isIssuingDistributionPointEnabled() - { - return issuingDistributionPointEnabled; - } - - /** - * Enables or disables the issuing distribution point check. - * - * @param issuingDistributionPointEnabled true to enable the - * issuing distribution point check. - */ - public void setIssuingDistributionPointEnabled( - boolean issuingDistributionPointEnabled) - { - this.issuingDistributionPointEnabled = issuingDistributionPointEnabled; - } - - /** - * Sets the attribute certificate being checked. This is not a criterion. - * Rather, it is optional information that may help a {@link X509Store} find - * CRLs that would be relevant when checking revocation for the specified - * attribute certificate. If null is specified, then no such - * optional information is provided. - * - * @param attrCert the X509AttributeCertificate being checked (or - * null) - * @see #getAttrCertificateChecking() - */ - public void setAttrCertificateChecking(X509AttributeCertificate attrCert) - { - attrCertChecking = attrCert; - } - - /** - * Returns the attribute certificate being checked. - * - * @return Returns the attribute certificate being checked. - * @see #setAttrCertificateChecking(X509AttributeCertificate) - */ - public X509AttributeCertificate getAttrCertificateChecking() - { - return attrCertChecking; - } - - public boolean match(Object obj) - { - if (!(obj instanceof X509CRL)) - { - return false; - } - X509CRL crl = (X509CRL)obj; - ASN1Integer dci = null; - try - { - byte[] bytes = crl - .getExtensionValue(X509Extensions.DeltaCRLIndicator.getId()); - if (bytes != null) - { - dci = ASN1Integer.getInstance(X509ExtensionUtil - .fromExtensionValue(bytes)); - } - } - catch (Exception e) - { - return false; - } - if (isDeltaCRLIndicatorEnabled()) - { - if (dci == null) - { - return false; - } - } - if (isCompleteCRLEnabled()) - { - if (dci != null) - { - return false; - } - } - if (dci != null) - { - - if (maxBaseCRLNumber != null) - { - if (dci.getPositiveValue().compareTo(maxBaseCRLNumber) == 1) - { - return false; - } - } - } - if (issuingDistributionPointEnabled) - { - byte[] idp = crl - .getExtensionValue(X509Extensions.IssuingDistributionPoint - .getId()); - if (issuingDistributionPoint == null) - { - if (idp != null) - { - return false; - } - } - else - { - if (!Arrays.areEqual(idp, issuingDistributionPoint)) - { - return false; - } - } - - } - return super.match((X509CRL)obj); - } - - public boolean match(CRL crl) - { - return match((Object)crl); - } - - /** - * Returns if this selector must match CRLs with the delta CRL indicator - * extension set. Defaults to false. - * - * @return Returns true if only CRLs with the delta CRL - * indicator extension are selected. - */ - public boolean isDeltaCRLIndicatorEnabled() - { - return deltaCRLIndicator; - } - - /** - * If this is set to true the CRL reported contains the delta - * CRL indicator CRL extension. - *

- * {@link #setCompleteCRLEnabled(boolean)} and - * {@link #setDeltaCRLIndicatorEnabled(boolean)} excluded each other. - * - * @param deltaCRLIndicator true if the delta CRL indicator - * extension must be in the CRL. - */ - public void setDeltaCRLIndicatorEnabled(boolean deltaCRLIndicator) - { - this.deltaCRLIndicator = deltaCRLIndicator; - } - - /** - * Returns an instance of this from a X509CRLSelector. - * - * @param selector A X509CRLSelector instance. - * @return An instance of an X509CRLStoreSelector. - * @exception IllegalArgumentException if selector is null or creation - * fails. - */ - public static X509CRLStoreSelector getInstance(X509CRLSelector selector) - { - if (selector == null) - { - throw new IllegalArgumentException( - "cannot create from null selector"); - } - X509CRLStoreSelector cs = new X509CRLStoreSelector(); - cs.setCertificateChecking(selector.getCertificateChecking()); - cs.setDateAndTime(selector.getDateAndTime()); - try - { - cs.setIssuerNames(selector.getIssuerNames()); - } - catch (IOException e) - { - // cannot happen - throw new IllegalArgumentException(e.getMessage()); - } - //cs.setIssuers(selector.getIssuers()); - cs.setMaxCRLNumber(selector.getMaxCRL()); - cs.setMinCRLNumber(selector.getMinCRL()); - return cs; - } - - public Object clone() - { - X509CRLStoreSelector sel = X509CRLStoreSelector.getInstance(this); - sel.deltaCRLIndicator = deltaCRLIndicator; - sel.completeCRLEnabled = completeCRLEnabled; - sel.maxBaseCRLNumber = maxBaseCRLNumber; - sel.attrCertChecking = attrCertChecking; - sel.issuingDistributionPointEnabled = issuingDistributionPointEnabled; - sel.issuingDistributionPoint = Arrays.clone(issuingDistributionPoint); - return sel; - } - - /** - * If true only complete CRLs are returned. Defaults to - * false. - * - * @return true if only complete CRLs are returned. - */ - public boolean isCompleteCRLEnabled() - { - return completeCRLEnabled; - } - - /** - * If set to true only complete CRLs are returned. - *

- * {@link #setCompleteCRLEnabled(boolean)} and - * {@link #setDeltaCRLIndicatorEnabled(boolean)} excluded each other. - * - * @param completeCRLEnabled true if only complete CRLs - * should be returned. - */ - public void setCompleteCRLEnabled(boolean completeCRLEnabled) - { - this.completeCRLEnabled = completeCRLEnabled; - } - - /** - * Get the maximum base CRL number. Defaults to null. - * - * @return Returns the maximum base CRL number. - * @see #setMaxBaseCRLNumber(BigInteger) - */ - public BigInteger getMaxBaseCRLNumber() - { - return maxBaseCRLNumber; - } - - /** - * Sets the maximum base CRL number. Setting to null disables - * this cheack. - *

- * This is only meaningful for delta CRLs. Complete CRLs must have a CRL - * number which is greater or equal than the base number of the - * corresponding CRL. - * - * @param maxBaseCRLNumber The maximum base CRL number to set. - */ - public void setMaxBaseCRLNumber(BigInteger maxBaseCRLNumber) - { - this.maxBaseCRLNumber = maxBaseCRLNumber; - } - - /** - * Returns the issuing distribution point. Defaults to null, - * which is a missing issuing distribution point extension. - *

- * The internal byte array is cloned before it is returned. - *

- * The criteria must be enable with - * {@link #setIssuingDistributionPointEnabled(boolean)}. - * - * @return Returns the issuing distribution point. - * @see #setIssuingDistributionPoint(byte[]) - */ - public byte[] getIssuingDistributionPoint() - { - return Arrays.clone(issuingDistributionPoint); - } - - /** - * Sets the issuing distribution point. - *

- * The issuing distribution point extension is a CRL extension which - * identifies the scope and the distribution point of a CRL. The scope - * contains among others information about revocation reasons contained in - * the CRL. Delta CRLs and complete CRLs must have matching issuing - * distribution points. - *

- * The byte array is cloned to protect against subsequent modifications. - *

- * You must also enable or disable this criteria with - * {@link #setIssuingDistributionPointEnabled(boolean)}. - * - * @param issuingDistributionPoint The issuing distribution point to set. - * This is the DER encoded OCTET STRING extension value. - * @see #getIssuingDistributionPoint() - */ - public void setIssuingDistributionPoint(byte[] issuingDistributionPoint) - { - this.issuingDistributionPoint = Arrays.clone(issuingDistributionPoint); - } -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/x509/X509CertStoreSelector.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/x509/X509CertStoreSelector.java deleted file mode 100644 index 61664c449..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/x509/X509CertStoreSelector.java +++ /dev/null @@ -1,86 +0,0 @@ -package org.spongycastle.x509; - -import org.spongycastle.util.Selector; - -import java.io.IOException; -import java.security.cert.Certificate; -import java.security.cert.X509CertSelector; -import java.security.cert.X509Certificate; - -/** - * This class is a Selector implementation for X.509 certificates. - * - * @see org.spongycastle.util.Selector - * @see org.spongycastle.x509.X509Store - * @see org.spongycastle.jce.provider.X509StoreCertCollection - */ -public class X509CertStoreSelector - extends X509CertSelector - implements Selector -{ - public boolean match(Object obj) - { - if (!(obj instanceof X509Certificate)) - { - return false; - } - - X509Certificate other = (X509Certificate)obj; - - return super.match(other); - } - - public boolean match(Certificate cert) - { - return match((Object)cert); - } - - public Object clone() - { - X509CertStoreSelector selector = (X509CertStoreSelector)super.clone(); - - return selector; - } - - /** - * Returns an instance of this from a X509CertSelector. - * - * @param selector A X509CertSelector instance. - * @return An instance of an X509CertStoreSelector. - * @exception IllegalArgumentException if selector is null or creation fails. - */ - public static X509CertStoreSelector getInstance(X509CertSelector selector) - { - if (selector == null) - { - throw new IllegalArgumentException("cannot create from null selector"); - } - X509CertStoreSelector cs = new X509CertStoreSelector(); - cs.setAuthorityKeyIdentifier(selector.getAuthorityKeyIdentifier()); - cs.setBasicConstraints(selector.getBasicConstraints()); - cs.setCertificate(selector.getCertificate()); - cs.setCertificateValid(selector.getCertificateValid()); - cs.setMatchAllSubjectAltNames(selector.getMatchAllSubjectAltNames()); - try - { - cs.setPathToNames(selector.getPathToNames()); - cs.setExtendedKeyUsage(selector.getExtendedKeyUsage()); - cs.setNameConstraints(selector.getNameConstraints()); - cs.setPolicy(selector.getPolicy()); - cs.setSubjectPublicKeyAlgID(selector.getSubjectPublicKeyAlgID()); - cs.setIssuer(selector.getIssuerAsBytes()); - cs.setSubject(selector.getSubjectAsBytes()); - } - catch (IOException e) - { - throw new IllegalArgumentException("error in passed in selector: " + e); - } - cs.setKeyUsage(selector.getKeyUsage()); - cs.setPrivateKeyValid(selector.getPrivateKeyValid()); - cs.setSerialNumber(selector.getSerialNumber()); - cs.setSubjectKeyIdentifier(selector.getSubjectKeyIdentifier()); - cs.setSubjectPublicKey(selector.getSubjectPublicKey()); - return cs; - } - -} diff --git a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/x509/util/LDAPStoreHelper.java b/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/x509/util/LDAPStoreHelper.java deleted file mode 100644 index b78c4a765..000000000 --- a/extern/spongycastle/prov/src/main/jdk1.4/org/spongycastle/x509/util/LDAPStoreHelper.java +++ /dev/null @@ -1,1118 +0,0 @@ -package org.spongycastle.x509.util; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.security.Principal; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.sql.Date; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import javax.naming.Context; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.Attribute; -import javax.naming.directory.DirContext; -import javax.naming.directory.InitialDirContext; -import javax.naming.directory.SearchControls; -import javax.naming.directory.SearchResult; -import javax.security.auth.x500.X500Principal; - -import org.spongycastle.asn1.ASN1InputStream; -import org.spongycastle.asn1.x509.Certificate; -import org.spongycastle.asn1.x509.CertificatePair; -import org.spongycastle.jce.X509LDAPCertStoreParameters; -import org.spongycastle.jce.provider.X509AttrCertParser; -import org.spongycastle.jce.provider.X509CRLParser; -import org.spongycastle.jce.provider.X509CertPairParser; -import org.spongycastle.jce.provider.X509CertParser; -import org.spongycastle.util.StoreException; -import org.spongycastle.x509.X509AttributeCertStoreSelector; -import org.spongycastle.x509.X509AttributeCertificate; -import org.spongycastle.x509.X509CRLStoreSelector; -import org.spongycastle.x509.X509CertPairStoreSelector; -import org.spongycastle.x509.X509CertStoreSelector; -import org.spongycastle.x509.X509CertificatePair; - -/** - * This is a general purpose implementation to get X.509 certificates, CRLs, - * attribute certificates and cross certificates from a LDAP location. - *

- * At first a search is performed in the ldap*AttributeNames of the - * {@link org.spongycastle.jce.X509LDAPCertStoreParameters} with the given - * information of the subject (for all kind of certificates) or issuer (for - * CRLs), respectively, if a {@link org.spongycastle.x509.X509CertStoreSelector} or - * {@link org.spongycastle.x509.X509AttributeCertificate} is given with that - * details. - *

- * For the used schemes see: - *

- */ -public class LDAPStoreHelper -{ - - // TODO: cache results - - private X509LDAPCertStoreParameters params; - - public LDAPStoreHelper(X509LDAPCertStoreParameters params) - { - this.params = params; - } - - /** - * Initial Context Factory. - */ - private static String LDAP_PROVIDER = "com.sun.jndi.ldap.LdapCtxFactory"; - - /** - * Processing referrals.. - */ - private static String REFERRALS_IGNORE = "ignore"; - - /** - * Security level to be used for LDAP connections. - */ - private static final String SEARCH_SECURITY_LEVEL = "none"; - - /** - * Package Prefix for loading URL context factories. - */ - private static final String URL_CONTEXT_PREFIX = "com.sun.jndi.url"; - - private DirContext connectLDAP() throws NamingException - { - Properties props = new Properties(); - props.setProperty(Context.INITIAL_CONTEXT_FACTORY, LDAP_PROVIDER); - props.setProperty(Context.BATCHSIZE, "0"); - - props.setProperty(Context.PROVIDER_URL, params.getLdapURL()); - props.setProperty(Context.URL_PKG_PREFIXES, URL_CONTEXT_PREFIX); - props.setProperty(Context.REFERRAL, REFERRALS_IGNORE); - props.setProperty(Context.SECURITY_AUTHENTICATION, - SEARCH_SECURITY_LEVEL); - - DirContext ctx = new InitialDirContext(props); - return ctx; - } - - private String parseDN(String subject, String dNAttributeName) - { - String temp = subject; - int begin = temp.toLowerCase().indexOf( - dNAttributeName.toLowerCase() + "="); - if (begin == -1) - { - return ""; - } - temp = temp.substring(begin + dNAttributeName.length()); - int end = temp.indexOf(','); - if (end == -1) - { - end = temp.length(); - } - while (temp.charAt(end - 1) == '\\') - { - end = temp.indexOf(',', end + 1); - if (end == -1) - { - end = temp.length(); - } - } - temp = temp.substring(0, end); - begin = temp.indexOf('='); - temp = temp.substring(begin + 1); - if (temp.charAt(0) == ' ') - { - temp = temp.substring(1); - } - if (temp.startsWith("\"")) - { - temp = temp.substring(1); - } - if (temp.endsWith("\"")) - { - temp = temp.substring(0, temp.length() - 1); - } - return temp; - } - - private Set createCerts(List list, X509CertStoreSelector xselector) - throws StoreException - { - Set certSet = new HashSet(); - - Iterator it = list.iterator(); - X509CertParser parser = new X509CertParser(); - while (it.hasNext()) - { - try - { - parser.engineInit(new ByteArrayInputStream((byte[])it - .next())); - X509Certificate cert = (X509Certificate)parser - .engineRead(); - if (xselector.match((Object)cert)) - { - certSet.add(cert); - } - - } - catch (Exception e) - { - - } - } - - return certSet; - } - - /** - * Can use the subject and serial and the subject and serialNumber of the - * certificate of the given of the X509CertStoreSelector. If a certificate - * for checking is given this has higher precedence. - * - * @param xselector The selector with the search criteria. - * @param attrs Attributes which contain the certificates in the LDAP - * directory. - * @param attrNames Attribute names in teh LDAP directory which correspond to the - * subjectAttributeNames. - * @param subjectAttributeNames Subject attribute names (like "CN", "O", "OU") to use to - * search in the LDAP directory - * @return A list of found DER encoded certificates. - * @throws StoreException if an error occurs while searching. - */ - private List certSubjectSerialSearch(X509CertStoreSelector xselector, - String[] attrs, String attrNames[], String subjectAttributeNames[]) - throws StoreException - { - // TODO: support also subjectAltNames? - List list = new ArrayList(); - - String subject = null; - String serial = null; - - subject = getSubjectAsString(xselector); - - if (xselector.getSerialNumber() != null) - { - serial = xselector.getSerialNumber().toString(); - } - if (xselector.getCertificate() != null) - { - subject = xselector.getCertificate().getSubjectX500Principal().getName("RFC1779"); - serial = xselector.getCertificate().getSerialNumber().toString(); - } - - String attrValue = null; - if (subject != null) - { - for (int i = 0; i < subjectAttributeNames.length; i++) - { - attrValue = parseDN(subject, subjectAttributeNames[i]); - list - .addAll(search(attrNames, "*" + attrValue + "*", - attrs)); - } - } - if (serial != null && params.getSearchForSerialNumberIn() != null) - { - attrValue = serial; - list.addAll(search( - splitString(params.getSearchForSerialNumberIn()), - attrValue, attrs)); - } - if (serial == null && subject == null) - { - list.addAll(search(attrNames, "*", attrs)); - } - - return list; - } - - - - /** - * Can use the subject of the forward certificate of the set certificate - * pair or the subject of the forward - * {@link org.spongycastle.x509.X509CertStoreSelector} of the given - * selector. - * - * @param xselector The selector with the search criteria. - * @param attrs Attributes which contain the attribute certificates in the - * LDAP directory. - * @param attrNames Attribute names in the LDAP directory which correspond to the - * subjectAttributeNames. - * @param subjectAttributeNames Subject attribute names (like "CN", "O", "OU") to use to - * search in the LDAP directory - * @return A list of found DER encoded certificate pairs. - * @throws StoreException if an error occurs while searching. - */ - private List crossCertificatePairSubjectSearch( - X509CertPairStoreSelector xselector, String[] attrs, - String attrNames[], String subjectAttributeNames[]) - throws StoreException - { - List list = new ArrayList(); - - // search for subject - String subject = null; - - if (xselector.getForwardSelector() != null) - { - subject = getSubjectAsString(xselector.getForwardSelector()); - } - if (xselector.getCertPair() != null) - { - if (xselector.getCertPair().getForward() != null) - { - subject = xselector.getCertPair().getForward() - .getSubjectX500Principal().getName("RFC1779"); - } - } - String attrValue = null; - if (subject != null) - { - for (int i = 0; i < subjectAttributeNames.length; i++) - { - attrValue = parseDN(subject, subjectAttributeNames[i]); - list - .addAll(search(attrNames, "*" + attrValue + "*", - attrs)); - } - } - if (subject == null) - { - list.addAll(search(attrNames, "*", attrs)); - } - - return list; - } - - /** - * Can use the entityName of the holder of the attribute certificate, the - * serialNumber of attribute certificate and the serialNumber of the - * associated certificate of the given of the X509AttributeCertSelector. - * - * @param xselector The selector with the search criteria. - * @param attrs Attributes which contain the attribute certificates in the - * LDAP directory. - * @param attrNames Attribute names in the LDAP directory which correspond to the - * subjectAttributeNames. - * @param subjectAttributeNames Subject attribute names (like "CN", "O", "OU") to use to - * search in the LDAP directory - * @return A list of found DER encoded attribute certificates. - * @throws StoreException if an error occurs while searching. - */ - private List attrCertSubjectSerialSearch( - X509AttributeCertStoreSelector xselector, String[] attrs, - String attrNames[], String subjectAttributeNames[]) - throws StoreException - { - List list = new ArrayList(); - - // search for serialNumber of associated cert, - // serialNumber of the attribute certificate or DN in the entityName - // of the holder - - String subject = null; - String serial = null; - - Collection serials = new HashSet(); - Principal principals[] = null; - if (xselector.getHolder() != null) - { - // serialNumber of associated cert - if (xselector.getHolder().getSerialNumber() != null) - { - serials.add(xselector.getHolder().getSerialNumber() - .toString()); - } - // DN in the entityName of the holder - if (xselector.getHolder().getEntityNames() != null) - { - principals = xselector.getHolder().getEntityNames(); - } - } - - if (xselector.getAttributeCert() != null) - { - if (xselector.getAttributeCert().getHolder().getEntityNames() != null) - { - principals = xselector.getAttributeCert().getHolder() - .getEntityNames(); - } - // serialNumber of the attribute certificate - serials.add(xselector.getAttributeCert().getSerialNumber() - .toString()); - } - if (principals != null) - { - // only first should be relevant - if (principals[0] instanceof X500Principal) - { - subject = ((X500Principal)principals[0]) - .getName("RFC1779"); - } - else - { - // strange ... - subject = principals[0].getName(); - } - } - if (xselector.getSerialNumber() != null) - { - serials.add(xselector.getSerialNumber().toString()); - } - - String attrValue = null; - if (subject != null) - { - for (int i = 0; i < subjectAttributeNames.length; i++) - { - attrValue = parseDN(subject, subjectAttributeNames[i]); - list - .addAll(search(attrNames, "*" + attrValue + "*", - attrs)); - } - } - if (serials.size() > 0 - && params.getSearchForSerialNumberIn() != null) - { - Iterator it = serials.iterator(); - while (it.hasNext()) - { - serial = (String)it.next(); - list.addAll(search(splitString(params.getSearchForSerialNumberIn()), serial, attrs)); - } - } - if (serials.size() == 0 && subject == null) - { - list.addAll(search(attrNames, "*", attrs)); - } - - return list; - } - - /** - * Can use the issuer of the given of the X509CRLStoreSelector. - * - * @param xselector The selector with the search criteria. - * @param attrs Attributes which contain the attribute certificates in the - * LDAP directory. - * @param attrNames Attribute names in the LDAP directory which correspond to the - * subjectAttributeNames. - * @param issuerAttributeNames Issuer attribute names (like "CN", "O", "OU") to use to search - * in the LDAP directory - * @return A list of found DER encoded CRLs. - * @throws StoreException if an error occurs while searching. - */ - private List cRLIssuerSearch(X509CRLStoreSelector xselector, - String[] attrs, String attrNames[], String issuerAttributeNames[]) - throws StoreException - { - List list = new ArrayList(); - - String issuer = null; - Collection issuers = new HashSet(); -/* - if (xselector.getIssuers() != null) - { - issuers.addAll(xselector.getIssuers()); - } -*/ - if (xselector.getCertificateChecking() != null) - { - issuers.add(getCertificateIssuer(xselector.getCertificateChecking())); - } - if (xselector.getAttrCertificateChecking() != null) - { - Principal principals[] = xselector.getAttrCertificateChecking().getIssuer().getPrincipals(); - for (int i=0; iList of encodings of the certificates, attribute - * certificates, CRL or certificate pairs. - * - * @param attributeNames The attribute names to look for in the LDAP. - * @param attributeValue The value the attribute name must have. - * @param attrs The attributes in the LDAP which hold the certificate, - * attribute certificate, certificate pair or CRL in a found - * entry. - * @return A List of byte arrays with the encodings. - * @throws StoreException if an error occurs getting the results from the LDAP - * directory. - */ - private List search(String attributeNames[], String attributeValue, - String[] attrs) throws StoreException - { - String filter = null; - if (attributeNames == null) - { - filter = null; - } - else - { - filter = ""; - if (attributeValue.equals("**")) - { - attributeValue = "*"; - } - for (int i = 0; i < attributeNames.length; i++) - { - filter += "(" + attributeNames[i] + "=" + attributeValue + ")"; - } - filter = "(|" + filter + ")"; - } - String filter2 = ""; - for (int i = 0; i < attrs.length; i++) - { - filter2 += "(" + attrs[i] + "=*)"; - } - filter2 = "(|" + filter2 + ")"; - - String filter3 = "(&" + filter + "" + filter2 + ")"; - if (filter == null) - { - filter3 = filter2; - } - List list; - list = getFromCache(filter3); - if (list != null) - { - return list; - } - DirContext ctx = null; - list = new ArrayList(); - try - { - - ctx = connectLDAP(); - - SearchControls constraints = new SearchControls(); - constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); - constraints.setCountLimit(0); - constraints.setReturningAttributes(attrs); - NamingEnumeration results = ctx.search(params.getBaseDN(), filter3, - constraints); - while (results.hasMoreElements()) - { - SearchResult sr = (SearchResult)results.next(); - NamingEnumeration enumeration = ((Attribute)(sr - .getAttributes().getAll().next())).getAll(); - while (enumeration.hasMore()) - { - list.add(enumeration.next()); - } - } - addToCache(filter3, list); - } - catch (NamingException e) - { - // skip exception, unfortunately if an attribute type is not - // supported an exception is thrown - - } - finally - { - try - { - if (null != ctx) - { - ctx.close(); - } - } - catch (Exception e) - { - } - } - return list; - } - - private Set createCRLs(List list, X509CRLStoreSelector xselector) - throws StoreException - { - Set crlSet = new HashSet(); - - X509CRLParser parser = new X509CRLParser(); - Iterator it = list.iterator(); - while (it.hasNext()) - { - try - { - parser.engineInit(new ByteArrayInputStream((byte[])it - .next())); - X509CRL crl = (X509CRL)parser.engineRead(); - if (xselector.match((Object)crl)) - { - crlSet.add(crl); - } - } - catch (StreamParsingException e) - { - - } - } - - return crlSet; - } - - private Set createCrossCertificatePairs(List list, - X509CertPairStoreSelector xselector) throws StoreException - { - Set certPairSet = new HashSet(); - - int i = 0; - while (i < list.size()) - { - X509CertificatePair pair; - try - { - // first try to decode it as certificate pair - try - { - X509CertPairParser parser = new X509CertPairParser(); - parser.engineInit(new ByteArrayInputStream( - (byte[])list.get(i))); - pair = (X509CertificatePair)parser.engineRead(); - } - catch (StreamParsingException e) - { - // now try it to construct it the forward and reverse - // certificate - byte[] forward = (byte[])list.get(i); - byte[] reverse = (byte[])list.get(i + 1); - pair = new X509CertificatePair(new CertificatePair( - Certificate - .getInstance(new ASN1InputStream( - forward).readObject()), - Certificate - .getInstance(new ASN1InputStream( - reverse).readObject()))); - i++; - } - if (xselector.match((Object)pair)) - { - certPairSet.add(pair); - } - } - catch (CertificateParsingException e) - { - // try next - } - catch (IOException e) - { - // try next - } - i++; - } - - return certPairSet; - } - - private Set createAttributeCertificates(List list, - X509AttributeCertStoreSelector xselector) throws StoreException - { - Set certSet = new HashSet(); - - Iterator it = list.iterator(); - X509AttrCertParser parser = new X509AttrCertParser(); - while (it.hasNext()) - { - try - { - parser.engineInit(new ByteArrayInputStream((byte[])it - .next())); - X509AttributeCertificate cert = (X509AttributeCertificate)parser - .engineRead(); - if (xselector.match((Object)cert)) - { - certSet.add(cert); - } - } - catch (StreamParsingException e) - { - - } - } - - return certSet; - } - - /** - * Returns the CRLs for issued certificates for other CAs matching the given - * selector.
- * The authorityRevocationList attribute includes revocation information - * regarding certificates issued to other CAs. - * - * @param selector The CRL selector to use to find the CRLs. - * @return A possible empty collection with CRLs - * @throws StoreException - */ - public Collection getAuthorityRevocationLists(X509CRLStoreSelector selector) - throws StoreException - { - String[] attrs = splitString(params.getAuthorityRevocationListAttribute()); - String attrNames[] = splitString(params - .getLdapAuthorityRevocationListAttributeName()); - String issuerAttributeNames[] = splitString(params - .getAuthorityRevocationListIssuerAttributeName()); - - List list = cRLIssuerSearch(selector, attrs, attrNames, - issuerAttributeNames); - Set resultSet = createCRLs(list, selector); - if (resultSet.size() == 0) - { - X509CRLStoreSelector emptySelector = new X509CRLStoreSelector(); - list = cRLIssuerSearch(emptySelector, attrs, attrNames, - issuerAttributeNames); - - resultSet.addAll(createCRLs(list, selector)); - } - return resultSet; - } - - /** - * Returns the revocation list for revoked attribute certificates. - *

- * The attributeCertificateRevocationList holds a list of attribute - * certificates that have been revoked. - * - * @param selector The CRL selector to use to find the CRLs. - * @return A possible empty collection with CRLs. - * @throws StoreException - */ - public Collection getAttributeCertificateRevocationLists( - X509CRLStoreSelector selector) throws StoreException - { - String[] attrs = splitString(params - .getAttributeCertificateRevocationListAttribute()); - String attrNames[] = splitString(params - .getLdapAttributeCertificateRevocationListAttributeName()); - String issuerAttributeNames[] = splitString(params - .getAttributeCertificateRevocationListIssuerAttributeName()); - - List list = cRLIssuerSearch(selector, attrs, attrNames, - issuerAttributeNames); - Set resultSet = createCRLs(list, selector); - if (resultSet.size() == 0) - { - X509CRLStoreSelector emptySelector = new X509CRLStoreSelector(); - list = cRLIssuerSearch(emptySelector, attrs, attrNames, - issuerAttributeNames); - - resultSet.addAll(createCRLs(list, selector)); - } - return resultSet; - } - - /** - * Returns the revocation list for revoked attribute certificates for an - * attribute authority - *

- * The attributeAuthorityList holds a list of AA certificates that have been - * revoked. - * - * @param selector The CRL selector to use to find the CRLs. - * @return A possible empty collection with CRLs - * @throws StoreException - */ - public Collection getAttributeAuthorityRevocationLists( - X509CRLStoreSelector selector) throws StoreException - { - String[] attrs = splitString(params.getAttributeAuthorityRevocationListAttribute()); - String attrNames[] = splitString(params - .getLdapAttributeAuthorityRevocationListAttributeName()); - String issuerAttributeNames[] = splitString(params - .getAttributeAuthorityRevocationListIssuerAttributeName()); - - List list = cRLIssuerSearch(selector, attrs, attrNames, - issuerAttributeNames); - Set resultSet = createCRLs(list, selector); - if (resultSet.size() == 0) - { - X509CRLStoreSelector emptySelector = new X509CRLStoreSelector(); - list = cRLIssuerSearch(emptySelector, attrs, attrNames, - issuerAttributeNames); - - resultSet.addAll(createCRLs(list, selector)); - } - return resultSet; - } - - /** - * Returns cross certificate pairs. - * - * @param selector The selector to use to find the cross certificates. - * @return A possible empty collection with {@link X509CertificatePair}s - * @throws StoreException - */ - public Collection getCrossCertificatePairs( - X509CertPairStoreSelector selector) throws StoreException - { - String[] attrs = splitString(params.getCrossCertificateAttribute()); - String attrNames[] = splitString(params.getLdapCrossCertificateAttributeName()); - String subjectAttributeNames[] = splitString(params - .getCrossCertificateSubjectAttributeName()); - List list = crossCertificatePairSubjectSearch(selector, attrs, - attrNames, subjectAttributeNames); - Set resultSet = createCrossCertificatePairs(list, selector); - if (resultSet.size() == 0) - { - X509CertStoreSelector emptyCertselector = new X509CertStoreSelector(); - X509CertPairStoreSelector emptySelector = new X509CertPairStoreSelector(); - - emptySelector.setForwardSelector(emptyCertselector); - emptySelector.setReverseSelector(emptyCertselector); - list = crossCertificatePairSubjectSearch(emptySelector, attrs, - attrNames, subjectAttributeNames); - resultSet.addAll(createCrossCertificatePairs(list, selector)); - } - return resultSet; - } - - /** - * Returns end certificates. - *

- * The attributeDescriptorCertificate is self signed by a source of - * authority and holds a description of the privilege and its delegation - * rules. - * - * @param selector The selector to find the certificates. - * @return A possible empty collection with certificates. - * @throws StoreException - */ - public Collection getUserCertificates(X509CertStoreSelector selector) - throws StoreException - { - String[] attrs = splitString(params.getUserCertificateAttribute()); - String attrNames[] = splitString(params.getLdapUserCertificateAttributeName()); - String subjectAttributeNames[] = splitString(params - .getUserCertificateSubjectAttributeName()); - - List list = certSubjectSerialSearch(selector, attrs, attrNames, - subjectAttributeNames); - Set resultSet = createCerts(list, selector); - if (resultSet.size() == 0) - { - X509CertStoreSelector emptySelector = new X509CertStoreSelector(); - list = certSubjectSerialSearch(emptySelector, attrs, attrNames, - subjectAttributeNames); - resultSet.addAll(createCerts(list, selector)); - } - - return resultSet; - } - - /** - * Returns attribute certificates for an attribute authority - *

- * The aAcertificate holds the privileges of an attribute authority. - * - * @param selector The selector to find the attribute certificates. - * @return A possible empty collection with attribute certificates. - * @throws StoreException - */ - public Collection getAACertificates(X509AttributeCertStoreSelector selector) - throws StoreException - { - String[] attrs = splitString(params.getAACertificateAttribute()); - String attrNames[] = splitString(params.getLdapAACertificateAttributeName()); - String subjectAttributeNames[] = splitString(params.getAACertificateSubjectAttributeName()); - - List list = attrCertSubjectSerialSearch(selector, attrs, attrNames, - subjectAttributeNames); - Set resultSet = createAttributeCertificates(list, selector); - if (resultSet.size() == 0) - { - X509AttributeCertStoreSelector emptySelector = new X509AttributeCertStoreSelector(); - list = attrCertSubjectSerialSearch(emptySelector, attrs, attrNames, - subjectAttributeNames); - resultSet.addAll(createAttributeCertificates(list, selector)); - } - - return resultSet; - } - - /** - * Returns an attribute certificate for an authority - *

- * The attributeDescriptorCertificate is self signed by a source of - * authority and holds a description of the privilege and its delegation - * rules. - * - * @param selector The selector to find the attribute certificates. - * @return A possible empty collection with attribute certificates. - * @throws StoreException - */ - public Collection getAttributeDescriptorCertificates( - X509AttributeCertStoreSelector selector) throws StoreException - { - String[] attrs = splitString(params.getAttributeDescriptorCertificateAttribute()); - String attrNames[] = splitString(params - .getLdapAttributeDescriptorCertificateAttributeName()); - String subjectAttributeNames[] = splitString(params - .getAttributeDescriptorCertificateSubjectAttributeName()); - - List list = attrCertSubjectSerialSearch(selector, attrs, attrNames, - subjectAttributeNames); - Set resultSet = createAttributeCertificates(list, selector); - if (resultSet.size() == 0) - { - X509AttributeCertStoreSelector emptySelector = new X509AttributeCertStoreSelector(); - list = attrCertSubjectSerialSearch(emptySelector, attrs, attrNames, - subjectAttributeNames); - resultSet.addAll(createAttributeCertificates(list, selector)); - } - - return resultSet; - } - - /** - * Returns CA certificates. - *

- * The cACertificate attribute of a CA's directory entry shall be used to - * store self-issued certificates (if any) and certificates issued to this - * CA by CAs in the same realm as this CA. - * - * @param selector The selector to find the certificates. - * @return A possible empty collection with certificates. - * @throws StoreException - */ - public Collection getCACertificates(X509CertStoreSelector selector) - throws StoreException - { - String[] attrs = splitString(params.getCACertificateAttribute()); - String attrNames[] = splitString(params.getLdapCACertificateAttributeName()); - String subjectAttributeNames[] = splitString(params - .getCACertificateSubjectAttributeName()); - List list = certSubjectSerialSearch(selector, attrs, attrNames, - subjectAttributeNames); - Set resultSet = createCerts(list, selector); - if (resultSet.size() == 0) - { - X509CertStoreSelector emptySelector = new X509CertStoreSelector(); - list = certSubjectSerialSearch(emptySelector, attrs, attrNames, - subjectAttributeNames); - resultSet.addAll(createCerts(list, selector)); - } - return resultSet; - } - - /** - * Returns the delta revocation list for revoked certificates. - * - * @param selector The CRL selector to use to find the CRLs. - * @return A possible empty collection with CRLs. - * @throws StoreException - */ - public Collection getDeltaCertificateRevocationLists( - X509CRLStoreSelector selector) throws StoreException - { - String[] attrs = splitString(params.getDeltaRevocationListAttribute()); - String attrNames[] = splitString(params.getLdapDeltaRevocationListAttributeName()); - String issuerAttributeNames[] = splitString(params - .getDeltaRevocationListIssuerAttributeName()); - List list = cRLIssuerSearch(selector, attrs, attrNames, - issuerAttributeNames); - Set resultSet = createCRLs(list, selector); - if (resultSet.size() == 0) - { - X509CRLStoreSelector emptySelector = new X509CRLStoreSelector(); - list = cRLIssuerSearch(emptySelector, attrs, attrNames, - issuerAttributeNames); - - resultSet.addAll(createCRLs(list, selector)); - } - return resultSet; - } - - /** - * Returns an attribute certificate for an user. - *

- * The attributeCertificateAttribute holds the privileges of a user - * - * @param selector The selector to find the attribute certificates. - * @return A possible empty collection with attribute certificates. - * @throws StoreException - */ - public Collection getAttributeCertificateAttributes( - X509AttributeCertStoreSelector selector) throws StoreException - { - String[] attrs = splitString(params.getAttributeCertificateAttributeAttribute()); - String attrNames[] = splitString(params - .getLdapAttributeCertificateAttributeAttributeName()); - String subjectAttributeNames[] = splitString(params - .getAttributeCertificateAttributeSubjectAttributeName()); - List list = attrCertSubjectSerialSearch(selector, attrs, attrNames, - subjectAttributeNames); - Set resultSet = createAttributeCertificates(list, selector); - if (resultSet.size() == 0) - { - X509AttributeCertStoreSelector emptySelector = new X509AttributeCertStoreSelector(); - list = attrCertSubjectSerialSearch(emptySelector, attrs, attrNames, - subjectAttributeNames); - resultSet.addAll(createAttributeCertificates(list, selector)); - } - - return resultSet; - } - - /** - * Returns the certificate revocation lists for revoked certificates. - * - * @param selector The CRL selector to use to find the CRLs. - * @return A possible empty collection with CRLs. - * @throws StoreException - */ - public Collection getCertificateRevocationLists( - X509CRLStoreSelector selector) throws StoreException - { - String[] attrs = splitString(params.getCertificateRevocationListAttribute()); - String attrNames[] = splitString(params - .getLdapCertificateRevocationListAttributeName()); - String issuerAttributeNames[] = splitString(params - .getCertificateRevocationListIssuerAttributeName()); - List list = cRLIssuerSearch(selector, attrs, attrNames, - issuerAttributeNames); - Set resultSet = createCRLs(list, selector); - if (resultSet.size() == 0) - { - X509CRLStoreSelector emptySelector = new X509CRLStoreSelector(); - list = cRLIssuerSearch(emptySelector, attrs, attrNames, - issuerAttributeNames); - - resultSet.addAll(createCRLs(list, selector)); - } - return resultSet; - } - - private Map cacheMap = new HashMap(cacheSize); - - private static int cacheSize = 32; - - private static long lifeTime = 60 * 1000; - - private synchronized void addToCache(String searchCriteria, List list) - { - Date now = new Date(System.currentTimeMillis()); - List cacheEntry = new ArrayList(); - cacheEntry.add(now); - cacheEntry.add(list); - if (cacheMap.containsKey(searchCriteria)) - { - cacheMap.put(searchCriteria, cacheEntry); - } - else - { - if (cacheMap.size() >= cacheSize) - { - // replace oldest - Iterator it = cacheMap.entrySet().iterator(); - long oldest = now.getTime(); - Object replace = null; - while (it.hasNext()) - { - Map.Entry entry = (Map.Entry)it.next(); - long current = ((Date)((List)entry.getValue()).get(0)) - .getTime(); - if (current < oldest) - { - oldest = current; - replace = entry.getKey(); - } - } - cacheMap.remove(replace); - } - cacheMap.put(searchCriteria, cacheEntry); - } - } - - private List getFromCache(String searchCriteria) - { - List entry = (List)cacheMap.get(searchCriteria); - long now = System.currentTimeMillis(); - if (entry != null) - { - // too old - if (((Date)entry.get(0)).getTime() < (now - lifeTime)) - { - return null; - } - return (List)entry.get(1); - } - return null; - } - - /* - * spilt string based on spaces - */ - private String[] splitString(String str) - { - return str.split("\\s+"); - } - - private String getSubjectAsString(X509CertStoreSelector xselector) - { - try - { - byte[] encSubject = xselector.getSubjectAsBytes(); - if (encSubject != null) - { - return new X500Principal(encSubject).getName("RFC1779"); - } - } - catch (IOException e) - { - throw new StoreException("exception processing name: " + e.getMessage(), e); - } - return null; - } - - private X500Principal getCertificateIssuer(X509Certificate cert) - { - return cert.getIssuerX500Principal(); - } -}