David Del Vecchio <ddelvecc@virginia.edu> - patches to RSA Pkcs1
+ Signature generation OID issues, help with clarifications on DateTime and
+ certificates.
+
+
+
Nelson Fernandez <nelson-bc@kpanic.com.ar> - patches to allow
+ compilation under mono.
+
+
+
Paulo Soares <psoares@consiste.pt> - patches to X509CertificateParser,
+ C# port of JZlib plus inflater/deflater streams, C# port of Apache BZip2
+ classes.
+
+
+
Pawel Niewiadomski <11110000b@gmail.com> - patches for X509 and CMS,
+ unit test for time classes.
+
+
+
Jesper Johansen <jesper@hc.jay.net> - bug fix for DerT61String
+ encodings.
+
+
+
Adam Sternberg <agsternberg@gmail.com> - identified problem with
+ generation of PGP public keyrings.
+
+
+
Kirill Zhuklinets <zhuklinets_k@gaz-is.ru> - initial submission of
+ bulk of Asn1.Esf classes (RFC 3126).
+
+
+
Dr Andrew Gray <andrew.gray@rcrt.co.uk> - identified problem with
+ BigInteger.ModPow for negative exponents.
+
+
+
Mauricio Ulate <mulate@gmail.com> - identified problem with non-ASCII
+ pass phrases in PGP.
+
+
+
John Allberg <John.Allberg@teliasonera.com> - initial implementation
+ of CryptoApiRandomGenerator.
+
+
+
Mattias Öhrn <mattias.ohrn@gmail.com> - identified problem with
+ Pkcs12Store.Save and provided fix.
+
+
+
Jen Andre <jandre@gmail.com> - initial implementation of
+ case-insensitive searches for PGP keyrings.
+
+
+
#Cyrille37# <cyrille37@gmail.com> - identified problem with
+ BigInteger.ModInverse for negative values.
+
+
+
David Reis Jr <davidreis@yahoo.com> - bug fix for X509CrlStoreSelector
+ handling of NextUpdate, fix handling of null parameters for DSA in key
+ factories, initial port of Pkix namespace and supporting tests.
+
+
+
+
Ivan Peev <ivan.peev@cozyroc.com> - bug fix for version string
+ displayed in PGP armored output.
+
+
+
Hector Ornelas Aciga <hector.ornelas@sat.gob.mx> - patch to add support for PKCS#5 Scheme 2 keys.
+
+
+
Tom Van Holle <tvh@dsoft.be> - patch to add new class: Pkcs10CertificationRequestDelaySigned.
+
+
+
Kalev Lember <kalev@smartlink.ee> - patch to fix compilation problem under Mono 2.8+.
+
+
+
Kyle Hamilton <kyanha.bouncycastle@kyanha.net> - identified problem with BigInteger.Multiply, patch for MiscPemGenerator infinite recursion.
+
+
+
Atanas Krachev <akrachev@gmail.com> - added support for revocation signatures in OpenPGP.
+
+
+
Torsten Moschny <t.moschny@web.de> - identified problem where PrivateKeyFactory/PublicKeyFactory failed to preserve publicKeyParamSet for EC keys.
+
+
+
Thomas Heggelund <the@dips.no> - identified problem with RSAParameters fields requiring zero-byte padding to satisfy .NET.
+
+
+
Laszlo Magyar <lmagyar1973@gmail.com> - patch to fix problem with SubjectDirectoryAttributes constructor.
+The Bouncy Castle License
+Copyright (c) 2000-2011 The Legion Of The Bouncy Castle
+(http://www.bouncycastle.org)
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"), to deal in the
+Software without restriction, including without limitation the rights to use, copy, modify, merge,
+publish, distribute, sub license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS",
+WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+INCLUDING BUT NOT LIMITED TO THE
+WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+PURPOSE AND NONINFRINGEMENT. IN NO
+EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+
+
+
diff --git a/Crypto/Readme.html b/Crypto/Readme.html
new file mode 100644
index 000000000..afa75e882
--- /dev/null
+++ b/Crypto/Readme.html
@@ -0,0 +1,455 @@
+
+
+
+ Notes
+
+
+
+
+ Online Certificate Status Protocol (OCSP, RFC 2560).
+
+ Time Stamp Protocol (TSP, RFC 3161).
+
+ Elliptic Curve Cryptography (support for F2m and Fp curves).
+
+ Reading/writing of PEM files, including RSA and DSA keys, with a variety of
+ encryptions.
+
+
PKIX certificate path validation
+
+
+
Porting notes from the old ASN.1 library For the most part code using the
+ old subset of ASN.1 classes should be easy to transfer, providing the following
+ changes are made:
+
+ If you were using the older mutable DERConstructedSequence/Set and
+ BERConstructedSequence, use an Asn1EncodableVector in conjunction with
+ DerSequence/Set and BerSequence
+
+ BERInputStream and DERInputStream are replaced with Asn1InputStream
+
+ AsymmetricKeyParameter is now in the Org.Bouncycastle.Crypto namespace
+
+
+
+
How To Build.
+
+ The BC C# API uses NAnt (http://nant.sourceforge.net)
+ to provide a platform independent build environment (suggested version NAnt 0.90).
+ There is also a solution file for Visual Studio, and for MonoDevelop. The API works
+ with .NET Framework 1.1 and above. It has been successfully built and tested with Mono
+ versions from 1.1.13 onwards. The source code can be built for .NET Compact Framework 1.0
+ by setting the compilation flag NETCF_1_0, or .NET Compact Framework 2.0 by setting NETCF_2_0,
+ or Silverlight 2 by setting SILVERLIGHT.
+
+ Using a command prompt (DOS window), cd into the 'crypto' folder of this
+ distribution.
+
+ Use,
+
+
+ 'nant' without arguments to compile
+ debug code, the tests and run the tests.
+
+ 'nant compile-release' to compile
+ release code.
+
+ 'nant compile-debug' to compile
+ debug code.
+
+ 'nant test' to run the included unit
+ tests (using NUnit; you may need to edit the build file to set the location
+ where NUnit is installed).
+
+
+ Output:
+
+ The compiled API can be found in the 'api/bin/release' &
+ 'api/bin/debug' directories.
+ The compiled tests can be found in the 'test/bin' directory
+ (by default a debug build is used for testing).
+
+
+
+
The Source:
+ Source code can be found in the 'src'directory.
+
+
+
Documentation:
+
There is limited documentation available at the moment. Some of the source
+ contains XML comments, but this is a work in progress. We will be working to
+ improve this now that 1.0 is out the door.
+
+
+
+
For first time users.
+ Java heritage,
+
+ The Bouncy Castle C# API is a port of the Bouncy Castle Java APIs.
+ Approximately %80 of the functionality in the Java build has now been ported.
+ For the most part, the naming conventions of the .NET platform have been
+ adopted. The C# API is constantly kept uptodate with bug fixes and new test
+ cases from the Java build (and vice versa sometimes), thus benefitting from the
+ large user base and real-world use the Java version has seen.
+
+ Please consider.
+
+ The Bouncy Castle C# API is a library of transformations that when combined
+ properly will enable developers to create standard conforming cryptographic
+ systems. In order to use this API you must have some knowledge of how to build
+ cryptographic systems, namely what transformations to use and the when, where
+ and why of their use.
+ Developing good cryptographic systems takes practice and understanding.
+
+ There are many resources available online and in book shops; please use those
+ to your advantage.
+
+
+
Notes:
+
Release 1.7, Thursday April 7, 2011
+
Additional Features and Functionality
+
+
TLS now supports client authentication.
+
TLS now supports compression.
+
TLS now supports ECC cipher suites (RFC 4492).
+
Library can now be built for Silverlight (2.0 and above).
+
ASN.1 classes for CRMF (RFC 4211) and CMP (RFC 4210) have been added.
+
Further performance improvements to GCM mode.
+
BufferedBlockCipher will now always reset after a DoFinal().
A point release to rectify some problems with the released assembly of 1.6 version.
+
+
Release 1.6, Thursday February 4, 2010
+
Defects Fixed
+
+
X509DefaultEntryConverter was not recognising telephone number as a PrintableString field. This has been fixed.
+
OpenPGP now supports UTF-8 in file names for literal data.
+
+
Security Advisory
+
+
This version has been specifically reviewed to eliminate possible timing attacks on algorithms such as GCM and CCM mode.
+
+
Additional Features and Functionality
+
+
Support for PSS signatures has been added to CMS.
+
SubjectKeyIdentifier now supports both methods specified in RFC 3280, section 4.2.1.2 for generating the identifier.
+
Performance of GCM mode has been greatly improved (on average 10x).
+
Support for mac lengths of 96, 104, 112, and 120 bits has been added to existing support for 128 bits in GCMBlockCipher.
+
Support for raw signatures has been extended to RSA, RSA-PSS and ECDSA. RSA support can be used in CmsSignedDataStreamGenerator to support signatures without signed attributes.
+
Support for EC MQV has been added to the light weight API and the CMS library.
Correct the ASN.1 class for AuthorityInformationAccess.
+
In the Bcpg libs, armored output now inserts the correct version string.
+
EssCertIDv2 encoding now complies with RFC 5035.
+
ECDSA now computes correct signatures for oversized hashes when the order of the base point is not a multiple of 8 in compliance with X9.62-2005.
+
Standard name "DiffieHellman" is now supported in factory classes.
+
Better support for equality tests for '#' encoded entries has been added to X509Name.
+
'=' inside a X509Name was not being properly escaped. This has been fixed.
+
ApplicationSpecific ASN.1 tags are now recognised in BER data. The GetObject() method now handles processing of arbitrary tags.
+
Multiplication by negative powers of two is fixed in BigInteger.
+
Multiple countersignature attributes are now correctly collected.
+
Two bugs in HC-128 and HC-256 related to sign extension and byte swapping have been fixed. The implementations now pass the latest ecrypt vector tests.
+
+
Security Advisory
+
+
The effect of the sign extension bug was to decrease the key space the HC-128 and HC-256 ciphers were operating in and the byte swapping inverted every 32 bits of the generated stream. If you are using either HC-128 or HC-256 you must upgrade to this release.
+
+
Additional Features and Functionality
+
+
PKIX certificate path validation
+
Accept duplicate PKCS#9 FriendlyName attributes in PKCS#12 keystore.
+
Add support for PKCS#5 Scheme 2 keys.
+
Camellia performance improved.
+
A smaller version of Camellia, CamelliaLightEngine has also been added.
+
CmsSignedData generation now supports SubjectKeyIdentifier as well as use of issuer/serial.
+
A CMS PBE key holder for UTF8 keys has been added to the CMS API.
+
Salt and iteration count can now be recovered from PasswordRecipientInformation.
+
Support for reading and extracting personalised certificates in PGP Secret Key rings has been added.
+
Support for EAC algorithms has been added to CMS.
+
Asn1Dump now supports a verbose mode for displaying the contents of octet and bit strings.
The GeneralName string constructor now supports IPv4 and IPv6 address parsing.
+
EAX mode was not handling non-zero offsetted data correctly and failing. This has been fixed.
+
EAX mode ciphers were not resetting correctly after a DoFinal/Reset. This has been fixed.
+
Some boolean parameters to IssuingDistributionPoint were being reversed. This has been fixed.
A zero length RDN would cause an exception in an X509Name. This has been fixed.
+
Specifying a greater than 32bit length for a stream and relying on the default BcpgOutputStream resulted in corrupted data. This has been fixed.
+
Pkcs7Padding validation would not fail if pad length was 0. This has been fixed.
+
Signature creation time was not being properly initialised in new V4 PGP signature objects although the encoding was correct. This has been fixed.
+
The '+' character can now be escaped or quoted in the constructor for X509Name.
+
IV handling in CMS for SEED and Camellia was incorrect. This has been fixed.
+
ASN.1 stream parser now throws exceptions for unterminated sequences.
+
X509CertificateParser/X509CrlParser now handle multiple certificates/CRLs in streams that don't support seeking.
+
The CertID class used by the TSP library was incomplete. This has been fixed
+
\# is now properly recognised in the X509Name class.
+
BigInteger.ModInverse was failing for negative values. This has been fixed.
+
CMS API now supports RSASSA-PSS signatures with explicit salt length.
+
+
Additional Features and Functionality
+
+
ASN.1 libs now support high tag numbers.
+
Galois/Counter Mode (GCM) has been added.
+
The TSP API now supports parsing and validation of responses with V2 signing certificate entries.
+
Unnecessary local ID attributes on certificates in PKCS12 files are now automatically removed.
+
New Pkcs12StoreBuilder class supports generation of PKCS12 files with both certificates and keys protected by 3DES.
+
Certifications associated with user attributes can now be created, verified and removed in OpenPGP.
+
API support now exists for CMS countersignature reading and production.
+
A new class LazyAsn1InputStream supports lazy evaluation of DER sequences and sets, considerably reducing memory requirements in some scenarios.
+
KeyPurposeId class has been updated for RFC 4945.
+
Initial support has been added for HP_CERTIFICATE_REQUEST in the TLS API.
+
PGP example programs now handle blank names in literal data objects.
+
The ProofOfPossession class now better supports the underlying ASN.1 structure.
+
+
Additional Notes
+
+
Due to problems for some users caused by the presence of the IDEA algorithm, an implementation is no
+longer included in the default assembly. Only the assembly named BouncyCastle.CryptoExt now includes IDEA.
+ ASN.1 stream parsing now handles definite length encodings efficiently.
+ Buffering in the streaming CMS has been reworked. Throughput is now usually higher and the behaviour is more predictable.
+ BcpgInputStream now handles data blocks in the 2**31->2**32-1 range.
+ Some confusion over the parameters J and L in connection with Diffie-Hellman has been resolved.
+ Added CryptoApiRandomGenerator, a wrapper for RNGCryptoServiceProvider.
+ Added VMPC stream cipher, VMPCMAC and a VMPC-based implementation of IRandomGenerator.
+ Added support in OpenPGP for fetching keyrings by case-insensitive user ID [#BMA-8].
+ Fixed a vulnerability of CMS signatures that do not use signed attributes (Bleichenbacher RSA forgery).
+ Fixed a bug causing second and later encrypted objects to be ignored in KeyBasedFileProcessor example.
+ Fixed case-sensitivity issue with deletion from a PKCS#12 file.
+ Fixed problem overwriting entities in a PKCS#12 file.
+ Fixed PgpUtilities.MakeKeyFromPassPhrase for 8-bit characters [#BMA-13].
+ Fixed duplicate certificate problem in Pkcs12Store.Save [#BMA-12].
+ Fixed NAnt build under Mono [#BMA-10].
+ Fixed BigInteger.ModPow for negative exponents [#BMA-7].
+
+
Release 1.2, Thursday July 5, 2007
+
+ Source now builds on .NET Compact Framework 1.0 (compilation flag NETCF_1_0).
+ Release assembly now signed with a strong name.
+ Added CCM and EAX block cipher modes.
+ Added Noekeon block cipher.
+ Added HC-128, HC-256, and ISAAC stream ciphers.
+ Added RIPEMD160withECDSA signature algorithm.
+ Added support for notation data signature subpackets to OpenPGP.
+ Added support for parsing of experimental signatures to OpenPGP.
+ Added the complete set of SEC-2 EC curves.
+ Added support for implicit tagging to DerApplicationSpecific.
+ Added remaining ASN.1 structures from RFC 3126 to Asn1.Esf namespace.
+ Performance of ECDSA improved.
+ Performance of ASN.1 stream parsing improved.
+ Fixed default private key length for Diffie-Hellman parameters.
+ Fixed DerT61String to correctly support 8-bit characters.
+ Fixed duplicate attribute problem in Pkcs12Store.Save.
+ Fixed a problem writing public keys in OpenPGP [#BMA-5].
+
+
Release 1.1, Friday May 4, 2007
+
+ Added support for writing DSA private keys, and more encodings, in OpenSsl
+ (PemReader/PemWriter).
+ Removed SharpZipLib dependency.
+ Added RSA blinded signature classes.
+ Added Asn1.IsisMtt namespace (ISIS-MTT ASN.1 classes).
+ Added SEED block cipher engine.
+ Added Salsa20 stream cipher engine.
+ Performance optimisations for F2m elliptic curves.
+ Fixed OpenPGP bug decrypting files with multiple types of encryption on the
+ session key.
+
+
Release 1.0, Thursday January 18,
+ 2007
+
+ Implementations of CMS, OCSP, OpenPGP, and TSP.
+ Elliptic Curves (F2m and Fp).
+ A basic TLS client.
+ PEM file reading and writing.
+ Symmetric key algorithms: Camellia, GOST28147, NaccacheStern, and TEA/XTEA.
+ Symmetric key modes: GOFB and OpenPGPCFB.
+ Symmetric key paddings: ISO7816d4.
+ Asymmetric key algorithms: RSA blinding.
+ Digests: GOST3411 and Whirlpool.
+ Macs: GOST28147 and ISO9797 Alg 3.
+ Signer mechanisms: ECDSA, ECGOST3410, and GOST3410.
+ ...and many more features, bug fixes, and performance improvements.
+
+
Tuesday Febuary 1, 2005
+
This is the second beta release of the Bouncy Castle API C# implementation.
+ Reliability improvement to ASN1InputStream.
+ The OID entries in SignerUtilities for RSA signature algorithms for SHA-256,
+ SHA-384, and SHA-512 were pointing creating the wrong signature objects.
+
Sunday December 12, 2004
+ This is the first beta release of the Bouncy Castle Cryptographic API C#
+ implementation.
+ The Legion of the Bouncy Castle would like to extend their thanks to all those
+ who contributed to this API during the alpha stages of its development.
+ Keep up the good work folks.
+ Please send any questions or bug reports to
+ dev-crypto-csharp@bouncycastle.org
+
+
+
Trademarks.
+
+ C#, .NET, and MSDN are Registered Trademarks of Microsoft.
+ Microsoft.com
+ Java is a Registered Trademark of Sun Microsystems. Sun
+ Microsystems
+
+
+
2007 Legion of the Bouncy Castle
+
+
+
diff --git a/Crypto/bzip2/src/BZip2Constants.cs b/Crypto/bzip2/src/BZip2Constants.cs
new file mode 100644
index 000000000..4a5442d8b
--- /dev/null
+++ b/Crypto/bzip2/src/BZip2Constants.cs
@@ -0,0 +1,103 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+/*
+ * This package is based on the work done by Keiron Liddle, Aftex Software
+ * to whom the Ant project is very grateful for his
+ * great code.
+ */
+
+using System;
+
+namespace Org.BouncyCastle.Apache.Bzip2
+{
+ /**
+ * Base class for both the compress and decompress classes.
+ * Holds common arrays, and static data.
+ *
+ * @author Keiron Liddle
+ */
+ public class BZip2Constants {
+
+ public const int baseBlockSize = 100000;
+ public const int MAX_ALPHA_SIZE = 258;
+ public const int MAX_CODE_LEN = 23;
+ public const int RUNA = 0;
+ public const int RUNB = 1;
+ public const int N_GROUPS = 6;
+ public const int G_SIZE = 50;
+ public const int N_ITERS = 4;
+ public const int MAX_SELECTORS = (2 + (900000 / G_SIZE));
+ public const int NUM_OVERSHOOT_BYTES = 20;
+
+ public static readonly int[] rNums = {
+ 619, 720, 127, 481, 931, 816, 813, 233, 566, 247,
+ 985, 724, 205, 454, 863, 491, 741, 242, 949, 214,
+ 733, 859, 335, 708, 621, 574, 73, 654, 730, 472,
+ 419, 436, 278, 496, 867, 210, 399, 680, 480, 51,
+ 878, 465, 811, 169, 869, 675, 611, 697, 867, 561,
+ 862, 687, 507, 283, 482, 129, 807, 591, 733, 623,
+ 150, 238, 59, 379, 684, 877, 625, 169, 643, 105,
+ 170, 607, 520, 932, 727, 476, 693, 425, 174, 647,
+ 73, 122, 335, 530, 442, 853, 695, 249, 445, 515,
+ 909, 545, 703, 919, 874, 474, 882, 500, 594, 612,
+ 641, 801, 220, 162, 819, 984, 589, 513, 495, 799,
+ 161, 604, 958, 533, 221, 400, 386, 867, 600, 782,
+ 382, 596, 414, 171, 516, 375, 682, 485, 911, 276,
+ 98, 553, 163, 354, 666, 933, 424, 341, 533, 870,
+ 227, 730, 475, 186, 263, 647, 537, 686, 600, 224,
+ 469, 68, 770, 919, 190, 373, 294, 822, 808, 206,
+ 184, 943, 795, 384, 383, 461, 404, 758, 839, 887,
+ 715, 67, 618, 276, 204, 918, 873, 777, 604, 560,
+ 951, 160, 578, 722, 79, 804, 96, 409, 713, 940,
+ 652, 934, 970, 447, 318, 353, 859, 672, 112, 785,
+ 645, 863, 803, 350, 139, 93, 354, 99, 820, 908,
+ 609, 772, 154, 274, 580, 184, 79, 626, 630, 742,
+ 653, 282, 762, 623, 680, 81, 927, 626, 789, 125,
+ 411, 521, 938, 300, 821, 78, 343, 175, 128, 250,
+ 170, 774, 972, 275, 999, 639, 495, 78, 352, 126,
+ 857, 956, 358, 619, 580, 124, 737, 594, 701, 612,
+ 669, 112, 134, 694, 363, 992, 809, 743, 168, 974,
+ 944, 375, 748, 52, 600, 747, 642, 182, 862, 81,
+ 344, 805, 988, 739, 511, 655, 814, 334, 249, 515,
+ 897, 955, 664, 981, 649, 113, 974, 459, 893, 228,
+ 433, 837, 553, 268, 926, 240, 102, 654, 459, 51,
+ 686, 754, 806, 760, 493, 403, 415, 394, 687, 700,
+ 946, 670, 656, 610, 738, 392, 760, 799, 887, 653,
+ 978, 321, 576, 617, 626, 502, 894, 679, 243, 440,
+ 680, 879, 194, 572, 640, 724, 926, 56, 204, 700,
+ 707, 151, 457, 449, 797, 195, 791, 558, 945, 679,
+ 297, 59, 87, 824, 713, 663, 412, 693, 342, 606,
+ 134, 108, 571, 364, 631, 212, 174, 643, 304, 329,
+ 343, 97, 430, 751, 497, 314, 983, 374, 822, 928,
+ 140, 206, 73, 263, 980, 736, 876, 478, 430, 305,
+ 170, 514, 364, 692, 829, 82, 855, 953, 676, 246,
+ 369, 970, 294, 750, 807, 827, 150, 790, 288, 923,
+ 804, 378, 215, 828, 592, 281, 565, 555, 710, 82,
+ 896, 831, 547, 261, 524, 462, 293, 465, 502, 56,
+ 661, 821, 976, 991, 658, 869, 905, 758, 745, 193,
+ 768, 550, 608, 933, 378, 286, 215, 979, 792, 961,
+ 61, 688, 793, 644, 986, 403, 106, 366, 905, 644,
+ 372, 567, 466, 434, 645, 210, 389, 550, 919, 135,
+ 780, 773, 635, 389, 707, 100, 626, 958, 165, 504,
+ 920, 176, 193, 713, 857, 265, 203, 50, 668, 108,
+ 645, 990, 626, 197, 510, 357, 358, 850, 858, 364,
+ 936, 638
+ };
+ }
+}
\ No newline at end of file
diff --git a/Crypto/bzip2/src/CBZip2InputStream.cs b/Crypto/bzip2/src/CBZip2InputStream.cs
new file mode 100644
index 000000000..7411f0a21
--- /dev/null
+++ b/Crypto/bzip2/src/CBZip2InputStream.cs
@@ -0,0 +1,919 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+/*
+ * This package is based on the work done by Keiron Liddle, Aftex Software
+ * to whom the Ant project is very grateful for his
+ * great code.
+ */
+
+using System;
+using System.IO;
+
+namespace Org.BouncyCastle.Apache.Bzip2
+{
+ /**
+ * An input stream that decompresses from the BZip2 format (with the file
+ * header chars) to be read as any other stream.
+ *
+ * @author Keiron Liddle
+ *
+ * NB: note this class has been modified to read the leading BZ from the
+ * start of the BZIP2 stream to make it compatible with other PGP programs.
+ */
+ public class CBZip2InputStream : Stream
+ {
+ private static void Cadvise() {
+ //System.out.Println("CRC Error");
+ //throw new CCoruptionError();
+ }
+
+// private static void BadBGLengths() {
+// Cadvise();
+// }
+//
+// private static void BitStreamEOF() {
+// Cadvise();
+// }
+
+ private static void CompressedStreamEOF() {
+ Cadvise();
+ }
+
+ private void MakeMaps() {
+ int i;
+ nInUse = 0;
+ for (i = 0; i < 256; i++) {
+ if (inUse[i]) {
+ seqToUnseq[nInUse] = (char) i;
+ unseqToSeq[i] = (char) nInUse;
+ nInUse++;
+ }
+ }
+ }
+
+ /*
+ index of the last char in the block, so
+ the block size == last + 1.
+ */
+ private int last;
+
+ /*
+ index in zptr[] of original string after sorting.
+ */
+ private int origPtr;
+
+ /*
+ always: in the range 0 .. 9.
+ The current block size is 100000 * this number.
+ */
+ private int blockSize100k;
+
+ private bool blockRandomised;
+
+ private int bsBuff;
+ private int bsLive;
+ private CRC mCrc = new CRC();
+
+ private bool[] inUse = new bool[256];
+ private int nInUse;
+
+ private char[] seqToUnseq = new char[256];
+ private char[] unseqToSeq = new char[256];
+
+ private char[] selector = new char[BZip2Constants.MAX_SELECTORS];
+ private char[] selectorMtf = new char[BZip2Constants.MAX_SELECTORS];
+
+ private int[] tt;
+ private char[] ll8;
+
+ /*
+ freq table collected to save a pass over the data
+ during decompression.
+ */
+ private int[] unzftab = new int[256];
+
+ private int[][] limit = InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE);
+ private int[][] basev = InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE);
+ private int[][] perm = InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE);
+ private int[] minLens = new int[BZip2Constants.N_GROUPS];
+
+ private Stream bsStream;
+
+ private bool streamEnd = false;
+
+ private int currentChar = -1;
+
+ private const int START_BLOCK_STATE = 1;
+ private const int RAND_PART_A_STATE = 2;
+ private const int RAND_PART_B_STATE = 3;
+ private const int RAND_PART_C_STATE = 4;
+ private const int NO_RAND_PART_A_STATE = 5;
+ private const int NO_RAND_PART_B_STATE = 6;
+ private const int NO_RAND_PART_C_STATE = 7;
+
+ private int currentState = START_BLOCK_STATE;
+
+ private int storedBlockCRC, storedCombinedCRC;
+ private int computedBlockCRC, computedCombinedCRC;
+
+ int i2, count, chPrev, ch2;
+ int i, tPos;
+ int rNToGo = 0;
+ int rTPos = 0;
+ int j2;
+ char z;
+
+ public CBZip2InputStream(Stream zStream) {
+ ll8 = null;
+ tt = null;
+ BsSetStream(zStream);
+ Initialize();
+ InitBlock();
+ SetupBlock();
+ }
+
+ internal static int[][] InitIntArray(int n1, int n2) {
+ int[][] a = new int[n1][];
+ for (int k = 0; k < n1; ++k) {
+ a[k] = new int[n2];
+ }
+ return a;
+ }
+
+ internal static char[][] InitCharArray(int n1, int n2) {
+ char[][] a = new char[n1][];
+ for (int k = 0; k < n1; ++k) {
+ a[k] = new char[n2];
+ }
+ return a;
+ }
+
+ public override int ReadByte() {
+ if (streamEnd) {
+ return -1;
+ } else {
+ int retChar = currentChar;
+ switch (currentState) {
+ case START_BLOCK_STATE:
+ break;
+ case RAND_PART_A_STATE:
+ break;
+ case RAND_PART_B_STATE:
+ SetupRandPartB();
+ break;
+ case RAND_PART_C_STATE:
+ SetupRandPartC();
+ break;
+ case NO_RAND_PART_A_STATE:
+ break;
+ case NO_RAND_PART_B_STATE:
+ SetupNoRandPartB();
+ break;
+ case NO_RAND_PART_C_STATE:
+ SetupNoRandPartC();
+ break;
+ default:
+ break;
+ }
+ return retChar;
+ }
+ }
+
+ private void Initialize() {
+ char magic3, magic4;
+ magic3 = BsGetUChar();
+ magic4 = BsGetUChar();
+ if (magic3 != 'B' && magic4 != 'Z')
+ {
+ throw new IOException("Not a BZIP2 marked stream");
+ }
+ magic3 = BsGetUChar();
+ magic4 = BsGetUChar();
+ if (magic3 != 'h' || magic4 < '1' || magic4 > '9') {
+ BsFinishedWithStream();
+ streamEnd = true;
+ return;
+ }
+
+ SetDecompressStructureSizes(magic4 - '0');
+ computedCombinedCRC = 0;
+ }
+
+ private void InitBlock() {
+ char magic1, magic2, magic3, magic4;
+ char magic5, magic6;
+ magic1 = BsGetUChar();
+ magic2 = BsGetUChar();
+ magic3 = BsGetUChar();
+ magic4 = BsGetUChar();
+ magic5 = BsGetUChar();
+ magic6 = BsGetUChar();
+ if (magic1 == 0x17 && magic2 == 0x72 && magic3 == 0x45
+ && magic4 == 0x38 && magic5 == 0x50 && magic6 == 0x90) {
+ Complete();
+ return;
+ }
+
+ if (magic1 != 0x31 || magic2 != 0x41 || magic3 != 0x59
+ || magic4 != 0x26 || magic5 != 0x53 || magic6 != 0x59) {
+ BadBlockHeader();
+ streamEnd = true;
+ return;
+ }
+
+ storedBlockCRC = BsGetInt32();
+
+ if (BsR(1) == 1) {
+ blockRandomised = true;
+ } else {
+ blockRandomised = false;
+ }
+
+ // currBlockNo++;
+ GetAndMoveToFrontDecode();
+
+ mCrc.InitialiseCRC();
+ currentState = START_BLOCK_STATE;
+ }
+
+ private void EndBlock() {
+ computedBlockCRC = mCrc.GetFinalCRC();
+ /* A bad CRC is considered a fatal error. */
+ if (storedBlockCRC != computedBlockCRC) {
+ CrcError();
+ }
+
+ computedCombinedCRC = (computedCombinedCRC << 1)
+ | (int)(((uint)computedCombinedCRC) >> 31);
+ computedCombinedCRC ^= computedBlockCRC;
+ }
+
+ private void Complete() {
+ storedCombinedCRC = BsGetInt32();
+ if (storedCombinedCRC != computedCombinedCRC) {
+ CrcError();
+ }
+
+ BsFinishedWithStream();
+ streamEnd = true;
+ }
+
+ private static void BlockOverrun() {
+ Cadvise();
+ }
+
+ private static void BadBlockHeader() {
+ Cadvise();
+ }
+
+ private static void CrcError() {
+ Cadvise();
+ }
+
+ private void BsFinishedWithStream() {
+ try {
+ if (this.bsStream != null) {
+ this.bsStream.Dispose();
+ this.bsStream = null;
+ }
+ } catch {
+ //ignore
+ }
+ }
+
+ private void BsSetStream(Stream f) {
+ bsStream = f;
+ bsLive = 0;
+ bsBuff = 0;
+ }
+
+ private int BsR(int n) {
+ int v;
+ while (bsLive < n) {
+ int zzi;
+ char thech = '\0';
+ try {
+ thech = (char) bsStream.ReadByte();
+ } catch (IOException) {
+ CompressedStreamEOF();
+ }
+ if (thech == '\uffff') {
+ CompressedStreamEOF();
+ }
+ zzi = thech;
+ bsBuff = (bsBuff << 8) | (zzi & 0xff);
+ bsLive += 8;
+ }
+
+ v = (bsBuff >> (bsLive - n)) & ((1 << n) - 1);
+ bsLive -= n;
+ return v;
+ }
+
+ private char BsGetUChar() {
+ return (char) BsR(8);
+ }
+
+ private int BsGetint() {
+ int u = 0;
+ u = (u << 8) | BsR(8);
+ u = (u << 8) | BsR(8);
+ u = (u << 8) | BsR(8);
+ u = (u << 8) | BsR(8);
+ return u;
+ }
+
+ private int BsGetIntVS(int numBits) {
+ return (int) BsR(numBits);
+ }
+
+ private int BsGetInt32() {
+ return (int) BsGetint();
+ }
+
+ private void HbCreateDecodeTables(int[] limit, int[] basev,
+ int[] perm, char[] length,
+ int minLen, int maxLen, int alphaSize) {
+ int pp, i, j, vec;
+
+ pp = 0;
+ for (i = minLen; i <= maxLen; i++) {
+ for (j = 0; j < alphaSize; j++) {
+ if (length[j] == i) {
+ perm[pp] = j;
+ pp++;
+ }
+ }
+ }
+
+ for (i = 0; i < BZip2Constants.MAX_CODE_LEN; i++) {
+ basev[i] = 0;
+ }
+ for (i = 0; i < alphaSize; i++) {
+ basev[length[i] + 1]++;
+ }
+
+ for (i = 1; i < BZip2Constants.MAX_CODE_LEN; i++) {
+ basev[i] += basev[i - 1];
+ }
+
+ for (i = 0; i < BZip2Constants.MAX_CODE_LEN; i++) {
+ limit[i] = 0;
+ }
+ vec = 0;
+
+ for (i = minLen; i <= maxLen; i++) {
+ vec += (basev[i + 1] - basev[i]);
+ limit[i] = vec - 1;
+ vec <<= 1;
+ }
+ for (i = minLen + 1; i <= maxLen; i++) {
+ basev[i] = ((limit[i - 1] + 1) << 1) - basev[i];
+ }
+ }
+
+ private void RecvDecodingTables() {
+ char[][] len = InitCharArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE);
+ int i, j, t, nGroups, nSelectors, alphaSize;
+ int minLen, maxLen;
+ bool[] inUse16 = new bool[16];
+
+ /* Receive the mapping table */
+ for (i = 0; i < 16; i++) {
+ if (BsR(1) == 1) {
+ inUse16[i] = true;
+ } else {
+ inUse16[i] = false;
+ }
+ }
+
+ for (i = 0; i < 256; i++) {
+ inUse[i] = false;
+ }
+
+ for (i = 0; i < 16; i++) {
+ if (inUse16[i]) {
+ for (j = 0; j < 16; j++) {
+ if (BsR(1) == 1) {
+ inUse[i * 16 + j] = true;
+ }
+ }
+ }
+ }
+
+ MakeMaps();
+ alphaSize = nInUse + 2;
+
+ /* Now the selectors */
+ nGroups = BsR(3);
+ nSelectors = BsR(15);
+ for (i = 0; i < nSelectors; i++) {
+ j = 0;
+ while (BsR(1) == 1) {
+ j++;
+ }
+ selectorMtf[i] = (char) j;
+ }
+
+ /* Undo the MTF values for the selectors. */
+ {
+ char[] pos = new char[BZip2Constants.N_GROUPS];
+ char tmp, v;
+ for (v = '\0'; v < nGroups; v++) {
+ pos[v] = v;
+ }
+
+ for (i = 0; i < nSelectors; i++) {
+ v = selectorMtf[i];
+ tmp = pos[v];
+ while (v > 0) {
+ pos[v] = pos[v - 1];
+ v--;
+ }
+ pos[0] = tmp;
+ selector[i] = tmp;
+ }
+ }
+
+ /* Now the coding tables */
+ for (t = 0; t < nGroups; t++) {
+ int curr = BsR(5);
+ for (i = 0; i < alphaSize; i++) {
+ while (BsR(1) == 1) {
+ if (BsR(1) == 0) {
+ curr++;
+ } else {
+ curr--;
+ }
+ }
+ len[t][i] = (char) curr;
+ }
+ }
+
+ /* Create the Huffman decoding tables */
+ for (t = 0; t < nGroups; t++) {
+ minLen = 32;
+ maxLen = 0;
+ for (i = 0; i < alphaSize; i++) {
+ if (len[t][i] > maxLen) {
+ maxLen = len[t][i];
+ }
+ if (len[t][i] < minLen) {
+ minLen = len[t][i];
+ }
+ }
+ HbCreateDecodeTables(limit[t], basev[t], perm[t], len[t], minLen,
+ maxLen, alphaSize);
+ minLens[t] = minLen;
+ }
+ }
+
+ private void GetAndMoveToFrontDecode() {
+ char[] yy = new char[256];
+ int i, j, nextSym, limitLast;
+ int EOB, groupNo, groupPos;
+
+ limitLast = BZip2Constants.baseBlockSize * blockSize100k;
+ origPtr = BsGetIntVS(24);
+
+ RecvDecodingTables();
+ EOB = nInUse + 1;
+ groupNo = -1;
+ groupPos = 0;
+
+ /*
+ Setting up the unzftab entries here is not strictly
+ necessary, but it does save having to do it later
+ in a separate pass, and so saves a block's worth of
+ cache misses.
+ */
+ for (i = 0; i <= 255; i++) {
+ unzftab[i] = 0;
+ }
+
+ for (i = 0; i <= 255; i++) {
+ yy[i] = (char) i;
+ }
+
+ last = -1;
+
+ {
+ int zt, zn, zvec, zj;
+ if (groupPos == 0) {
+ groupNo++;
+ groupPos = BZip2Constants.G_SIZE;
+ }
+ groupPos--;
+ zt = selector[groupNo];
+ zn = minLens[zt];
+ zvec = BsR(zn);
+ while (zvec > limit[zt][zn]) {
+ zn++;
+ {
+ {
+ while (bsLive < 1) {
+ int zzi;
+ char thech = '\0';
+ try {
+ thech = (char) bsStream.ReadByte();
+ } catch (IOException) {
+ CompressedStreamEOF();
+ }
+ if (thech == '\uffff') {
+ CompressedStreamEOF();
+ }
+ zzi = thech;
+ bsBuff = (bsBuff << 8) | (zzi & 0xff);
+ bsLive += 8;
+ }
+ }
+ zj = (bsBuff >> (bsLive - 1)) & 1;
+ bsLive--;
+ }
+ zvec = (zvec << 1) | zj;
+ }
+ nextSym = perm[zt][zvec - basev[zt][zn]];
+ }
+
+ while (true) {
+
+ if (nextSym == EOB) {
+ break;
+ }
+
+ if (nextSym == BZip2Constants.RUNA || nextSym == BZip2Constants.RUNB) {
+ char ch;
+ int s = -1;
+ int N = 1;
+ do {
+ if (nextSym == BZip2Constants.RUNA) {
+ s = s + (0 + 1) * N;
+ } else if (nextSym == BZip2Constants.RUNB) {
+ s = s + (1 + 1) * N;
+ }
+ N = N * 2;
+ {
+ int zt, zn, zvec, zj;
+ if (groupPos == 0) {
+ groupNo++;
+ groupPos = BZip2Constants.G_SIZE;
+ }
+ groupPos--;
+ zt = selector[groupNo];
+ zn = minLens[zt];
+ zvec = BsR(zn);
+ while (zvec > limit[zt][zn]) {
+ zn++;
+ {
+ {
+ while (bsLive < 1) {
+ int zzi;
+ char thech = '\0';
+ try {
+ thech = (char) bsStream.ReadByte();
+ } catch (IOException) {
+ CompressedStreamEOF();
+ }
+ if (thech == '\uffff') {
+ CompressedStreamEOF();
+ }
+ zzi = thech;
+ bsBuff = (bsBuff << 8) | (zzi & 0xff);
+ bsLive += 8;
+ }
+ }
+ zj = (bsBuff >> (bsLive - 1)) & 1;
+ bsLive--;
+ }
+ zvec = (zvec << 1) | zj;
+ }
+ nextSym = perm[zt][zvec - basev[zt][zn]];
+ }
+ } while (nextSym == BZip2Constants.RUNA || nextSym == BZip2Constants.RUNB);
+
+ s++;
+ ch = seqToUnseq[yy[0]];
+ unzftab[ch] += s;
+
+ while (s > 0) {
+ last++;
+ ll8[last] = ch;
+ s--;
+ }
+
+ if (last >= limitLast) {
+ BlockOverrun();
+ }
+ continue;
+ } else {
+ char tmp;
+ last++;
+ if (last >= limitLast) {
+ BlockOverrun();
+ }
+
+ tmp = yy[nextSym - 1];
+ unzftab[seqToUnseq[tmp]]++;
+ ll8[last] = seqToUnseq[tmp];
+
+ /*
+ This loop is hammered during decompression,
+ hence the unrolling.
+
+ for (j = nextSym-1; j > 0; j--) yy[j] = yy[j-1];
+ */
+
+ j = nextSym - 1;
+ for (; j > 3; j -= 4) {
+ yy[j] = yy[j - 1];
+ yy[j - 1] = yy[j - 2];
+ yy[j - 2] = yy[j - 3];
+ yy[j - 3] = yy[j - 4];
+ }
+ for (; j > 0; j--) {
+ yy[j] = yy[j - 1];
+ }
+
+ yy[0] = tmp;
+ {
+ int zt, zn, zvec, zj;
+ if (groupPos == 0) {
+ groupNo++;
+ groupPos = BZip2Constants.G_SIZE;
+ }
+ groupPos--;
+ zt = selector[groupNo];
+ zn = minLens[zt];
+ zvec = BsR(zn);
+ while (zvec > limit[zt][zn]) {
+ zn++;
+ {
+ {
+ while (bsLive < 1) {
+ int zzi;
+ char thech = '\0';
+ try {
+ thech = (char) bsStream.ReadByte();
+ } catch (IOException) {
+ CompressedStreamEOF();
+ }
+ zzi = thech;
+ bsBuff = (bsBuff << 8) | (zzi & 0xff);
+ bsLive += 8;
+ }
+ }
+ zj = (bsBuff >> (bsLive - 1)) & 1;
+ bsLive--;
+ }
+ zvec = (zvec << 1) | zj;
+ }
+ nextSym = perm[zt][zvec - basev[zt][zn]];
+ }
+ continue;
+ }
+ }
+ }
+
+ private void SetupBlock() {
+ int[] cftab = new int[257];
+ char ch;
+
+ cftab[0] = 0;
+ for (i = 1; i <= 256; i++) {
+ cftab[i] = unzftab[i - 1];
+ }
+ for (i = 1; i <= 256; i++) {
+ cftab[i] += cftab[i - 1];
+ }
+
+ for (i = 0; i <= last; i++) {
+ ch = (char) ll8[i];
+ tt[cftab[ch]] = i;
+ cftab[ch]++;
+ }
+ cftab = null;
+
+ tPos = tt[origPtr];
+
+ count = 0;
+ i2 = 0;
+ ch2 = 256; /* not a char and not EOF */
+
+ if (blockRandomised) {
+ rNToGo = 0;
+ rTPos = 0;
+ SetupRandPartA();
+ } else {
+ SetupNoRandPartA();
+ }
+ }
+
+ private void SetupRandPartA() {
+ if (i2 <= last) {
+ chPrev = ch2;
+ ch2 = ll8[tPos];
+ tPos = tt[tPos];
+ if (rNToGo == 0) {
+ rNToGo = BZip2Constants.rNums[rTPos];
+ rTPos++;
+ if (rTPos == 512) {
+ rTPos = 0;
+ }
+ }
+ rNToGo--;
+ ch2 ^= (int) ((rNToGo == 1) ? 1 : 0);
+ i2++;
+
+ currentChar = ch2;
+ currentState = RAND_PART_B_STATE;
+ mCrc.UpdateCRC(ch2);
+ } else {
+ EndBlock();
+ InitBlock();
+ SetupBlock();
+ }
+ }
+
+ private void SetupNoRandPartA() {
+ if (i2 <= last) {
+ chPrev = ch2;
+ ch2 = ll8[tPos];
+ tPos = tt[tPos];
+ i2++;
+
+ currentChar = ch2;
+ currentState = NO_RAND_PART_B_STATE;
+ mCrc.UpdateCRC(ch2);
+ } else {
+ EndBlock();
+ InitBlock();
+ SetupBlock();
+ }
+ }
+
+ private void SetupRandPartB() {
+ if (ch2 != chPrev) {
+ currentState = RAND_PART_A_STATE;
+ count = 1;
+ SetupRandPartA();
+ } else {
+ count++;
+ if (count >= 4) {
+ z = ll8[tPos];
+ tPos = tt[tPos];
+ if (rNToGo == 0) {
+ rNToGo = BZip2Constants.rNums[rTPos];
+ rTPos++;
+ if (rTPos == 512) {
+ rTPos = 0;
+ }
+ }
+ rNToGo--;
+ z ^= (char)((rNToGo == 1) ? 1 : 0);
+ j2 = 0;
+ currentState = RAND_PART_C_STATE;
+ SetupRandPartC();
+ } else {
+ currentState = RAND_PART_A_STATE;
+ SetupRandPartA();
+ }
+ }
+ }
+
+ private void SetupRandPartC() {
+ if (j2 < (int) z) {
+ currentChar = ch2;
+ mCrc.UpdateCRC(ch2);
+ j2++;
+ } else {
+ currentState = RAND_PART_A_STATE;
+ i2++;
+ count = 0;
+ SetupRandPartA();
+ }
+ }
+
+ private void SetupNoRandPartB() {
+ if (ch2 != chPrev) {
+ currentState = NO_RAND_PART_A_STATE;
+ count = 1;
+ SetupNoRandPartA();
+ } else {
+ count++;
+ if (count >= 4) {
+ z = ll8[tPos];
+ tPos = tt[tPos];
+ currentState = NO_RAND_PART_C_STATE;
+ j2 = 0;
+ SetupNoRandPartC();
+ } else {
+ currentState = NO_RAND_PART_A_STATE;
+ SetupNoRandPartA();
+ }
+ }
+ }
+
+ private void SetupNoRandPartC() {
+ if (j2 < (int) z) {
+ currentChar = ch2;
+ mCrc.UpdateCRC(ch2);
+ j2++;
+ } else {
+ currentState = NO_RAND_PART_A_STATE;
+ i2++;
+ count = 0;
+ SetupNoRandPartA();
+ }
+ }
+
+ private void SetDecompressStructureSizes(int newSize100k) {
+ if (!(0 <= newSize100k && newSize100k <= 9 && 0 <= blockSize100k
+ && blockSize100k <= 9)) {
+ // throw new IOException("Invalid block size");
+ }
+
+ blockSize100k = newSize100k;
+
+ if (newSize100k == 0) {
+ return;
+ }
+
+ int n = BZip2Constants.baseBlockSize * newSize100k;
+ ll8 = new char[n];
+ tt = new int[n];
+ }
+
+ public override void Flush() {
+ }
+
+ public override int Read(byte[] buffer, int offset, int count) {
+ int c = -1;
+ int k;
+ for (k = 0; k < count; ++k) {
+ c = ReadByte();
+ if (c == -1)
+ break;
+ buffer[k + offset] = (byte)c;
+ }
+ return k;
+ }
+
+ public override long Seek(long offset, SeekOrigin origin) {
+ return 0;
+ }
+
+ public override void SetLength(long value) {
+ }
+
+ public override void Write(byte[] buffer, int offset, int count) {
+ }
+
+ public override bool CanRead {
+ get {
+ return true;
+ }
+ }
+
+ public override bool CanSeek {
+ get {
+ return false;
+ }
+ }
+
+ public override bool CanWrite {
+ get {
+ return false;
+ }
+ }
+
+ public override long Length {
+ get {
+ return 0;
+ }
+ }
+
+ public override long Position {
+ get {
+ return 0;
+ }
+ set {
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Crypto/bzip2/src/CBZip2OutputStream.cs b/Crypto/bzip2/src/CBZip2OutputStream.cs
new file mode 100644
index 000000000..2c6bed1df
--- /dev/null
+++ b/Crypto/bzip2/src/CBZip2OutputStream.cs
@@ -0,0 +1,1696 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+/*
+ * This package is based on the work done by Keiron Liddle, Aftex Software
+ * to whom the Ant project is very grateful for his
+ * great code.
+ */
+
+using System;
+using System.IO;
+
+namespace Org.BouncyCastle.Apache.Bzip2
+{
+ /**
+ * An output stream that compresses into the BZip2 format (with the file
+ * header chars) into another stream.
+ *
+ * @author Keiron Liddle
+ *
+ * TODO: Update to BZip2 1.0.1
+ * NB: note this class has been modified to add a leading BZ to the
+ * start of the BZIP2 stream to make it compatible with other PGP programs.
+ */
+ public class CBZip2OutputStream : Stream
+ {
+ protected const int SETMASK = (1 << 21);
+ protected const int CLEARMASK = (~SETMASK);
+ protected const int GREATER_ICOST = 15;
+ protected const int LESSER_ICOST = 0;
+ protected const int SMALL_THRESH = 20;
+ protected const int DEPTH_THRESH = 10;
+
+ /*
+ If you are ever unlucky/improbable enough
+ to get a stack overflow whilst sorting,
+ increase the following constant and try
+ again. In practice I have never seen the
+ stack go above 27 elems, so the following
+ limit seems very generous.
+ */
+ protected const int QSORT_STACK_SIZE = 1000;
+ private bool finished;
+
+ private static void Panic() {
+ //System.out.Println("panic");
+ //throw new CError();
+ }
+
+ private void MakeMaps() {
+ int i;
+ nInUse = 0;
+ for (i = 0; i < 256; i++) {
+ if (inUse[i]) {
+ seqToUnseq[nInUse] = (char) i;
+ unseqToSeq[i] = (char) nInUse;
+ nInUse++;
+ }
+ }
+ }
+
+ protected static void HbMakeCodeLengths(char[] len, int[] freq,
+ int alphaSize, int maxLen) {
+ /*
+ Nodes and heap entries run from 1. Entry 0
+ for both the heap and nodes is a sentinel.
+ */
+ int nNodes, nHeap, n1, n2, i, j, k;
+ bool tooLong;
+
+ int[] heap = new int[BZip2Constants.MAX_ALPHA_SIZE + 2];
+ int[] weight = new int[BZip2Constants.MAX_ALPHA_SIZE * 2];
+ int[] parent = new int[BZip2Constants.MAX_ALPHA_SIZE * 2];
+
+ for (i = 0; i < alphaSize; i++) {
+ weight[i + 1] = (freq[i] == 0 ? 1 : freq[i]) << 8;
+ }
+
+ while (true) {
+ nNodes = alphaSize;
+ nHeap = 0;
+
+ heap[0] = 0;
+ weight[0] = 0;
+ parent[0] = -2;
+
+ for (i = 1; i <= alphaSize; i++) {
+ parent[i] = -1;
+ nHeap++;
+ heap[nHeap] = i;
+ {
+ int zz, tmp;
+ zz = nHeap;
+ tmp = heap[zz];
+ while (weight[tmp] < weight[heap[zz >> 1]]) {
+ heap[zz] = heap[zz >> 1];
+ zz >>= 1;
+ }
+ heap[zz] = tmp;
+ }
+ }
+ if (!(nHeap < (BZip2Constants.MAX_ALPHA_SIZE + 2))) {
+ Panic();
+ }
+
+ while (nHeap > 1) {
+ n1 = heap[1];
+ heap[1] = heap[nHeap];
+ nHeap--;
+ {
+ int zz = 0, yy = 0, tmp = 0;
+ zz = 1;
+ tmp = heap[zz];
+ while (true) {
+ yy = zz << 1;
+ if (yy > nHeap) {
+ break;
+ }
+ if (yy < nHeap
+ && weight[heap[yy + 1]] < weight[heap[yy]]) {
+ yy++;
+ }
+ if (weight[tmp] < weight[heap[yy]]) {
+ break;
+ }
+ heap[zz] = heap[yy];
+ zz = yy;
+ }
+ heap[zz] = tmp;
+ }
+ n2 = heap[1];
+ heap[1] = heap[nHeap];
+ nHeap--;
+ {
+ int zz = 0, yy = 0, tmp = 0;
+ zz = 1;
+ tmp = heap[zz];
+ while (true) {
+ yy = zz << 1;
+ if (yy > nHeap) {
+ break;
+ }
+ if (yy < nHeap
+ && weight[heap[yy + 1]] < weight[heap[yy]]) {
+ yy++;
+ }
+ if (weight[tmp] < weight[heap[yy]]) {
+ break;
+ }
+ heap[zz] = heap[yy];
+ zz = yy;
+ }
+ heap[zz] = tmp;
+ }
+ nNodes++;
+ parent[n1] = parent[n2] = nNodes;
+
+ weight[nNodes] = (int)((uint)((weight[n1] & 0xffffff00)
+ + (weight[n2] & 0xffffff00))
+ | (uint)(1 + (((weight[n1] & 0x000000ff) >
+ (weight[n2] & 0x000000ff)) ?
+ (weight[n1] & 0x000000ff) :
+ (weight[n2] & 0x000000ff))));
+
+ parent[nNodes] = -1;
+ nHeap++;
+ heap[nHeap] = nNodes;
+ {
+ int zz = 0, tmp = 0;
+ zz = nHeap;
+ tmp = heap[zz];
+ while (weight[tmp] < weight[heap[zz >> 1]]) {
+ heap[zz] = heap[zz >> 1];
+ zz >>= 1;
+ }
+ heap[zz] = tmp;
+ }
+ }
+ if (!(nNodes < (BZip2Constants.MAX_ALPHA_SIZE * 2))) {
+ Panic();
+ }
+
+ tooLong = false;
+ for (i = 1; i <= alphaSize; i++) {
+ j = 0;
+ k = i;
+ while (parent[k] >= 0) {
+ k = parent[k];
+ j++;
+ }
+ len[i - 1] = (char) j;
+ if (j > maxLen) {
+ tooLong = true;
+ }
+ }
+
+ if (!tooLong) {
+ break;
+ }
+
+ for (i = 1; i < alphaSize; i++) {
+ j = weight[i] >> 8;
+ j = 1 + (j / 2);
+ weight[i] = j << 8;
+ }
+ }
+ }
+
+ /*
+ index of the last char in the block, so
+ the block size == last + 1.
+ */
+ int last;
+
+ /*
+ index in zptr[] of original string after sorting.
+ */
+ int origPtr;
+
+ /*
+ always: in the range 0 .. 9.
+ The current block size is 100000 * this number.
+ */
+ int blockSize100k;
+
+ bool blockRandomised;
+
+ int bytesOut;
+ int bsBuff;
+ int bsLive;
+ CRC mCrc = new CRC();
+
+ private bool[] inUse = new bool[256];
+ private int nInUse;
+
+ private char[] seqToUnseq = new char[256];
+ private char[] unseqToSeq = new char[256];
+
+ private char[] selector = new char[BZip2Constants.MAX_SELECTORS];
+ private char[] selectorMtf = new char[BZip2Constants.MAX_SELECTORS];
+
+ private char[] block;
+ private int[] quadrant;
+ private int[] zptr;
+ private short[] szptr;
+ private int[] ftab;
+
+ private int nMTF;
+
+ private int[] mtfFreq = new int[BZip2Constants.MAX_ALPHA_SIZE];
+
+ /*
+ * Used when sorting. If too many long comparisons
+ * happen, we stop sorting, randomise the block
+ * slightly, and try again.
+ */
+ private int workFactor;
+ private int workDone;
+ private int workLimit;
+ private bool firstAttempt;
+ private int nBlocksRandomised;
+
+ private int currentChar = -1;
+ private int runLength = 0;
+
+ public CBZip2OutputStream(Stream inStream) : this(inStream, 9) {
+ }
+
+ public CBZip2OutputStream(Stream inStream, int inBlockSize)
+ {
+ block = null;
+ quadrant = null;
+ zptr = null;
+ ftab = null;
+
+ inStream.WriteByte((byte)'B');
+ inStream.WriteByte((byte)'Z');
+
+ BsSetStream(inStream);
+
+ workFactor = 50;
+ if (inBlockSize > 9) {
+ inBlockSize = 9;
+ }
+ if (inBlockSize < 1) {
+ inBlockSize = 1;
+ }
+ blockSize100k = inBlockSize;
+ AllocateCompressStructures();
+ Initialize();
+ InitBlock();
+ }
+
+ /**
+ *
+ * modified by Oliver Merkel, 010128
+ *
+ */
+ public override void WriteByte(byte bv) {
+ int b = (256 + bv) % 256;
+ if (currentChar != -1) {
+ if (currentChar == b) {
+ runLength++;
+ if (runLength > 254) {
+ WriteRun();
+ currentChar = -1;
+ runLength = 0;
+ }
+ } else {
+ WriteRun();
+ runLength = 1;
+ currentChar = b;
+ }
+ } else {
+ currentChar = b;
+ runLength++;
+ }
+ }
+
+ private void WriteRun() {
+ if (last < allowableBlockSize) {
+ inUse[currentChar] = true;
+ for (int i = 0; i < runLength; i++) {
+ mCrc.UpdateCRC((char) currentChar);
+ }
+ switch (runLength) {
+ case 1:
+ last++;
+ block[last + 1] = (char) currentChar;
+ break;
+ case 2:
+ last++;
+ block[last + 1] = (char) currentChar;
+ last++;
+ block[last + 1] = (char) currentChar;
+ break;
+ case 3:
+ last++;
+ block[last + 1] = (char) currentChar;
+ last++;
+ block[last + 1] = (char) currentChar;
+ last++;
+ block[last + 1] = (char) currentChar;
+ break;
+ default:
+ inUse[runLength - 4] = true;
+ last++;
+ block[last + 1] = (char) currentChar;
+ last++;
+ block[last + 1] = (char) currentChar;
+ last++;
+ block[last + 1] = (char) currentChar;
+ last++;
+ block[last + 1] = (char) currentChar;
+ last++;
+ block[last + 1] = (char) (runLength - 4);
+ break;
+ }
+ } else {
+ EndBlock();
+ InitBlock();
+ WriteRun();
+ }
+ }
+
+ bool closed = false;
+
+// protected void Finalize() {
+// Close();
+// }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ if (closed)
+ {
+ return;
+ }
+
+ Finish();
+
+ closed = true;
+ base.Dispose(disposing);
+ bsStream.Dispose();
+ }
+ }
+
+ public void Finish() {
+ if (finished) {
+ return;
+ }
+
+ if (runLength > 0) {
+ WriteRun();
+ }
+ currentChar = -1;
+ EndBlock();
+ EndCompression();
+ finished = true;
+ Flush();
+ }
+
+ public override void Flush() {
+ bsStream.Flush();
+ }
+
+ private int blockCRC, combinedCRC;
+
+ private void Initialize() {
+ bytesOut = 0;
+ nBlocksRandomised = 0;
+
+ /* Write `magic' bytes h indicating file-format == huffmanised,
+ followed by a digit indicating blockSize100k.
+ */
+ BsPutUChar('h');
+ BsPutUChar('0' + blockSize100k);
+
+ combinedCRC = 0;
+ }
+
+ private int allowableBlockSize;
+
+ private void InitBlock() {
+ // blockNo++;
+ mCrc.InitialiseCRC();
+ last = -1;
+ // ch = 0;
+
+ for (int i = 0; i < 256; i++) {
+ inUse[i] = false;
+ }
+
+ /* 20 is just a paranoia constant */
+ allowableBlockSize = BZip2Constants.baseBlockSize * blockSize100k - 20;
+ }
+
+ private void EndBlock() {
+ blockCRC = mCrc.GetFinalCRC();
+ combinedCRC = (combinedCRC << 1) | (int)(((uint)combinedCRC) >> 31);
+ combinedCRC ^= blockCRC;
+
+ /* sort the block and establish posn of original string */
+ DoReversibleTransformation();
+
+ /*
+ A 6-byte block header, the value chosen arbitrarily
+ as 0x314159265359 :-). A 32 bit value does not really
+ give a strong enough guarantee that the value will not
+ appear by chance in the compressed datastream. Worst-case
+ probability of this event, for a 900k block, is about
+ 2.0e-3 for 32 bits, 1.0e-5 for 40 bits and 4.0e-8 for 48 bits.
+ For a compressed file of size 100Gb -- about 100000 blocks --
+ only a 48-bit marker will do. NB: normal compression/
+ decompression do *not* rely on these statistical properties.
+ They are only important when trying to recover blocks from
+ damaged files.
+ */
+ BsPutUChar(0x31);
+ BsPutUChar(0x41);
+ BsPutUChar(0x59);
+ BsPutUChar(0x26);
+ BsPutUChar(0x53);
+ BsPutUChar(0x59);
+
+ /* Now the block's CRC, so it is in a known place. */
+ BsPutint(blockCRC);
+
+ /* Now a single bit indicating randomisation. */
+ if (blockRandomised) {
+ BsW(1, 1);
+ nBlocksRandomised++;
+ } else {
+ BsW(1, 0);
+ }
+
+ /* Finally, block's contents proper. */
+ MoveToFrontCodeAndSend();
+ }
+
+ private void EndCompression() {
+ /*
+ Now another magic 48-bit number, 0x177245385090, to
+ indicate the end of the last block. (Sqrt(pi), if
+ you want to know. I did want to use e, but it contains
+ too much repetition -- 27 18 28 18 28 46 -- for me
+ to feel statistically comfortable. Call me paranoid.)
+ */
+ BsPutUChar(0x17);
+ BsPutUChar(0x72);
+ BsPutUChar(0x45);
+ BsPutUChar(0x38);
+ BsPutUChar(0x50);
+ BsPutUChar(0x90);
+
+ BsPutint(combinedCRC);
+
+ BsFinishedWithStream();
+ }
+
+ private void HbAssignCodes(int[] code, char[] length, int minLen,
+ int maxLen, int alphaSize) {
+ int n, vec, i;
+
+ vec = 0;
+ for (n = minLen; n <= maxLen; n++) {
+ for (i = 0; i < alphaSize; i++) {
+ if (length[i] == n) {
+ code[i] = vec;
+ vec++;
+ }
+ };
+ vec <<= 1;
+ }
+ }
+
+ private void BsSetStream(Stream f) {
+ bsStream = f;
+ bsLive = 0;
+ bsBuff = 0;
+ bytesOut = 0;
+ }
+
+ private void BsFinishedWithStream() {
+ while (bsLive > 0) {
+ int ch = (bsBuff >> 24);
+ try {
+ bsStream.WriteByte((byte)ch); // write 8-bit
+ } catch (IOException e) {
+ throw e;
+ }
+ bsBuff <<= 8;
+ bsLive -= 8;
+ bytesOut++;
+ }
+ }
+
+ private void BsW(int n, int v) {
+ while (bsLive >= 8) {
+ int ch = (bsBuff >> 24);
+ try {
+ bsStream.WriteByte((byte)ch); // write 8-bit
+ } catch (IOException e) {
+ throw e;
+ }
+ bsBuff <<= 8;
+ bsLive -= 8;
+ bytesOut++;
+ }
+ bsBuff |= (v << (32 - bsLive - n));
+ bsLive += n;
+ }
+
+ private void BsPutUChar(int c) {
+ BsW(8, c);
+ }
+
+ private void BsPutint(int u) {
+ BsW(8, (u >> 24) & 0xff);
+ BsW(8, (u >> 16) & 0xff);
+ BsW(8, (u >> 8) & 0xff);
+ BsW(8, u & 0xff);
+ }
+
+ private void BsPutIntVS(int numBits, int c) {
+ BsW(numBits, c);
+ }
+
+ private void SendMTFValues() {
+ char[][] len = CBZip2InputStream.InitCharArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE);
+
+ int v, t, i, j, gs, ge, totc, bt, bc, iter;
+ int nSelectors = 0, alphaSize, minLen, maxLen, selCtr;
+ int nGroups;
+
+ alphaSize = nInUse + 2;
+ for (t = 0; t < BZip2Constants.N_GROUPS; t++) {
+ for (v = 0; v < alphaSize; v++) {
+ len[t][v] = (char) GREATER_ICOST;
+ }
+ }
+
+ /* Decide how many coding tables to use */
+ if (nMTF <= 0) {
+ Panic();
+ }
+
+ if (nMTF < 200) {
+ nGroups = 2;
+ } else if (nMTF < 600) {
+ nGroups = 3;
+ } else if (nMTF < 1200) {
+ nGroups = 4;
+ } else if (nMTF < 2400) {
+ nGroups = 5;
+ } else {
+ nGroups = 6;
+ }
+
+ /* Generate an initial set of coding tables */ {
+ int nPart, remF, tFreq, aFreq;
+
+ nPart = nGroups;
+ remF = nMTF;
+ gs = 0;
+ while (nPart > 0) {
+ tFreq = remF / nPart;
+ ge = gs - 1;
+ aFreq = 0;
+ while (aFreq < tFreq && ge < alphaSize - 1) {
+ ge++;
+ aFreq += mtfFreq[ge];
+ }
+
+ if (ge > gs && nPart != nGroups && nPart != 1
+ && ((nGroups - nPart) % 2 == 1)) {
+ aFreq -= mtfFreq[ge];
+ ge--;
+ }
+
+ for (v = 0; v < alphaSize; v++) {
+ if (v >= gs && v <= ge) {
+ len[nPart - 1][v] = (char) LESSER_ICOST;
+ } else {
+ len[nPart - 1][v] = (char) GREATER_ICOST;
+ }
+ }
+
+ nPart--;
+ gs = ge + 1;
+ remF -= aFreq;
+ }
+ }
+
+ int[][] rfreq = CBZip2InputStream.InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE);
+ int[] fave = new int[BZip2Constants.N_GROUPS];
+ short[] cost = new short[BZip2Constants.N_GROUPS];
+ /*
+ Iterate up to N_ITERS times to improve the tables.
+ */
+ for (iter = 0; iter < BZip2Constants.N_ITERS; iter++) {
+ for (t = 0; t < nGroups; t++) {
+ fave[t] = 0;
+ }
+
+ for (t = 0; t < nGroups; t++) {
+ for (v = 0; v < alphaSize; v++) {
+ rfreq[t][v] = 0;
+ }
+ }
+
+ nSelectors = 0;
+ totc = 0;
+ gs = 0;
+ while (true) {
+
+ /* Set group start & end marks. */
+ if (gs >= nMTF) {
+ break;
+ }
+ ge = gs + BZip2Constants.G_SIZE - 1;
+ if (ge >= nMTF) {
+ ge = nMTF - 1;
+ }
+
+ /*
+ Calculate the cost of this group as coded
+ by each of the coding tables.
+ */
+ for (t = 0; t < nGroups; t++) {
+ cost[t] = 0;
+ }
+
+ if (nGroups == 6) {
+ short cost0, cost1, cost2, cost3, cost4, cost5;
+ cost0 = cost1 = cost2 = cost3 = cost4 = cost5 = 0;
+ for (i = gs; i <= ge; i++) {
+ short icv = szptr[i];
+ cost0 += (short)len[0][icv];
+ cost1 += (short)len[1][icv];
+ cost2 += (short)len[2][icv];
+ cost3 += (short)len[3][icv];
+ cost4 += (short)len[4][icv];
+ cost5 += (short)len[5][icv];
+ }
+ cost[0] = cost0;
+ cost[1] = cost1;
+ cost[2] = cost2;
+ cost[3] = cost3;
+ cost[4] = cost4;
+ cost[5] = cost5;
+ } else {
+ for (i = gs; i <= ge; i++) {
+ short icv = szptr[i];
+ for (t = 0; t < nGroups; t++) {
+ cost[t] += (short)len[t][icv];
+ }
+ }
+ }
+
+ /*
+ Find the coding table which is best for this group,
+ and record its identity in the selector table.
+ */
+ bc = 999999999;
+ bt = -1;
+ for (t = 0; t < nGroups; t++) {
+ if (cost[t] < bc) {
+ bc = cost[t];
+ bt = t;
+ }
+ };
+ totc += bc;
+ fave[bt]++;
+ selector[nSelectors] = (char) bt;
+ nSelectors++;
+
+ /*
+ Increment the symbol frequencies for the selected table.
+ */
+ for (i = gs; i <= ge; i++) {
+ rfreq[bt][szptr[i]]++;
+ }
+
+ gs = ge + 1;
+ }
+
+ /*
+ Recompute the tables based on the accumulated frequencies.
+ */
+ for (t = 0; t < nGroups; t++) {
+ HbMakeCodeLengths(len[t], rfreq[t], alphaSize, 20);
+ }
+ }
+
+ rfreq = null;
+ fave = null;
+ cost = null;
+
+ if (!(nGroups < 8)) {
+ Panic();
+ }
+ if (!(nSelectors < 32768 && nSelectors <= (2 + (900000 / BZip2Constants.G_SIZE)))) {
+ Panic();
+ }
+
+
+ /* Compute MTF values for the selectors. */
+ {
+ char[] pos = new char[BZip2Constants.N_GROUPS];
+ char ll_i, tmp2, tmp;
+ for (i = 0; i < nGroups; i++) {
+ pos[i] = (char) i;
+ }
+ for (i = 0; i < nSelectors; i++) {
+ ll_i = selector[i];
+ j = 0;
+ tmp = pos[j];
+ while (ll_i != tmp) {
+ j++;
+ tmp2 = tmp;
+ tmp = pos[j];
+ pos[j] = tmp2;
+ }
+ pos[0] = tmp;
+ selectorMtf[i] = (char) j;
+ }
+ }
+
+ int[][] code = CBZip2InputStream.InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE);
+
+ /* Assign actual codes for the tables. */
+ for (t = 0; t < nGroups; t++) {
+ minLen = 32;
+ maxLen = 0;
+ for (i = 0; i < alphaSize; i++) {
+ if (len[t][i] > maxLen) {
+ maxLen = len[t][i];
+ }
+ if (len[t][i] < minLen) {
+ minLen = len[t][i];
+ }
+ }
+ if (maxLen > 20) {
+ Panic();
+ }
+ if (minLen < 1) {
+ Panic();
+ }
+ HbAssignCodes(code[t], len[t], minLen, maxLen, alphaSize);
+ }
+
+ /* Transmit the mapping table. */
+ {
+ bool[] inUse16 = new bool[16];
+ for (i = 0; i < 16; i++) {
+ inUse16[i] = false;
+ for (j = 0; j < 16; j++) {
+ if (inUse[i * 16 + j]) {
+ inUse16[i] = true;
+ }
+ }
+ }
+
+ for (i = 0; i < 16; i++) {
+ if (inUse16[i]) {
+ BsW(1, 1);
+ } else {
+ BsW(1, 0);
+ }
+ }
+
+ for (i = 0; i < 16; i++) {
+ if (inUse16[i]) {
+ for (j = 0; j < 16; j++) {
+ if (inUse[i * 16 + j]) {
+ BsW(1, 1);
+ } else {
+ BsW(1, 0);
+ }
+ }
+ }
+ }
+
+ }
+
+ /* Now the selectors. */
+ BsW(3, nGroups);
+ BsW(15, nSelectors);
+ for (i = 0; i < nSelectors; i++) {
+ for (j = 0; j < selectorMtf[i]; j++) {
+ BsW(1, 1);
+ }
+ BsW(1, 0);
+ }
+
+ /* Now the coding tables. */
+ for (t = 0; t < nGroups; t++) {
+ int curr = len[t][0];
+ BsW(5, curr);
+ for (i = 0; i < alphaSize; i++) {
+ while (curr < len[t][i]) {
+ BsW(2, 2);
+ curr++; /* 10 */
+ }
+ while (curr > len[t][i]) {
+ BsW(2, 3);
+ curr--; /* 11 */
+ }
+ BsW(1, 0);
+ }
+ }
+
+ /* And finally, the block data proper */
+ selCtr = 0;
+ gs = 0;
+ while (true) {
+ if (gs >= nMTF) {
+ break;
+ }
+ ge = gs + BZip2Constants.G_SIZE - 1;
+ if (ge >= nMTF) {
+ ge = nMTF - 1;
+ }
+ for (i = gs; i <= ge; i++) {
+ BsW(len[selector[selCtr]][szptr[i]],
+ code[selector[selCtr]][szptr[i]]);
+ }
+
+ gs = ge + 1;
+ selCtr++;
+ }
+ if (!(selCtr == nSelectors)) {
+ Panic();
+ }
+ }
+
+ private void MoveToFrontCodeAndSend() {
+ BsPutIntVS(24, origPtr);
+ GenerateMTFValues();
+ SendMTFValues();
+ }
+
+ private Stream bsStream;
+
+ private void SimpleSort(int lo, int hi, int d) {
+ int i, j, h, bigN, hp;
+ int v;
+
+ bigN = hi - lo + 1;
+ if (bigN < 2) {
+ return;
+ }
+
+ hp = 0;
+ while (incs[hp] < bigN) {
+ hp++;
+ }
+ hp--;
+
+ for (; hp >= 0; hp--) {
+ h = incs[hp];
+
+ i = lo + h;
+ while (true) {
+ /* copy 1 */
+ if (i > hi) {
+ break;
+ }
+ v = zptr[i];
+ j = i;
+ while (FullGtU(zptr[j - h] + d, v + d)) {
+ zptr[j] = zptr[j - h];
+ j = j - h;
+ if (j <= (lo + h - 1)) {
+ break;
+ }
+ }
+ zptr[j] = v;
+ i++;
+
+ /* copy 2 */
+ if (i > hi) {
+ break;
+ }
+ v = zptr[i];
+ j = i;
+ while (FullGtU(zptr[j - h] + d, v + d)) {
+ zptr[j] = zptr[j - h];
+ j = j - h;
+ if (j <= (lo + h - 1)) {
+ break;
+ }
+ }
+ zptr[j] = v;
+ i++;
+
+ /* copy 3 */
+ if (i > hi) {
+ break;
+ }
+ v = zptr[i];
+ j = i;
+ while (FullGtU(zptr[j - h] + d, v + d)) {
+ zptr[j] = zptr[j - h];
+ j = j - h;
+ if (j <= (lo + h - 1)) {
+ break;
+ }
+ }
+ zptr[j] = v;
+ i++;
+
+ if (workDone > workLimit && firstAttempt) {
+ return;
+ }
+ }
+ }
+ }
+
+ private void Vswap(int p1, int p2, int n) {
+ int temp = 0;
+ while (n > 0) {
+ temp = zptr[p1];
+ zptr[p1] = zptr[p2];
+ zptr[p2] = temp;
+ p1++;
+ p2++;
+ n--;
+ }
+ }
+
+ private char Med3(char a, char b, char c) {
+ char t;
+ if (a > b) {
+ t = a;
+ a = b;
+ b = t;
+ }
+ if (b > c) {
+ t = b;
+ b = c;
+ c = t;
+ }
+ if (a > b) {
+ b = a;
+ }
+ return b;
+ }
+
+ internal class StackElem {
+ internal int ll;
+ internal int hh;
+ internal int dd;
+ }
+
+ private void QSort3(int loSt, int hiSt, int dSt) {
+ int unLo, unHi, ltLo, gtHi, med, n, m;
+ int sp, lo, hi, d;
+ StackElem[] stack = new StackElem[QSORT_STACK_SIZE];
+ for (int count = 0; count < QSORT_STACK_SIZE; count++) {
+ stack[count] = new StackElem();
+ }
+
+ sp = 0;
+
+ stack[sp].ll = loSt;
+ stack[sp].hh = hiSt;
+ stack[sp].dd = dSt;
+ sp++;
+
+ while (sp > 0) {
+ if (sp >= QSORT_STACK_SIZE) {
+ Panic();
+ }
+
+ sp--;
+ lo = stack[sp].ll;
+ hi = stack[sp].hh;
+ d = stack[sp].dd;
+
+ if (hi - lo < SMALL_THRESH || d > DEPTH_THRESH) {
+ SimpleSort(lo, hi, d);
+ if (workDone > workLimit && firstAttempt) {
+ return;
+ }
+ continue;
+ }
+
+ med = Med3(block[zptr[lo] + d + 1],
+ block[zptr[hi ] + d + 1],
+ block[zptr[(lo + hi) >> 1] + d + 1]);
+
+ unLo = ltLo = lo;
+ unHi = gtHi = hi;
+
+ while (true) {
+ while (true) {
+ if (unLo > unHi) {
+ break;
+ }
+ n = ((int) block[zptr[unLo] + d + 1]) - med;
+ if (n == 0) {
+ int temp = 0;
+ temp = zptr[unLo];
+ zptr[unLo] = zptr[ltLo];
+ zptr[ltLo] = temp;
+ ltLo++;
+ unLo++;
+ continue;
+ };
+ if (n > 0) {
+ break;
+ }
+ unLo++;
+ }
+ while (true) {
+ if (unLo > unHi) {
+ break;
+ }
+ n = ((int) block[zptr[unHi] + d + 1]) - med;
+ if (n == 0) {
+ int temp = 0;
+ temp = zptr[unHi];
+ zptr[unHi] = zptr[gtHi];
+ zptr[gtHi] = temp;
+ gtHi--;
+ unHi--;
+ continue;
+ };
+ if (n < 0) {
+ break;
+ }
+ unHi--;
+ }
+ if (unLo > unHi) {
+ break;
+ }
+ int tempx = zptr[unLo];
+ zptr[unLo] = zptr[unHi];
+ zptr[unHi] = tempx;
+ unLo++;
+ unHi--;
+ }
+
+ if (gtHi < ltLo) {
+ stack[sp].ll = lo;
+ stack[sp].hh = hi;
+ stack[sp].dd = d + 1;
+ sp++;
+ continue;
+ }
+
+ n = ((ltLo - lo) < (unLo - ltLo)) ? (ltLo - lo) : (unLo - ltLo);
+ Vswap(lo, unLo - n, n);
+ m = ((hi - gtHi) < (gtHi - unHi)) ? (hi - gtHi) : (gtHi - unHi);
+ Vswap(unLo, hi - m + 1, m);
+
+ n = lo + unLo - ltLo - 1;
+ m = hi - (gtHi - unHi) + 1;
+
+ stack[sp].ll = lo;
+ stack[sp].hh = n;
+ stack[sp].dd = d;
+ sp++;
+
+ stack[sp].ll = n + 1;
+ stack[sp].hh = m - 1;
+ stack[sp].dd = d + 1;
+ sp++;
+
+ stack[sp].ll = m;
+ stack[sp].hh = hi;
+ stack[sp].dd = d;
+ sp++;
+ }
+ }
+
+ private void MainSort() {
+ int i, j, ss, sb;
+ int[] runningOrder = new int[256];
+ int[] copy = new int[256];
+ bool[] bigDone = new bool[256];
+ int c1, c2;
+ int numQSorted;
+
+ /*
+ In the various block-sized structures, live data runs
+ from 0 to last+NUM_OVERSHOOT_BYTES inclusive. First,
+ set up the overshoot area for block.
+ */
+
+ // if (verbosity >= 4) fprintf ( stderr, " sort initialise ...\n" );
+ for (i = 0; i < BZip2Constants.NUM_OVERSHOOT_BYTES; i++) {
+ block[last + i + 2] = block[(i % (last + 1)) + 1];
+ }
+ for (i = 0; i <= last + BZip2Constants.NUM_OVERSHOOT_BYTES; i++) {
+ quadrant[i] = 0;
+ }
+
+ block[0] = (char) (block[last + 1]);
+
+ if (last < 4000) {
+ /*
+ Use SimpleSort(), since the full sorting mechanism
+ has quite a large constant overhead.
+ */
+ for (i = 0; i <= last; i++) {
+ zptr[i] = i;
+ }
+ firstAttempt = false;
+ workDone = workLimit = 0;
+ SimpleSort(0, last, 0);
+ } else {
+ numQSorted = 0;
+ for (i = 0; i <= 255; i++) {
+ bigDone[i] = false;
+ }
+
+ for (i = 0; i <= 65536; i++) {
+ ftab[i] = 0;
+ }
+
+ c1 = block[0];
+ for (i = 0; i <= last; i++) {
+ c2 = block[i + 1];
+ ftab[(c1 << 8) + c2]++;
+ c1 = c2;
+ }
+
+ for (i = 1; i <= 65536; i++) {
+ ftab[i] += ftab[i - 1];
+ }
+
+ c1 = block[1];
+ for (i = 0; i < last; i++) {
+ c2 = block[i + 2];
+ j = (c1 << 8) + c2;
+ c1 = c2;
+ ftab[j]--;
+ zptr[ftab[j]] = i;
+ }
+
+ j = ((block[last + 1]) << 8) + (block[1]);
+ ftab[j]--;
+ zptr[ftab[j]] = last;
+
+ /*
+ Now ftab contains the first loc of every small bucket.
+ Calculate the running order, from smallest to largest
+ big bucket.
+ */
+
+ for (i = 0; i <= 255; i++) {
+ runningOrder[i] = i;
+ }
+
+ {
+ int vv;
+ int h = 1;
+ do {
+ h = 3 * h + 1;
+ }
+ while (h <= 256);
+ do {
+ h = h / 3;
+ for (i = h; i <= 255; i++) {
+ vv = runningOrder[i];
+ j = i;
+ while ((ftab[((runningOrder[j - h]) + 1) << 8]
+ - ftab[(runningOrder[j - h]) << 8]) >
+ (ftab[((vv) + 1) << 8] - ftab[(vv) << 8])) {
+ runningOrder[j] = runningOrder[j - h];
+ j = j - h;
+ if (j <= (h - 1)) {
+ break;
+ }
+ }
+ runningOrder[j] = vv;
+ }
+ } while (h != 1);
+ }
+
+ /*
+ The main sorting loop.
+ */
+ for (i = 0; i <= 255; i++) {
+
+ /*
+ Process big buckets, starting with the least full.
+ */
+ ss = runningOrder[i];
+
+ /*
+ Complete the big bucket [ss] by quicksorting
+ any unsorted small buckets [ss, j]. Hopefully
+ previous pointer-scanning phases have already
+ completed many of the small buckets [ss, j], so
+ we don't have to sort them at all.
+ */
+ for (j = 0; j <= 255; j++) {
+ sb = (ss << 8) + j;
+ if (!((ftab[sb] & SETMASK) == SETMASK)) {
+ int lo = ftab[sb] & CLEARMASK;
+ int hi = (ftab[sb + 1] & CLEARMASK) - 1;
+ if (hi > lo) {
+ QSort3(lo, hi, 2);
+ numQSorted += (hi - lo + 1);
+ if (workDone > workLimit && firstAttempt) {
+ return;
+ }
+ }
+ ftab[sb] |= SETMASK;
+ }
+ }
+
+ /*
+ The ss big bucket is now done. Record this fact,
+ and update the quadrant descriptors. Remember to
+ update quadrants in the overshoot area too, if
+ necessary. The "if (i < 255)" test merely skips
+ this updating for the last bucket processed, since
+ updating for the last bucket is pointless.
+ */
+ bigDone[ss] = true;
+
+ if (i < 255) {
+ int bbStart = ftab[ss << 8] & CLEARMASK;
+ int bbSize = (ftab[(ss + 1) << 8] & CLEARMASK) - bbStart;
+ int shifts = 0;
+
+ while ((bbSize >> shifts) > 65534) {
+ shifts++;
+ }
+
+ for (j = 0; j < bbSize; j++) {
+ int a2update = zptr[bbStart + j];
+ int qVal = (j >> shifts);
+ quadrant[a2update] = qVal;
+ if (a2update < BZip2Constants.NUM_OVERSHOOT_BYTES) {
+ quadrant[a2update + last + 1] = qVal;
+ }
+ }
+
+ if (!(((bbSize - 1) >> shifts) <= 65535)) {
+ Panic();
+ }
+ }
+
+ /*
+ Now scan this big bucket so as to synthesise the
+ sorted order for small buckets [t, ss] for all t != ss.
+ */
+ for (j = 0; j <= 255; j++) {
+ copy[j] = ftab[(j << 8) + ss] & CLEARMASK;
+ }
+
+ for (j = ftab[ss << 8] & CLEARMASK;
+ j < (ftab[(ss + 1) << 8] & CLEARMASK); j++) {
+ c1 = block[zptr[j]];
+ if (!bigDone[c1]) {
+ zptr[copy[c1]] = zptr[j] == 0 ? last : zptr[j] - 1;
+ copy[c1]++;
+ }
+ }
+
+ for (j = 0; j <= 255; j++) {
+ ftab[(j << 8) + ss] |= SETMASK;
+ }
+ }
+ }
+ }
+
+ private void RandomiseBlock() {
+ int i;
+ int rNToGo = 0;
+ int rTPos = 0;
+ for (i = 0; i < 256; i++) {
+ inUse[i] = false;
+ }
+
+ for (i = 0; i <= last; i++) {
+ if (rNToGo == 0) {
+ rNToGo = (char) BZip2Constants.rNums[rTPos];
+ rTPos++;
+ if (rTPos == 512) {
+ rTPos = 0;
+ }
+ }
+ rNToGo--;
+ block[i + 1] ^= (char)((rNToGo == 1) ? 1 : 0);
+ // handle 16 bit signed numbers
+ block[i + 1] &= (char)0xFF;
+
+ inUse[block[i + 1]] = true;
+ }
+ }
+
+ private void DoReversibleTransformation() {
+ int i;
+
+ workLimit = workFactor * last;
+ workDone = 0;
+ blockRandomised = false;
+ firstAttempt = true;
+
+ MainSort();
+
+ if (workDone > workLimit && firstAttempt) {
+ RandomiseBlock();
+ workLimit = workDone = 0;
+ blockRandomised = true;
+ firstAttempt = false;
+ MainSort();
+ }
+
+ origPtr = -1;
+ for (i = 0; i <= last; i++) {
+ if (zptr[i] == 0) {
+ origPtr = i;
+ break;
+ }
+ };
+
+ if (origPtr == -1) {
+ Panic();
+ }
+ }
+
+ private bool FullGtU(int i1, int i2) {
+ int k;
+ char c1, c2;
+ int s1, s2;
+
+ c1 = block[i1 + 1];
+ c2 = block[i2 + 1];
+ if (c1 != c2) {
+ return (c1 > c2);
+ }
+ i1++;
+ i2++;
+
+ c1 = block[i1 + 1];
+ c2 = block[i2 + 1];
+ if (c1 != c2) {
+ return (c1 > c2);
+ }
+ i1++;
+ i2++;
+
+ c1 = block[i1 + 1];
+ c2 = block[i2 + 1];
+ if (c1 != c2) {
+ return (c1 > c2);
+ }
+ i1++;
+ i2++;
+
+ c1 = block[i1 + 1];
+ c2 = block[i2 + 1];
+ if (c1 != c2) {
+ return (c1 > c2);
+ }
+ i1++;
+ i2++;
+
+ c1 = block[i1 + 1];
+ c2 = block[i2 + 1];
+ if (c1 != c2) {
+ return (c1 > c2);
+ }
+ i1++;
+ i2++;
+
+ c1 = block[i1 + 1];
+ c2 = block[i2 + 1];
+ if (c1 != c2) {
+ return (c1 > c2);
+ }
+ i1++;
+ i2++;
+
+ k = last + 1;
+
+ do {
+ c1 = block[i1 + 1];
+ c2 = block[i2 + 1];
+ if (c1 != c2) {
+ return (c1 > c2);
+ }
+ s1 = quadrant[i1];
+ s2 = quadrant[i2];
+ if (s1 != s2) {
+ return (s1 > s2);
+ }
+ i1++;
+ i2++;
+
+ c1 = block[i1 + 1];
+ c2 = block[i2 + 1];
+ if (c1 != c2) {
+ return (c1 > c2);
+ }
+ s1 = quadrant[i1];
+ s2 = quadrant[i2];
+ if (s1 != s2) {
+ return (s1 > s2);
+ }
+ i1++;
+ i2++;
+
+ c1 = block[i1 + 1];
+ c2 = block[i2 + 1];
+ if (c1 != c2) {
+ return (c1 > c2);
+ }
+ s1 = quadrant[i1];
+ s2 = quadrant[i2];
+ if (s1 != s2) {
+ return (s1 > s2);
+ }
+ i1++;
+ i2++;
+
+ c1 = block[i1 + 1];
+ c2 = block[i2 + 1];
+ if (c1 != c2) {
+ return (c1 > c2);
+ }
+ s1 = quadrant[i1];
+ s2 = quadrant[i2];
+ if (s1 != s2) {
+ return (s1 > s2);
+ }
+ i1++;
+ i2++;
+
+ if (i1 > last) {
+ i1 -= last;
+ i1--;
+ };
+ if (i2 > last) {
+ i2 -= last;
+ i2--;
+ };
+
+ k -= 4;
+ workDone++;
+ } while (k >= 0);
+
+ return false;
+ }
+
+ /*
+ Knuth's increments seem to work better
+ than Incerpi-Sedgewick here. Possibly
+ because the number of elems to sort is
+ usually small, typically <= 20.
+ */
+ private int[] incs = { 1, 4, 13, 40, 121, 364, 1093, 3280,
+ 9841, 29524, 88573, 265720,
+ 797161, 2391484 };
+
+ private void AllocateCompressStructures() {
+ int n = BZip2Constants.baseBlockSize * blockSize100k;
+ block = new char[(n + 1 + BZip2Constants.NUM_OVERSHOOT_BYTES)];
+ quadrant = new int[(n + BZip2Constants.NUM_OVERSHOOT_BYTES)];
+ zptr = new int[n];
+ ftab = new int[65537];
+
+ if (block == null || quadrant == null || zptr == null
+ || ftab == null) {
+ //int totalDraw = (n + 1 + NUM_OVERSHOOT_BYTES) + (n + NUM_OVERSHOOT_BYTES) + n + 65537;
+ //compressOutOfMemory ( totalDraw, n );
+ }
+
+ /*
+ The back end needs a place to store the MTF values
+ whilst it calculates the coding tables. We could
+ put them in the zptr array. However, these values
+ will fit in a short, so we overlay szptr at the
+ start of zptr, in the hope of reducing the number
+ of cache misses induced by the multiple traversals
+ of the MTF values when calculating coding tables.
+ Seems to improve compression speed by about 1%.
+ */
+ // szptr = zptr;
+
+
+ szptr = new short[2 * n];
+ }
+
+ private void GenerateMTFValues() {
+ char[] yy = new char[256];
+ int i, j;
+ char tmp;
+ char tmp2;
+ int zPend;
+ int wr;
+ int EOB;
+
+ MakeMaps();
+ EOB = nInUse + 1;
+
+ for (i = 0; i <= EOB; i++) {
+ mtfFreq[i] = 0;
+ }
+
+ wr = 0;
+ zPend = 0;
+ for (i = 0; i < nInUse; i++) {
+ yy[i] = (char) i;
+ }
+
+
+ for (i = 0; i <= last; i++) {
+ char ll_i;
+
+ ll_i = unseqToSeq[block[zptr[i]]];
+
+ j = 0;
+ tmp = yy[j];
+ while (ll_i != tmp) {
+ j++;
+ tmp2 = tmp;
+ tmp = yy[j];
+ yy[j] = tmp2;
+ };
+ yy[0] = tmp;
+
+ if (j == 0) {
+ zPend++;
+ } else {
+ if (zPend > 0) {
+ zPend--;
+ while (true) {
+ switch (zPend % 2) {
+ case 0:
+ szptr[wr] = (short) BZip2Constants.RUNA;
+ wr++;
+ mtfFreq[BZip2Constants.RUNA]++;
+ break;
+ case 1:
+ szptr[wr] = (short) BZip2Constants.RUNB;
+ wr++;
+ mtfFreq[BZip2Constants.RUNB]++;
+ break;
+ };
+ if (zPend < 2) {
+ break;
+ }
+ zPend = (zPend - 2) / 2;
+ };
+ zPend = 0;
+ }
+ szptr[wr] = (short) (j + 1);
+ wr++;
+ mtfFreq[j + 1]++;
+ }
+ }
+
+ if (zPend > 0) {
+ zPend--;
+ while (true) {
+ switch (zPend % 2) {
+ case 0:
+ szptr[wr] = (short) BZip2Constants.RUNA;
+ wr++;
+ mtfFreq[BZip2Constants.RUNA]++;
+ break;
+ case 1:
+ szptr[wr] = (short) BZip2Constants.RUNB;
+ wr++;
+ mtfFreq[BZip2Constants.RUNB]++;
+ break;
+ }
+ if (zPend < 2) {
+ break;
+ }
+ zPend = (zPend - 2) / 2;
+ }
+ }
+
+ szptr[wr] = (short) EOB;
+ wr++;
+ mtfFreq[EOB]++;
+
+ nMTF = wr;
+ }
+
+ public override int Read(byte[] buffer, int offset, int count) {
+ return 0;
+ }
+
+ public override long Seek(long offset, SeekOrigin origin) {
+ return 0;
+ }
+
+ public override void SetLength(long value) {
+ }
+
+ public override void Write(byte[] buffer, int offset, int count) {
+ for (int k = 0; k < count; ++k) {
+ WriteByte(buffer[k + offset]);
+ }
+ }
+
+ public override bool CanRead {
+ get {
+ return false;
+ }
+ }
+
+ public override bool CanSeek {
+ get {
+ return false;
+ }
+ }
+
+ public override bool CanWrite {
+ get {
+ return true;
+ }
+ }
+
+ public override long Length {
+ get {
+ return 0;
+ }
+ }
+
+ public override long Position {
+ get {
+ return 0;
+ }
+ set {
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Crypto/bzip2/src/CRC.cs b/Crypto/bzip2/src/CRC.cs
new file mode 100644
index 000000000..278a9f336
--- /dev/null
+++ b/Crypto/bzip2/src/CRC.cs
@@ -0,0 +1,134 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+/*
+ * This package is based on the work done by Keiron Liddle), Aftex Software
+ * to whom the Ant project is very grateful for his
+ * great code.
+ */
+
+using System;
+
+namespace Org.BouncyCastle.Apache.Bzip2
+{
+ /**
+ * A simple class the hold and calculate the CRC for sanity checking
+ * of the data.
+ *
+ * @author Keiron Liddle
+ */
+ internal class CRC
+ {
+ public static readonly int[] crc32Table = {
+ unchecked((int)0x00000000), unchecked((int)0x04c11db7), unchecked((int)0x09823b6e), unchecked((int)0x0d4326d9),
+ unchecked((int)0x130476dc), unchecked((int)0x17c56b6b), unchecked((int)0x1a864db2), unchecked((int)0x1e475005),
+ unchecked((int)0x2608edb8), unchecked((int)0x22c9f00f), unchecked((int)0x2f8ad6d6), unchecked((int)0x2b4bcb61),
+ unchecked((int)0x350c9b64), unchecked((int)0x31cd86d3), unchecked((int)0x3c8ea00a), unchecked((int)0x384fbdbd),
+ unchecked((int)0x4c11db70), unchecked((int)0x48d0c6c7), unchecked((int)0x4593e01e), unchecked((int)0x4152fda9),
+ unchecked((int)0x5f15adac), unchecked((int)0x5bd4b01b), unchecked((int)0x569796c2), unchecked((int)0x52568b75),
+ unchecked((int)0x6a1936c8), unchecked((int)0x6ed82b7f), unchecked((int)0x639b0da6), unchecked((int)0x675a1011),
+ unchecked((int)0x791d4014), unchecked((int)0x7ddc5da3), unchecked((int)0x709f7b7a), unchecked((int)0x745e66cd),
+ unchecked((int)0x9823b6e0), unchecked((int)0x9ce2ab57), unchecked((int)0x91a18d8e), unchecked((int)0x95609039),
+ unchecked((int)0x8b27c03c), unchecked((int)0x8fe6dd8b), unchecked((int)0x82a5fb52), unchecked((int)0x8664e6e5),
+ unchecked((int)0xbe2b5b58), unchecked((int)0xbaea46ef), unchecked((int)0xb7a96036), unchecked((int)0xb3687d81),
+ unchecked((int)0xad2f2d84), unchecked((int)0xa9ee3033), unchecked((int)0xa4ad16ea), unchecked((int)0xa06c0b5d),
+ unchecked((int)0xd4326d90), unchecked((int)0xd0f37027), unchecked((int)0xddb056fe), unchecked((int)0xd9714b49),
+ unchecked((int)0xc7361b4c), unchecked((int)0xc3f706fb), unchecked((int)0xceb42022), unchecked((int)0xca753d95),
+ unchecked((int)0xf23a8028), unchecked((int)0xf6fb9d9f), unchecked((int)0xfbb8bb46), unchecked((int)0xff79a6f1),
+ unchecked((int)0xe13ef6f4), unchecked((int)0xe5ffeb43), unchecked((int)0xe8bccd9a), unchecked((int)0xec7dd02d),
+ unchecked((int)0x34867077), unchecked((int)0x30476dc0), unchecked((int)0x3d044b19), unchecked((int)0x39c556ae),
+ unchecked((int)0x278206ab), unchecked((int)0x23431b1c), unchecked((int)0x2e003dc5), unchecked((int)0x2ac12072),
+ unchecked((int)0x128e9dcf), unchecked((int)0x164f8078), unchecked((int)0x1b0ca6a1), unchecked((int)0x1fcdbb16),
+ unchecked((int)0x018aeb13), unchecked((int)0x054bf6a4), unchecked((int)0x0808d07d), unchecked((int)0x0cc9cdca),
+ unchecked((int)0x7897ab07), unchecked((int)0x7c56b6b0), unchecked((int)0x71159069), unchecked((int)0x75d48dde),
+ unchecked((int)0x6b93dddb), unchecked((int)0x6f52c06c), unchecked((int)0x6211e6b5), unchecked((int)0x66d0fb02),
+ unchecked((int)0x5e9f46bf), unchecked((int)0x5a5e5b08), unchecked((int)0x571d7dd1), unchecked((int)0x53dc6066),
+ unchecked((int)0x4d9b3063), unchecked((int)0x495a2dd4), unchecked((int)0x44190b0d), unchecked((int)0x40d816ba),
+ unchecked((int)0xaca5c697), unchecked((int)0xa864db20), unchecked((int)0xa527fdf9), unchecked((int)0xa1e6e04e),
+ unchecked((int)0xbfa1b04b), unchecked((int)0xbb60adfc), unchecked((int)0xb6238b25), unchecked((int)0xb2e29692),
+ unchecked((int)0x8aad2b2f), unchecked((int)0x8e6c3698), unchecked((int)0x832f1041), unchecked((int)0x87ee0df6),
+ unchecked((int)0x99a95df3), unchecked((int)0x9d684044), unchecked((int)0x902b669d), unchecked((int)0x94ea7b2a),
+ unchecked((int)0xe0b41de7), unchecked((int)0xe4750050), unchecked((int)0xe9362689), unchecked((int)0xedf73b3e),
+ unchecked((int)0xf3b06b3b), unchecked((int)0xf771768c), unchecked((int)0xfa325055), unchecked((int)0xfef34de2),
+ unchecked((int)0xc6bcf05f), unchecked((int)0xc27dede8), unchecked((int)0xcf3ecb31), unchecked((int)0xcbffd686),
+ unchecked((int)0xd5b88683), unchecked((int)0xd1799b34), unchecked((int)0xdc3abded), unchecked((int)0xd8fba05a),
+ unchecked((int)0x690ce0ee), unchecked((int)0x6dcdfd59), unchecked((int)0x608edb80), unchecked((int)0x644fc637),
+ unchecked((int)0x7a089632), unchecked((int)0x7ec98b85), unchecked((int)0x738aad5c), unchecked((int)0x774bb0eb),
+ unchecked((int)0x4f040d56), unchecked((int)0x4bc510e1), unchecked((int)0x46863638), unchecked((int)0x42472b8f),
+ unchecked((int)0x5c007b8a), unchecked((int)0x58c1663d), unchecked((int)0x558240e4), unchecked((int)0x51435d53),
+ unchecked((int)0x251d3b9e), unchecked((int)0x21dc2629), unchecked((int)0x2c9f00f0), unchecked((int)0x285e1d47),
+ unchecked((int)0x36194d42), unchecked((int)0x32d850f5), unchecked((int)0x3f9b762c), unchecked((int)0x3b5a6b9b),
+ unchecked((int)0x0315d626), unchecked((int)0x07d4cb91), unchecked((int)0x0a97ed48), unchecked((int)0x0e56f0ff),
+ unchecked((int)0x1011a0fa), unchecked((int)0x14d0bd4d), unchecked((int)0x19939b94), unchecked((int)0x1d528623),
+ unchecked((int)0xf12f560e), unchecked((int)0xf5ee4bb9), unchecked((int)0xf8ad6d60), unchecked((int)0xfc6c70d7),
+ unchecked((int)0xe22b20d2), unchecked((int)0xe6ea3d65), unchecked((int)0xeba91bbc), unchecked((int)0xef68060b),
+ unchecked((int)0xd727bbb6), unchecked((int)0xd3e6a601), unchecked((int)0xdea580d8), unchecked((int)0xda649d6f),
+ unchecked((int)0xc423cd6a), unchecked((int)0xc0e2d0dd), unchecked((int)0xcda1f604), unchecked((int)0xc960ebb3),
+ unchecked((int)0xbd3e8d7e), unchecked((int)0xb9ff90c9), unchecked((int)0xb4bcb610), unchecked((int)0xb07daba7),
+ unchecked((int)0xae3afba2), unchecked((int)0xaafbe615), unchecked((int)0xa7b8c0cc), unchecked((int)0xa379dd7b),
+ unchecked((int)0x9b3660c6), unchecked((int)0x9ff77d71), unchecked((int)0x92b45ba8), unchecked((int)0x9675461f),
+ unchecked((int)0x8832161a), unchecked((int)0x8cf30bad), unchecked((int)0x81b02d74), unchecked((int)0x857130c3),
+ unchecked((int)0x5d8a9099), unchecked((int)0x594b8d2e), unchecked((int)0x5408abf7), unchecked((int)0x50c9b640),
+ unchecked((int)0x4e8ee645), unchecked((int)0x4a4ffbf2), unchecked((int)0x470cdd2b), unchecked((int)0x43cdc09c),
+ unchecked((int)0x7b827d21), unchecked((int)0x7f436096), unchecked((int)0x7200464f), unchecked((int)0x76c15bf8),
+ unchecked((int)0x68860bfd), unchecked((int)0x6c47164a), unchecked((int)0x61043093), unchecked((int)0x65c52d24),
+ unchecked((int)0x119b4be9), unchecked((int)0x155a565e), unchecked((int)0x18197087), unchecked((int)0x1cd86d30),
+ unchecked((int)0x029f3d35), unchecked((int)0x065e2082), unchecked((int)0x0b1d065b), unchecked((int)0x0fdc1bec),
+ unchecked((int)0x3793a651), unchecked((int)0x3352bbe6), unchecked((int)0x3e119d3f), unchecked((int)0x3ad08088),
+ unchecked((int)0x2497d08d), unchecked((int)0x2056cd3a), unchecked((int)0x2d15ebe3), unchecked((int)0x29d4f654),
+ unchecked((int)0xc5a92679), unchecked((int)0xc1683bce), unchecked((int)0xcc2b1d17), unchecked((int)0xc8ea00a0),
+ unchecked((int)0xd6ad50a5), unchecked((int)0xd26c4d12), unchecked((int)0xdf2f6bcb), unchecked((int)0xdbee767c),
+ unchecked((int)0xe3a1cbc1), unchecked((int)0xe760d676), unchecked((int)0xea23f0af), unchecked((int)0xeee2ed18),
+ unchecked((int)0xf0a5bd1d), unchecked((int)0xf464a0aa), unchecked((int)0xf9278673), unchecked((int)0xfde69bc4),
+ unchecked((int)0x89b8fd09), unchecked((int)0x8d79e0be), unchecked((int)0x803ac667), unchecked((int)0x84fbdbd0),
+ unchecked((int)0x9abc8bd5), unchecked((int)0x9e7d9662), unchecked((int)0x933eb0bb), unchecked((int)0x97ffad0c),
+ unchecked((int)0xafb010b1), unchecked((int)0xab710d06), unchecked((int)0xa6322bdf), unchecked((int)0xa2f33668),
+ unchecked((int)0xbcb4666d), unchecked((int)0xb8757bda), unchecked((int)0xb5365d03), unchecked((int)0xb1f740b4)
+ };
+
+ public CRC() {
+ InitialiseCRC();
+ }
+
+ internal void InitialiseCRC() {
+ globalCrc = unchecked((int)0xffffffff);
+ }
+
+ internal int GetFinalCRC() {
+ return ~globalCrc;
+ }
+
+ internal int GetGlobalCRC() {
+ return globalCrc;
+ }
+
+ internal void SetGlobalCRC(int newCrc) {
+ globalCrc = newCrc;
+ }
+
+ internal void UpdateCRC(int inCh) {
+ int temp = (globalCrc >> 24) ^ inCh;
+ if (temp < 0) {
+ temp = 256 + temp;
+ }
+ globalCrc = (globalCrc << 8) ^ CRC.crc32Table[temp];
+ }
+
+ internal int globalCrc;
+ }
+}
\ No newline at end of file
diff --git a/Crypto/crypto.csproj b/Crypto/crypto.csproj
new file mode 100644
index 000000000..9a541329d
--- /dev/null
+++ b/Crypto/crypto.csproj
@@ -0,0 +1,3469 @@
+
+
+
+
+ 10.0
+ Debug
+ AnyCPU
+ {38872A5F-E87E-4FAD-B109-8EB7B2E6A4A0}
+
+ crypto
+
+ false
+ Library
+ Properties
+ Org.BouncyCastle
+ OnBuildSuccess
+ v4.0
+ Profile136
+ 512
+ {786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
+ true
+ true
+ SAK
+ SAK
+ SAK
+ SAK
+ ..\..\Src\
+ true
+
+
+ bin\Debug\
+ false
+ false
+ TRACE;DEBUG;PORTABLE
+ doc\crypto.xml
+ true
+ false
+ false
+ false
+ false
+ 4
+ full
+ prompt
+ AllRules.ruleset
+
+
+ 1591
+
+
+ bin\Release\
+ false
+ false
+ TRACE;PORTABLE
+ doc\crypto.xml
+ false
+ true
+ true
+ true
+ false
+ false
+ false
+ 4
+ pdbonly
+ prompt
+ AllRules.ruleset
+
+
+ 1591
+
+
+
+
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Crypto/doc/crypto.xml b/Crypto/doc/crypto.xml
new file mode 100644
index 000000000..f1cf2f391
--- /dev/null
+++ b/Crypto/doc/crypto.xml
@@ -0,0 +1,19296 @@
+
+
+
+ crypto
+
+
+
+ Base class for both the compress and decompress classes.
+ Holds common arrays, and static data.
+
+ @author Keiron Liddle
+
+
+ An input stream that decompresses from the BZip2 format (with the file
+ header chars) to be read as any other stream.
+
+ @author Keiron Liddle
+
+ NB: note this class has been modified to read the leading BZ from the
+ start of the BZIP2 stream to make it compatible with other PGP programs.
+
+
+ An output stream that compresses into the BZip2 format (with the file
+ header chars) into another stream.
+
+ @author Keiron Liddle
+
+ TODO: Update to BZip2 1.0.1
+ NB: note this class has been modified to add a leading BZ to the
+ start of the BZIP2 stream to make it compatible with other PGP programs.
+
+
+
+ modified by Oliver Merkel, 010128
+
+
+
+ A simple class the hold and calculate the CRC for sanity checking
+ of the data.
+
+ @author Keiron Liddle
+
+
+ Return the DER encoding of the object, null if the DER encoding can not be made.
+
+ @return a DER byte array, null otherwise.
+
+
+ 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.
+
+
+ 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.
+
+
+ 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.
+
+
+ build an object given its tag and the number of bytes to construct it from.
+
+
+ A Null object.
+
+
+ Create a base ASN.1 object from a byte array.
+ The byte array to parse.
+ The base ASN.1 object represented by the byte array.
+ If there is a problem parsing the data.
+
+
+ Read a base ASN.1 object from a stream.
+ The stream to parse.
+ The base ASN.1 object represented by the byte array.
+ If there is a problem parsing the data.
+
+
+ return an Octet string from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ return an Octet string from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ @param string the octets making up the octet string.
+
+
+ return an Asn1Sequence from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Return an ASN1 sequence from a tagged object. There is a special
+ case here, if an object appears to have been explicitly tagged on
+ reading but we were expecting it to be implicitly tagged in the
+ normal course of events it indicates that we lost the surrounding
+ sequence - so we need to add it back (this will happen if the tagged
+ object is a sequence that contains other sequences). If you are
+ dealing with implicitly tagged sequences you really should
+ be using this method.
+
+ @param obj the tagged object.
+ @param explicitly true if the object is meant to be explicitly tagged,
+ false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ return the object at the sequence position indicated by index.
+
+ @param index the sequence number (starting at zero) of the object
+ @return the object at the sequence position indicated by index.
+
+
+ return an ASN1Set from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Return an ASN1 set from a tagged object. There is a special
+ case here, if an object appears to have been explicitly tagged on
+ reading but we were expecting it to be implicitly tagged in the
+ normal course of events it indicates that we lost the surrounding
+ set - so we need to add it back (this will happen if the tagged
+ object is a sequence that contains other sequences). If you are
+ dealing with implicitly tagged sets you really should
+ be using this method.
+
+ @param obj the tagged object.
+ @param explicitly true if the object is meant to be explicitly tagged
+ false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ return true if a <= b (arrays are assumed padded with zeros).
+
+
+ return the object at the set position indicated by index.
+
+ @param index the set number (starting at zero) of the object
+ @return the object at the set position indicated by index.
+
+
+ ASN.1 TaggedObject - in ASN.1 notation this is any object preceded by
+ a [n] where n is some number - these are assumed to follow the construction
+ rules (as with sequences).
+
+
+ @param tagNo the tag number for this object.
+ @param obj the tagged object.
+
+
+ @param explicitly true if the object is explicitly tagged.
+ @param tagNo the tag number for this object.
+ @param obj the tagged object.
+
+
+ return whether or not the object may be explicitly tagged.
+
+ Note: if the object has been read from an input stream, the only
+ time you can be sure if isExplicit is returning the true state of
+ affairs is if it returns false. An implicitly tagged object may appear
+ to be explicitly tagged, so you need to understand the context under
+ which the reading was done as well, see GetObject below.
+
+
+ return whatever was following the tag.
+
+ Note: tagged objects are generally context dependent if you're
+ trying to extract a tagged object you should be going via the
+ appropriate GetInstance method.
+
+
+ Return the object held in this tagged object as a parser assuming it has
+ the type of the passed in tag. If the object doesn't have a parser
+ associated with it, the base object is returned.
+
+
+ Base class for an application specific object
+
+
+ Return the enclosed object assuming explicit tagging.
+
+ @return the resulting object
+ @throws IOException if reconstruction fails.
+
+
+ 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.
+
+
+ A BER Null object.
+
+
+ A Null object.
+
+
+ The octets making up the octet string.
+
+
+ convert a vector of octet strings into a single byte string
+
+
+ The octets making up the octet string.
+
+
+ return the DER octets that make up this string.
+
+
+ create an empty sequence
+
+
+ create a sequence containing one object
+
+
+ create a sequence containing a vector of objects.
+
+
+ create an empty sequence
+
+
+ create a sequence containing one object
+
+
+ create a sequence containing a vector of objects.
+
+
+ A Der encoded set object
+
+
+ create an empty set
+
+
+ @param obj - a single object that makes up the set.
+
+
+ @param v - a vector of objects making up the set.
+
+
+ create an empty sequence
+
+
+ create a set containing one object
+
+
+ create a set containing a vector of objects.
+
+
+ BER TaggedObject - in ASN.1 notation this is any object preceded by
+ a [n] where n is some number - these are assumed to follow the construction
+ rules (as with sequences).
+
+
+ DER TaggedObject - in ASN.1 notation this is any object preceded by
+ a [n] where n is some number - these are assumed to follow the construction
+ rules (as with sequences).
+
+
+ @param tagNo the tag number for this object.
+ @param obj the tagged object.
+
+
+ @param explicitly true if an explicitly tagged object.
+ @param tagNo the tag number for this object.
+ @param obj the tagged object.
+
+
+ create an implicitly tagged object that contains a zero
+ length sequence.
+
+
+ @param tagNo the tag number for this object.
+ @param obj the tagged object.
+
+
+ @param explicitly true if an explicitly tagged object.
+ @param tagNo the tag number for this object.
+ @param obj the tagged object.
+
+
+ create an implicitly tagged object that contains a zero
+ length sequence.
+
+
+
+ CAKeyUpdAnnContent ::= SEQUENCE {
+ oldWithNew CmpCertificate, -- old pub signed with new priv
+ newWithOld CmpCertificate, -- new pub signed with old priv
+ newWithNew CmpCertificate -- new pub signed with new priv
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ CertConfirmContent ::= SEQUENCE OF CertStatus
+
+ @return a basic ASN.1 object representation.
+
+
+
+ CertifiedKeyPair ::= SEQUENCE {
+ certOrEncCert CertOrEncCert,
+ privateKey [0] EncryptedValue OPTIONAL,
+ -- see [CRMF] for comment on encoding
+ publicationInfo [1] PKIPublicationInfo OPTIONAL
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+ Marker interface for CHOICE objects - if you implement this in a roll-your-own
+ object, any attempt to tag the object implicitly will convert the tag to an
+ explicit one as the encoding rules require.
+
+ If you use this interface your class should also implement the getInstance
+ pattern which takes a tag object and the tagging mode used.
+
+ @return a basic ASN.1 object representation.
+
+
+
+ CertResponse ::= SEQUENCE {
+ certReqId INTEGER,
+ -- to match this response with corresponding request (a value
+ -- of -1 is to be used if certReqId is not specified in the
+ -- corresponding request)
+ status PKIStatusInfo,
+ certifiedKeyPair CertifiedKeyPair OPTIONAL,
+ rspInfo OCTET STRING OPTIONAL
+ -- analogous to the id-regInfo-utf8Pairs string defined
+ -- for regInfo in CertReqMsg [CRMF]
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ CertStatus ::= SEQUENCE {
+ certHash OCTET STRING,
+ -- the hash of the certificate, using the same hash algorithm
+ -- as is used to create and verify the certificate signature
+ certReqId INTEGER,
+ -- to match this confirmation with the corresponding req/rep
+ statusInfo PKIStatusInfo OPTIONAL
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ Challenge ::= SEQUENCE {
+ owf AlgorithmIdentifier OPTIONAL,
+
+ -- MUST be present in the first Challenge; MAY be omitted in
+ -- any subsequent Challenge in POPODecKeyChallContent (if
+ -- omitted, then the owf used in the immediately preceding
+ -- Challenge is to be used).
+
+ witness OCTET STRING,
+ -- the result of applying the one-way function (owf) to a
+ -- randomly-generated INTEGER, A. [Note that a different
+ -- INTEGER MUST be used for each Challenge.]
+ challenge OCTET STRING
+ -- the encryption (under the public key for which the cert.
+ -- request is being made) of Rand, where Rand is specified as
+ -- Rand ::= SEQUENCE {
+ -- int INTEGER,
+ -- - the randomly-generated INTEGER A (above)
+ -- sender GeneralName
+ -- - the sender's name (as included in PKIHeader)
+ -- }
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+ Note: the addition of attribute certificates is a BC extension.
+
+
+
+ @return a basic ASN.1 object representation.
+
+
+
+ GenMsgContent ::= SEQUENCE OF InfoTypeAndValue
+
+ @return a basic ASN.1 object representation.
+
+
+
+ GenRepContent ::= SEQUENCE OF InfoTypeAndValue
+
+ @return a basic ASN.1 object representation.
+
+
+ Example InfoTypeAndValue contents include, but are not limited
+ to, the following (un-comment in this ASN.1 module and use as
+ appropriate for a given environment):
+
+ @return a basic ASN.1 object representation.
+
+
+
+ OobCertHash ::= SEQUENCE {
+ hashAlg [0] AlgorithmIdentifier OPTIONAL,
+ certId [1] CertId OPTIONAL,
+ hashVal BIT STRING
+ -- hashVal is calculated over the Der encoding of the
+ -- self-signed certificate with the identifier certID.
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ PbmParameter ::= SEQUENCE {
+ salt OCTET STRING,
+ -- note: implementations MAY wish to limit acceptable sizes
+ -- of this string to values appropriate for their environment
+ -- in order to reduce the risk of denial-of-service attacks
+ owf AlgorithmIdentifier,
+ -- AlgId for a One-Way Function (SHA-1 recommended)
+ iterationCount INTEGER,
+ -- number of times the OWF is applied
+ -- note: implementations MAY wish to limit acceptable sizes
+ -- of this integer to values appropriate for their environment
+ -- in order to reduce the risk of denial-of-service attacks
+ mac AlgorithmIdentifier
+ -- the MAC AlgId (e.g., DES-MAC, Triple-DES-MAC [PKCS11],
+ } -- or HMAC [RFC2104, RFC2202])
+
+ @return a basic ASN.1 object representation.
+
+
+ Creates a new PkiBody.
+ @param type one of the TYPE_* constants
+ @param content message content
+
+
+
+ @return a basic ASN.1 object representation.
+
+
+
+ PkiConfirmContent ::= NULL
+
+ @return a basic ASN.1 object representation.
+
+
+
+ PKIFailureInfo ::= BIT STRING {
+ badAlg (0),
+ -- unrecognized or unsupported Algorithm Identifier
+ badMessageCheck (1), -- integrity check failed (e.g., signature did not verify)
+ badRequest (2),
+ -- transaction not permitted or supported
+ badTime (3), -- messageTime was not sufficiently close to the system time, as defined by local policy
+ badCertId (4), -- no certificate could be found matching the provided criteria
+ badDataFormat (5),
+ -- the data submitted has the wrong format
+ wrongAuthority (6), -- the authority indicated in the request is different from the one creating the response token
+ incorrectData (7), -- the requester's data is incorrect (for notary services)
+ missingTimeStamp (8), -- when the timestamp is missing but should be there (by policy)
+ badPOP (9) -- the proof-of-possession failed
+ timeNotAvailable (14),
+ -- the TSA's time source is not available
+ unacceptedPolicy (15),
+ -- the requested TSA policy is not supported by the TSA
+ unacceptedExtension (16),
+ -- the requested extension is not supported by the TSA
+ addInfoNotAvailable (17)
+ -- the additional information requested could not be understood
+ -- or is not available
+ systemFailure (25)
+ -- the request cannot be handled due to system failure
+
+
+
+ basic interface for Der string objects.
+
+
+ return the correct number of pad bits for a bit string defined in
+ a 32 bit constant
+
+
+ return the correct number of bytes for a bit string defined in
+ a 32 bit constant
+
+
+ return a Bit string from the passed in object
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return a Bit string from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ @param data the octets making up the bit string.
+ @param padBits the number of extra bits at the end of the string.
+
+
+ @return the value of the bit string as an int (truncating if necessary)
+
+
+ Basic constructor.
+
+
+
+ PkiFreeText ::= SEQUENCE SIZE (1..MAX) OF UTF8String
+
+
+
+ Return the number of string elements present.
+
+ @return number of elements present.
+
+
+ Return the UTF8STRING at index.
+
+ @param index index of the string of interest
+ @return the string at index.
+
+
+ Value for a "null" recipient or sender.
+
+
+
+ PkiHeader ::= SEQUENCE {
+ pvno INTEGER { cmp1999(1), cmp2000(2) },
+ sender GeneralName,
+ -- identifies the sender
+ recipient GeneralName,
+ -- identifies the intended recipient
+ messageTime [0] GeneralizedTime OPTIONAL,
+ -- time of production of this message (used when sender
+ -- believes that the transport will be "suitable"; i.e.,
+ -- that the time will still be meaningful upon receipt)
+ protectionAlg [1] AlgorithmIdentifier OPTIONAL,
+ -- algorithm used for calculation of protection bits
+ senderKID [2] KeyIdentifier OPTIONAL,
+ recipKID [3] KeyIdentifier OPTIONAL,
+ -- to identify specific keys used for protection
+ transactionID [4] OCTET STRING OPTIONAL,
+ -- identifies the transaction; i.e., this will be the same in
+ -- corresponding request, response, certConf, and PKIConf
+ -- messages
+ senderNonce [5] OCTET STRING OPTIONAL,
+ recipNonce [6] OCTET STRING OPTIONAL,
+ -- nonces used to provide replay protection, senderNonce
+ -- is inserted by the creator of this message; recipNonce
+ -- is a nonce previously inserted in a related message by
+ -- the intended recipient of this message
+ freeText [7] PKIFreeText OPTIONAL,
+ -- this may be used to indicate context-specific instructions
+ -- (this field is intended for human consumption)
+ generalInfo [8] SEQUENCE SIZE (1..MAX) OF
+ InfoTypeAndValue OPTIONAL
+ -- this may be used to convey context-specific information
+ -- (this field not primarily intended for human consumption)
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ PKIHeader ::= SEQUENCE {
+ pvno INTEGER { cmp1999(1), cmp2000(2) },
+ sender GeneralName,
+ -- identifies the sender
+ recipient GeneralName,
+ -- identifies the intended recipient
+ messageTime [0] GeneralizedTime OPTIONAL,
+ -- time of production of this message (used when sender
+ -- believes that the transport will be "suitable"; i.e.,
+ -- that the time will still be meaningful upon receipt)
+ protectionAlg [1] AlgorithmIdentifier OPTIONAL,
+ -- algorithm used for calculation of protection bits
+ senderKID [2] KeyIdentifier OPTIONAL,
+ recipKID [3] KeyIdentifier OPTIONAL,
+ -- to identify specific keys used for protection
+ transactionID [4] OCTET STRING OPTIONAL,
+ -- identifies the transaction; i.e., this will be the same in
+ -- corresponding request, response, certConf, and PKIConf
+ -- messages
+ senderNonce [5] OCTET STRING OPTIONAL,
+ recipNonce [6] OCTET STRING OPTIONAL,
+ -- nonces used to provide replay protection, senderNonce
+ -- is inserted by the creator of this message; recipNonce
+ -- is a nonce previously inserted in a related message by
+ -- the intended recipient of this message
+ freeText [7] PKIFreeText OPTIONAL,
+ -- this may be used to indicate context-specific instructions
+ -- (this field is intended for human consumption)
+ generalInfo [8] SEQUENCE SIZE (1..MAX) OF
+ InfoTypeAndValue OPTIONAL
+ -- this may be used to convey context-specific information
+ -- (this field not primarily intended for human consumption)
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+ Creates a new PkiMessage.
+
+ @param header message header
+ @param body message body
+ @param protection message protection (may be null)
+ @param extraCerts extra certificates (may be null)
+
+
+
+ @return a basic ASN.1 object representation.
+
+
+
+ PkiMessages ::= SEQUENCE SIZE (1..MAX) OF PkiMessage
+
+ @return a basic ASN.1 object representation.
+
+
+ @param status
+
+
+ @param status
+ @param statusString
+
+
+
+ PkiStatusInfo ::= SEQUENCE {
+ status PKIStatus, (INTEGER)
+ statusString PkiFreeText OPTIONAL,
+ failInfo PkiFailureInfo OPTIONAL (BIT STRING)
+ }
+
+ PKIStatus:
+ granted (0), -- you got exactly what you asked for
+ grantedWithMods (1), -- you got something like what you asked for
+ rejection (2), -- you don't get it, more information elsewhere in the message
+ waiting (3), -- the request body part has not yet been processed, expect to hear more later
+ revocationWarning (4), -- this message contains a warning that a revocation is imminent
+ revocationNotification (5), -- notification that a revocation has occurred
+ keyUpdateWarning (6) -- update already done for the oldCertId specified in CertReqMsg
+
+ PkiFailureInfo:
+ badAlg (0), -- unrecognized or unsupported Algorithm Identifier
+ badMessageCheck (1), -- integrity check failed (e.g., signature did not verify)
+ badRequest (2), -- transaction not permitted or supported
+ badTime (3), -- messageTime was not sufficiently close to the system time, as defined by local policy
+ badCertId (4), -- no certificate could be found matching the provided criteria
+ badDataFormat (5), -- the data submitted has the wrong format
+ wrongAuthority (6), -- the authority indicated in the request is different from the one creating the response token
+ incorrectData (7), -- the requester's data is incorrect (for notary services)
+ missingTimeStamp (8), -- when the timestamp is missing but should be there (by policy)
+ badPOP (9) -- the proof-of-possession failed
+
+
+
+
+
+ PollRepContent ::= SEQUENCE OF SEQUENCE {
+ certReqId INTEGER,
+ checkAfter INTEGER, -- time in seconds
+ reason PKIFreeText OPTIONAL
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ @return a basic ASN.1 object representation.
+
+
+
+ RevDetails ::= SEQUENCE {
+ certDetails CertTemplate,
+ -- allows requester to specify as much as they can about
+ -- the cert. for which revocation is requested
+ -- (e.g., for cases in which serialNumber is not available)
+ crlEntryDetails Extensions OPTIONAL
+ -- requested crlEntryExtensions
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ RevRepContent ::= SEQUENCE {
+ status SEQUENCE SIZE (1..MAX) OF PKIStatusInfo,
+ -- in same order as was sent in RevReqContent
+ revCerts [0] SEQUENCE SIZE (1..MAX) OF CertId OPTIONAL,
+ -- IDs for which revocation was requested
+ -- (same order as status)
+ crls [1] SEQUENCE SIZE (1..MAX) OF CertificateList OPTIONAL
+ -- the resulting CRLs (there may be more than one)
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ RevReqContent ::= SEQUENCE OF RevDetails
+
+ @return a basic ASN.1 object representation.
+
+
+ return an Attribute object from the given object.
+
+ @param o the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Attribute ::= SEQUENCE {
+ attrType OBJECT IDENTIFIER,
+ attrValues SET OF AttributeValue
+ }
+
+
+
+
+ Attributes ::=
+ SET SIZE(1..MAX) OF Attribute -- according to RFC 5652
+
+ @return
+
+
+ Return all the attributes matching the OBJECT IDENTIFIER oid. The vector will be
+ empty if there are no attributes of the required type present.
+
+ @param oid type of attribute required.
+ @return a vector of all the attributes found of type oid.
+
+
+ Return a new table with the passed in attribute added.
+
+ @param attrType
+ @param attrValue
+ @return
+
+
+ Return the first attribute matching the given OBJECT IDENTIFIER
+
+
+ return an AuthenticatedData object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param isExplicit true if the object is meant to be explicitly
+ tagged false otherwise.
+ @throws ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return an AuthenticatedData object from the given object.
+
+ @param obj the object we want converted.
+ @throws ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return an AuthEnvelopedData object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param isExplicit true if the object is meant to be explicitly
+ tagged false otherwise.
+ @throws ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return an AuthEnvelopedData object from the given object.
+
+ @param obj the object we want converted.
+ @throws ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return a CompressedData object from a tagged object.
+
+ @param ato the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return a CompressedData object from the given object.
+
+ @param _obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ RFC 3274 - CMS Compressed Data.
+
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ ContentInfo ::= Sequence {
+ contentType ContentType,
+ content
+ [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }
+
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ ContentInfo ::= SEQUENCE {
+ contentType ContentType,
+ content
+ [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }
+
+
+
+ return an AuthEnvelopedData object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param isExplicit true if the object is meant to be explicitly
+ tagged false otherwise.
+ @throws ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return an AuthEnvelopedData object from the given object.
+
+ @param obj the object we want converted.
+ @throws ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return an EncryptedContentInfo object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ @return a basic ASN.1 object representation.
+
+
+ return an EnvelopedData object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return an EnvelopedData object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return a KekIdentifier object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return a KekIdentifier object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ KekIdentifier ::= Sequence {
+ keyIdentifier OCTET STRING,
+ date GeneralizedTime OPTIONAL,
+ other OtherKeyAttribute OPTIONAL
+ }
+
+
+
+ return a KekRecipientInfo object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return a KekRecipientInfo object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ KekRecipientInfo ::= Sequence {
+ version CMSVersion, -- always set to 4
+ kekID KekIdentifier,
+ keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
+ encryptedKey EncryptedKey
+ }
+
+
+
+ return an KeyAgreeRecipientIdentifier object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param isExplicit true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return an KeyAgreeRecipientIdentifier object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return a KeyAgreeRecipientInfo object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return a KeyAgreeRecipientInfo object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ * Produce an object suitable for an Asn1OutputStream.
+ *
+
+
+ return a KeyTransRecipientInfo object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ KeyTransRecipientInfo ::= Sequence {
+ version CMSVersion, -- always set to 0 or 2
+ rid RecipientIdentifier,
+ keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
+ encryptedKey EncryptedKey
+ }
+
+ @return
+
+
+ return an OriginatorIdentifierOrKey object from a tagged object.
+
+ @param o the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return an OriginatorIdentifierOrKey object from the given object.
+
+ @param o the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return an OriginatorInfo object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return an OriginatorInfo object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return an OriginatorPublicKey object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return an OriginatorPublicKey object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return an OtherKeyAttribute object from the given object.
+
+ @param o the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ OtherKeyAttribute ::= Sequence {
+ keyAttrId OBJECT IDENTIFIER,
+ keyAttr ANY DEFINED BY keyAttrId OPTIONAL
+ }
+
+
+
+ return a OtherRecipientInfo object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return a OtherRecipientInfo object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ OtherRecipientInfo ::= Sequence {
+ oriType OBJECT IDENTIFIER,
+ oriValue ANY DEFINED BY oriType }
+
+
+
+ return a PasswordRecipientInfo object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return a PasswordRecipientInfo object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ PasswordRecipientInfo ::= Sequence {
+ version CMSVersion, -- Always set to 0
+ keyDerivationAlgorithm [0] KeyDerivationAlgorithmIdentifier
+ OPTIONAL,
+ keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
+ encryptedKey EncryptedKey }
+
+
+
+ return an RecipientEncryptedKey object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param isExplicit true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return a RecipientEncryptedKey object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return a RecipientIdentifier object from the given object.
+
+ @param o the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return a RecipientKeyIdentifier object from a tagged object.
+
+ @param _ato the tagged object holding the object we want.
+ @param _explicit true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return a RecipientKeyIdentifier object from the given object.
+
+ @param _obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return a SignerIdentifier object from the given object.
+
+ @param o the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ creates a time object from a given date - if the date is between 1950
+ and 2049 a UTCTime object is Generated, otherwise a GeneralizedTime
+ is used.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ @return a basic ASN.1 object representation.
+
+
+
+ CertReqMessages ::= SEQUENCE SIZE (1..MAX) OF CertReqMsg
+
+ @return a basic ASN.1 object representation.
+
+
+ Creates a new CertReqMsg.
+ @param certReq CertRequest
+ @param popo may be null
+ @param regInfo may be null
+
+
+
+ CertReqMsg ::= SEQUENCE {
+ certReq CertRequest,
+ pop ProofOfPossession OPTIONAL,
+ -- content depends upon key type
+ regInfo SEQUENCE SIZE(1..MAX) OF AttributeTypeAndValue OPTIONAL }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ CertRequest ::= SEQUENCE {
+ certReqId INTEGER, -- ID for matching request and reply
+ certTemplate CertTemplate, -- Selected fields of cert to be issued
+ controls Controls OPTIONAL } -- Attributes affecting issuance
+
+ @return a basic ASN.1 object representation.
+
+
+
+ @return a basic ASN.1 object representation.
+
+
+ Sets the X.509 version. Note: for X509v3, use 2 here.
+
+
+ Sets the issuer unique ID (deprecated in X.509v3)
+
+
+ Sets the subject unique ID (deprecated in X.509v3)
+
+
+
+ EncryptedKey ::= CHOICE {
+ encryptedValue EncryptedValue, -- deprecated
+ envelopedData [0] EnvelopedData }
+ -- The encrypted private key MUST be placed in the envelopedData
+ -- encryptedContentInfo encryptedContent OCTET STRING.
+
+
+
+
+ EncryptedValue ::= SEQUENCE {
+ intendedAlg [0] AlgorithmIdentifier OPTIONAL,
+ -- the intended algorithm for which the value will be used
+ symmAlg [1] AlgorithmIdentifier OPTIONAL,
+ -- the symmetric algorithm used to encrypt the value
+ encSymmKey [2] BIT STRING OPTIONAL,
+ -- the (encrypted) symmetric key used to encrypt the value
+ keyAlg [3] AlgorithmIdentifier OPTIONAL,
+ -- algorithm used to encrypt the symmetric key
+ valueHint [4] OCTET STRING OPTIONAL,
+ -- a brief description or identifier of the encValue content
+ -- (may be meaningful only to the sending entity, and used only
+ -- if EncryptedValue might be re-examined by the sending entity
+ -- in the future)
+ encValue BIT STRING }
+ -- the encrypted value itself
+
+ @return a basic ASN.1 object representation.
+
+
+
+ OptionalValidity ::= SEQUENCE {
+ notBefore [0] Time OPTIONAL,
+ notAfter [1] Time OPTIONAL } --at least one MUST be present
+
+ @return a basic ASN.1 object representation.
+
+
+
+ PkiArchiveOptions ::= CHOICE {
+ encryptedPrivKey [0] EncryptedKey,
+ -- the actual value of the private key
+ keyGenParameters [1] KeyGenParameters,
+ -- parameters which allow the private key to be re-generated
+ archiveRemGenPrivKey [2] BOOLEAN }
+ -- set to TRUE if sender wishes receiver to archive the private
+ -- key of a key pair that the receiver generates in response to
+ -- this request; set to FALSE if no archival is desired.
+
+
+
+
+ PkiPublicationInfo ::= SEQUENCE {
+ action INTEGER {
+ dontPublish (0),
+ pleasePublish (1) },
+ pubInfos SEQUENCE SIZE (1..MAX) OF SinglePubInfo OPTIONAL }
+ -- pubInfos MUST NOT be present if action is "dontPublish"
+ -- (if action is "pleasePublish" and pubInfos is omitted,
+ -- "dontCare" is assumed)
+
+ @return a basic ASN.1 object representation.
+
+
+ Password-based MAC value for use with POPOSigningKeyInput.
+
+
+ Creates a new PKMACValue.
+ @param params parameters for password-based MAC
+ @param value MAC of the DER-encoded SubjectPublicKeyInfo
+
+
+ Creates a new PKMACValue.
+ @param aid CMPObjectIdentifiers.passwordBasedMAC, with PBMParameter
+ @param value MAC of the DER-encoded SubjectPublicKeyInfo
+
+
+
+ PKMACValue ::= SEQUENCE {
+ algId AlgorithmIdentifier,
+ -- algorithm value shall be PasswordBasedMac 1.2.840.113533.7.66.13
+ -- parameter value is PBMParameter
+ value BIT STRING }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ PopoPrivKey ::= CHOICE {
+ thisMessage [0] BIT STRING, -- Deprecated
+ -- possession is proven in this message (which contains the private
+ -- key itself (encrypted for the CA))
+ subsequentMessage [1] SubsequentMessage,
+ -- possession will be proven in a subsequent message
+ dhMAC [2] BIT STRING, -- Deprecated
+ agreeMAC [3] PKMACValue,
+ encryptedKey [4] EnvelopedData }
+
+
+
+ Creates a new Proof of Possession object for a signing key.
+ @param poposkIn the PopoSigningKeyInput structure, or null if the
+ CertTemplate includes both subject and publicKey values.
+ @param aid the AlgorithmIdentifier used to sign the proof of possession.
+ @param signature a signature over the DER-encoded value of poposkIn,
+ or the DER-encoded value of certReq if poposkIn is null.
+
+
+
+ PopoSigningKey ::= SEQUENCE {
+ poposkInput [0] PopoSigningKeyInput OPTIONAL,
+ algorithmIdentifier AlgorithmIdentifier,
+ signature BIT STRING }
+ -- The signature (using "algorithmIdentifier") is on the
+ -- DER-encoded value of poposkInput. NOTE: If the CertReqMsg
+ -- certReq CertTemplate contains the subject and publicKey values,
+ -- then poposkInput MUST be omitted and the signature MUST be
+ -- computed on the DER-encoded value of CertReqMsg certReq. If
+ -- the CertReqMsg certReq CertTemplate does not contain the public
+ -- key and subject values, then poposkInput MUST be present and
+ -- MUST be signed. This strategy ensures that the public key is
+ -- not present in both the poposkInput and CertReqMsg certReq
+ -- CertTemplate fields.
+
+ @return a basic ASN.1 object representation.
+
+
+ Creates a new PopoSigningKeyInput with sender name as authInfo.
+
+
+ Creates a new PopoSigningKeyInput using password-based MAC.
+
+
+
+ PopoSigningKeyInput ::= SEQUENCE {
+ authInfo CHOICE {
+ sender [0] GeneralName,
+ -- used only if an authenticated identity has been
+ -- established for the sender (e.g., a DN from a
+ -- previously-issued and currently-valid certificate
+ publicKeyMac PKMacValue },
+ -- used if no authenticated GeneralName currently exists for
+ -- the sender; publicKeyMac contains a password-based MAC
+ -- on the DER-encoded value of publicKey
+ publicKey SubjectPublicKeyInfo } -- from CertTemplate
+
+ @return a basic ASN.1 object representation.
+
+
+ Returns the sender field, or null if authInfo is publicKeyMac
+
+
+ Returns the publicKeyMac field, or null if authInfo is sender
+
+
+ Creates a ProofOfPossession with type raVerified.
+
+
+ Creates a ProofOfPossession for a signing key.
+
+
+ Creates a ProofOfPossession for key encipherment or agreement.
+ @param type one of TYPE_KEY_ENCIPHERMENT or TYPE_KEY_AGREEMENT
+
+
+
+ ProofOfPossession ::= CHOICE {
+ raVerified [0] NULL,
+ -- used if the RA has already verified that the requester is in
+ -- possession of the private key
+ signature [1] PopoSigningKey,
+ keyEncipherment [2] PopoPrivKey,
+ keyAgreement [3] PopoPrivKey }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ @return a basic ASN.1 object representation.
+
+
+ return an integer from the passed in object
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return an Integer from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param isExplicit true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ in some cases positive values Get crammed into a space,
+ that's not quite big enough...
+
+
+ table of the available named parameters for GOST 3410-2001.
+
+
+ return the ECDomainParameters object for the given OID, null if it
+ isn't present.
+
+ @param oid an object identifier representing a named parameters, if present.
+
+
+ return the named curve name represented by the given object identifier.
+
+
+ returns an enumeration containing the name strings for curves
+ contained in this structure.
+
+
+
+
+
+ table of the available named parameters for GOST 3410-94.
+
+
+ return the GOST3410ParamSetParameters object for the given OID, null if it
+ isn't present.
+
+ @param oid an object identifier representing a named parameters, if present.
+
+
+ returns an enumeration containing the name strings for parameters
+ contained in this structure.
+
+
+ Der BMPString object.
+
+
+ return a BMP string from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return a BMP string from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ basic constructor - byte encoded string.
+
+
+ basic constructor
+
+
+ return a bool from the passed in object.
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return a DerBoolean from the passed in bool.
+
+
+ return a Boolean from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ return an integer from the passed in object
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return an Enumerated from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ Class representing the DER-type External
+
+
+ Creates a new instance of DerExternal
+ See X.690 for more informations about the meaning of these parameters
+ @param directReference The direct reference or null if not set.
+ @param indirectReference The indirect reference or null if not set.
+ @param dataValueDescriptor The data value descriptor or null if not set.
+ @param externalData The external data in its encoded form.
+
+
+ Creates a new instance of DerExternal.
+ See X.690 for more informations about the meaning of these parameters
+ @param directReference The direct reference or null if not set.
+ @param indirectReference The indirect reference or null if not set.
+ @param dataValueDescriptor The data value descriptor or null if not set.
+ @param encoding The encoding to be used for the external data
+ @param externalData The external data
+
+
+ The encoding of the content. Valid values are
+
+
0 single-ASN1-type
+
1 OCTET STRING
+
2 BIT STRING
+
+
+
+ Generalized time object.
+
+
+ return a generalized time from the passed in object
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return a Generalized Time object from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ The correct format for this is YYYYMMDDHHMMSS[.f]Z, or without the Z
+ for local time, or Z+-HHMM on the end, for difference between local
+ time and UTC time. The fractional second amount f must consist of at
+ least one number with trailing zeroes removed.
+
+ @param time the time string.
+ @exception ArgumentException if string is an illegal format.
+
+
+ base constructor from a local time object
+
+
+ return the time - always in the form of
+ YYYYMMDDhhmmssGMT(+hh:mm|-hh:mm).
+
+ Normally in a certificate we would expect "Z" rather than "GMT",
+ however adding the "GMT" means we can just use:
+
+ dateF = new SimpleDateFormat("yyyyMMddHHmmssz");
+
+ To read in the time and Get a date which is compatible with our local
+ time zone.
+
+
+ Return the time.
+ @return The time string as it appeared in the encoded object.
+
+
+ Der IA5String object - this is an ascii string.
+
+
+ return a IA5 string from the passed in object
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return an IA5 string from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ basic constructor - with bytes.
+
+
+ basic constructor - without validation.
+
+
+ Constructor with optional validation.
+
+ @param string the base string to wrap.
+ @param validate whether or not to check the string.
+ @throws ArgumentException if validate is true and the string
+ contains characters that should not be in an IA5String.
+
+
+ return true if the passed in String can be represented without
+ loss as an IA5String, false otherwise.
+
+ @return true if in printable set, false otherwise.
+
+
+ Der NumericString object - this is an ascii string of characters {0,1,2,3,4,5,6,7,8,9, }.
+
+
+ return a Numeric string from the passed in object
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return an Numeric string from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ basic constructor - with bytes.
+
+
+ basic constructor - without validation..
+
+
+ Constructor with optional validation.
+
+ @param string the base string to wrap.
+ @param validate whether or not to check the string.
+ @throws ArgumentException if validate is true and the string
+ contains characters that should not be in a NumericString.
+
+
+ Return true if the string can be represented as a NumericString ('0'..'9', ' ')
+
+ @param str string to validate.
+ @return true if numeric, fale otherwise.
+
+
+ return an Oid from the passed in object
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return an object Identifier from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ Return true if this oid is an extension of the passed in branch, stem.
+ @param stem the arc or branch that is a possible parent.
+ @return true if the branch is on the passed in stem, false otherwise.
+
+
+ Der PrintableString object.
+
+
+ return a printable string from the passed in object.
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return a Printable string from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ basic constructor - byte encoded string.
+
+
+ basic constructor - this does not validate the string
+
+
+ Constructor with optional validation.
+
+ @param string the base string to wrap.
+ @param validate whether or not to check the string.
+ @throws ArgumentException if validate is true and the string
+ contains characters that should not be in a PrintableString.
+
+
+ return true if the passed in String can be represented without
+ loss as a PrintableString, false otherwise.
+
+ @return true if in printable set, false otherwise.
+
+
+ Der T61String (also the teletex string) - 8-bit characters
+
+
+ return a T61 string from the passed in object.
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return an T61 string from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ basic constructor - with bytes.
+
+
+ basic constructor - with string.
+
+
+ Der UniversalString object.
+
+
+ return a Universal string from the passed in object.
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return a Universal string from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ basic constructor - byte encoded string.
+
+
+ We insert one of these when we find a tag we don't recognise.
+
+
+ @param tag the tag value.
+ @param data the contents octets.
+
+
+ UTC time object.
+
+
+ return an UTC Time from the passed in object.
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return an UTC Time from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ The correct format for this is YYMMDDHHMMSSZ (it used to be that seconds were
+ never encoded. When you're creating one of these objects from scratch, that's
+ what you want to use, otherwise we'll try to deal with whatever Gets read from
+ the input stream... (this is why the input format is different from the GetTime()
+ method output).
+
+ @param time the time string.
+
+
+ base constructor from a DateTime object
+
+
+ return the time as a date based on whatever a 2 digit year will return. For
+ standardised processing use ToAdjustedDateTime().
+
+ @return the resulting date
+ @exception ParseException if the date string cannot be parsed.
+
+
+ return the time as an adjusted date
+ in the range of 1950 - 2049.
+
+ @return a date in the range of 1950 to 2049.
+ @exception ParseException if the date string cannot be parsed.
+
+
+ return the time - always in the form of
+ YYMMDDhhmmssGMT(+hh:mm|-hh:mm).
+
+ Normally in a certificate we would expect "Z" rather than "GMT",
+ however adding the "GMT" means we can just use:
+
+ dateF = new SimpleDateFormat("yyMMddHHmmssz");
+
+ To read in the time and Get a date which is compatible with our local
+ time zone.
+
+ Note: In some cases, due to the local date processing, this
+ may lead to unexpected results. If you want to stick the normal
+ convention of 1950 to 2049 use the GetAdjustedTime() method.
+
+
+
+ Return a time string as an adjusted date with a 4 digit year.
+ This goes in the range of 1950 - 2049.
+
+
+
+ Der UTF8String object.
+
+
+ return an UTF8 string from the passed in object.
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return an UTF8 string from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ basic constructor - byte encoded string.
+
+
+ basic constructor
+
+
+ Der VisibleString object.
+
+
+ return a Visible string from the passed in object.
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return a Visible string from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ basic constructor - byte encoded string.
+
+
+ basic constructor
+
+
+
+ RFC 3126: 4.3.1 Certificate Values Attribute Definition
+
+ CertificateValues ::= SEQUENCE OF Certificate
+
+
+
+
+
+
+
+ Create from OCTET STRING whose octets represent the identifier.
+
+
+ Create from byte array representing the identifier.
+
+
+ The definition of ContentIdentifier is
+
+ SigningCertificate ::= SEQUENCE {
+ certs SEQUENCE OF EssCertID,
+ policies SEQUENCE OF PolicyInformation OPTIONAL
+ }
+
+ id-aa-signingCertificate OBJECT IDENTIFIER ::= { iso(1)
+ member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
+ smime(16) id-aa(2) 12 }
+
+
+ The definition of SigningCertificateV2 is
+
+ SigningCertificateV2 ::= SEQUENCE {
+ certs SEQUENCE OF EssCertIDv2,
+ policies SEQUENCE OF PolicyInformation OPTIONAL
+ }
+
+ id-aa-signingCertificateV2 OBJECT IDENTIFIER ::= { iso(1)
+ member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
+ smime(16) id-aa(2) 47 }
+
+
+ The CscaMasterList object. This object can be wrapped in a
+ CMSSignedData to be published in LDAP.
+
+
+ CscaMasterList ::= SEQUENCE {
+ version CscaMasterListVersion,
+ certList SET OF Certificate }
+
+ CscaMasterListVersion :: INTEGER {v0(0)}
+
+ @return
+
+
+ The id-isismtt-cp-accredited OID indicates that the certificate is a
+ qualified certificate according to Directive 1999/93/EC of the European
+ Parliament and of the Council of 13 December 1999 on a Community
+ Framework for Electronic Signatures, which additionally conforms the
+ special requirements of the SigG and has been issued by an accredited CA.
+
+
+ Certificate extensionDate of certificate generation
+
+
+ DateOfCertGenSyntax ::= GeneralizedTime
+
+
+
+ Attribute to indicate that the certificate holder may sign in the name of
+ a third person. May also be used as extension in a certificate.
+
+
+ Attribute to indicate admissions to certain professions. May be used as
+ attribute in attribute certificate or as extension in a certificate
+
+
+ Monetary limit for transactions. The QcEuMonetaryLimit QC statement MUST
+ be used in new certificates in place of the extension/attribute
+ MonetaryLimit since January 1, 2004. For the sake of backward
+ compatibility with certificates already in use, SigG conforming
+ components MUST support MonetaryLimit (as well as QcEuLimitValue).
+
+
+ A declaration of majority. May be used as attribute in attribute
+ certificate or as extension in a certificate
+
+
+
+ Serial number of the smart card containing the corresponding private key
+
+
+ ICCSNSyntax ::= OCTET STRING (SIZE(8..20))
+
+
+
+
+ Reference for a file of a smartcard that stores the public key of this
+ certificate and that is used as �security anchor�.
+
+
+ PKReferenceSyntax ::= OCTET STRING (SIZE(20))
+
+
+
+ Some other restriction regarding the usage of this certificate. May be
+ used as attribute in attribute certificate or as extension in a
+ certificate.
+
+
+
+ @see Org.BouncyCastle.Asn1.IsisMtt.X509.Restriction
+
+
+
+ (Single)Request extension: Clients may include this extension in a
+ (single) Request to request the responder to send the certificate in the
+ response message along with the status information. Besides the LDAP
+ service, this extension provides another mechanism for the distribution
+ of certificates, which MAY optionally be provided by certificate
+ repositories.
+
+
+ RetrieveIfAllowed ::= BOOLEAN
+
+
+
+ SingleOCSPResponse extension: The certificate requested by the client by
+ inserting the RetrieveIfAllowed extension in the request, will be
+ returned in this extension.
+
+ @see Org.BouncyCastle.Asn1.IsisMtt.Ocsp.RequestedCertificate
+
+
+ Base ObjectIdentifier for naming authorities
+
+
+ SingleOCSPResponse extension: Date, when certificate has been published
+ in the directory and status information has become available. Currently,
+ accrediting authorities enforce that SigG-conforming OCSP servers include
+ this extension in the responses.
+
+
+ CertInDirSince ::= GeneralizedTime
+
+
+
+ Hash of a certificate in OCSP.
+
+ @see Org.BouncyCastle.Asn1.IsisMtt.Ocsp.CertHash
+
+
+
+ NameAtBirth ::= DirectoryString(SIZE(1..64)
+
+
+ Used in
+ {@link Org.BouncyCastle.Asn1.X509.SubjectDirectoryAttributes SubjectDirectoryAttributes}
+
+
+ Some other information of non-restrictive nature regarding the usage of
+ this certificate. May be used as attribute in atribute certificate or as
+ extension in a certificate.
+
+
+
+ @see Org.BouncyCastle.Asn1.IsisMtt.X509.AdditionalInformationSyntax
+
+
+ Indicates that an attribute certificate exists, which limits the
+ usability of this public key certificate. Whenever verifying a signature
+ with the help of this certificate, the content of the corresponding
+ attribute certificate should be concerned. This extension MUST be
+ included in a PKC, if a corresponding attribute certificate (having the
+ PKC as base certificate) contains some attribute that restricts the
+ usability of the PKC too. Attribute certificates with restricting content
+ MUST always be included in the signed document.
+
+
+ LiabilityLimitationFlagSyntax ::= BOOLEAN
+
+
+
+ ISIS-MTT PROFILE: The responder may include this extension in a response to
+ send the hash of the requested certificate to the responder. This hash is
+ cryptographically bound to the certificate and serves as evidence that the
+ certificate is known to the responder (i.e. it has been issued and is present
+ in the directory). Hence, this extension is a means to provide a positive
+ statement of availability as described in T8.[8]. As explained in T13.[1],
+ clients may rely on this information to be able to validate signatures after
+ the expiry of the corresponding certificate. Hence, clients MUST support this
+ extension. If a positive statement of availability is to be delivered, this
+ extension syntax and OID MUST be used.
+
+
+
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructor from a given details.
+
+ @param hashAlgorithm The hash algorithm identifier.
+ @param certificateHash The hash of the whole DER encoding of the certificate.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @return an Asn1Object
+
+
+ ISIS-MTT-Optional: The certificate requested by the client by inserting the
+ RetrieveIfAllowed extension in the request, will be returned in this
+ extension.
+
+ ISIS-MTT-SigG: The signature act allows publishing certificates only then,
+ when the certificate owner gives his isExplicit permission. Accordingly, there
+ may be �nondownloadable� certificates, about which the responder must provide
+ status information, but MUST NOT include them in the response. Clients may
+ get therefore the following three kind of answers on a single request
+ including the RetrieveIfAllowed extension:
+
+
a) the responder supports the extension and is allowed to publish the
+ certificate: RequestedCertificate returned including the requested
+ certificate
+
b) the responder supports the extension but is NOT allowed to publish
+ the certificate: RequestedCertificate returned including an empty OCTET
+ STRING
+
c) the responder does not support the extension: RequestedCertificate is
+ not included in the response
+
+ Clients requesting RetrieveIfAllowed MUST be able to handle these cases. If
+ any of the OCTET STRING options is used, it MUST contain the DER encoding of
+ the requested certificate.
+
+
+
+
+ Constructor from a given details.
+
+ Only one parameter can be given. All other must be null.
+
+ @param certificate Given as Certificate
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+
+ Constructor from a given details.
+
+ @param information The describtion of the information.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructor from a given details.
+
+ Parameter professionInfos is mandatory.
+
+ @param admissionAuthority The admission authority.
+ @param namingAuthority The naming authority.
+ @param professionInfos The profession infos.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+
+ ISIS-MTT PROFILE: The relatively complex structure of AdmissionSyntax
+ supports the following concepts and requirements:
+
+
External institutions (e.g. professional associations, chambers, unions,
+ administrative bodies, companies, etc.), which are responsible for granting
+ and verifying professional admissions, are indicated by means of the data
+ field admissionAuthority. An admission authority is indicated by a
+ GeneralName object. Here an X.501 directory name (distinguished name) can be
+ indicated in the field directoryName, a URL address can be indicated in the
+ field uniformResourceIdentifier, and an object identifier can be indicated in
+ the field registeredId.
+
The names of authorities which are responsible for the administration of
+ title registers are indicated in the data field namingAuthority. The name of
+ the authority can be identified by an object identifier in the field
+ namingAuthorityId, by means of a text string in the field
+ namingAuthorityText, by means of a URL address in the field
+ namingAuthorityUrl, or by a combination of them. For example, the text string
+ can contain the name of the authority, the country and the name of the title
+ register. The URL-option refers to a web page which contains lists with
+ �officially� registered professions (text and possibly OID) as well as
+ further information on these professions. Object identifiers for the
+ component namingAuthorityId are grouped under the OID-branch
+ id-isis-at-namingAuthorities and must be applied for.
+
See http://www.teletrust.de/anwend.asp?Id=30200&Sprache=E_&HomePG=0
+ for an application form and http://www.teletrust.de/links.asp?id=30220,11
+ for an overview of registered naming authorities.
+
By means of the data type ProfessionInfo certain professions,
+ specializations, disciplines, fields of activity, etc. are identified. A
+ profession is represented by one or more text strings, resp. profession OIDs
+ in the fields professionItems and professionOIDs and by a registration number
+ in the field registrationNumber. An indication in text form must always be
+ present, whereas the other indications are optional. The component
+ addProfessionInfo may contain additional applicationspecific information in
+ DER-encoded form.
+
+
+ By means of different namingAuthority-OIDs or profession OIDs hierarchies of
+ professions, specializations, disciplines, fields of activity, etc. can be
+ expressed. The issuing admission authority should always be indicated (field
+ admissionAuthority), whenever a registration number is presented. Still,
+ information on admissions can be given without indicating an admission or a
+ naming authority by the exclusive use of the component professionItems. In
+ this case the certification authority is responsible for the verification of
+ the admission information.
+
+
+
+ This attribute is single-valued. Still, several admissions can be captured in
+ the sequence structure of the component contentsOfAdmissions of
+ AdmissionSyntax or in the component professionInfos of Admissions. The
+ component admissionAuthority of AdmissionSyntax serves as default value for
+ the component admissionAuthority of Admissions. Within the latter component
+ the default value can be overwritten, in case that another authority is
+ responsible. The component namingAuthority of Admissions serves as a default
+ value for the component namingAuthority of ProfessionInfo. Within the latter
+ component the default value can be overwritten, in case that another naming
+ authority needs to be recorded.
+
+ The length of the string objects is limited to 128 characters. It is
+ recommended to indicate a namingAuthorityURL in all issued attribute
+ certificates. If a namingAuthorityURL is indicated, the field professionItems
+ of ProfessionInfo should contain only registered titles. If the field
+ professionOIDs exists, it has to contain the OIDs of the professions listed
+ in professionItems in the same order. In general, the field professionInfos
+ should contain only one entry, unless the admissions that are to be listed
+ are logically connected (e.g. they have been issued under the same admission
+ number).
+
+ @see Org.BouncyCastle.Asn1.IsisMtt.X509.Admissions
+ @see Org.BouncyCastle.Asn1.IsisMtt.X509.ProfessionInfo
+ @see Org.BouncyCastle.Asn1.IsisMtt.X509.NamingAuthority
+
+
+ Constructor from Asn1Sequence.
+
+ The sequence is of type ProcurationSyntax:
+
+
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructor from given details.
+
+ @param admissionAuthority The admission authority.
+ @param contentsOfAdmissions The admissions.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ fullAgeAtCountry indicates the majority of the owner with respect to the laws
+ of a specific country.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @return an Asn1Object
+
+
+ @return notYoungerThan if that's what we are, -1 otherwise
+
+
+ Monetary limit for transactions. The QcEuMonetaryLimit QC statement MUST be
+ used in new certificates in place of the extension/attribute MonetaryLimit
+ since January 1, 2004. For the sake of backward compatibility with
+ certificates already in use, components SHOULD support MonetaryLimit (as well
+ as QcEuLimitValue).
+
+ Indicates a monetary limit within which the certificate holder is authorized
+ to act. (This value DOES NOT express a limit on the liability of the
+ certification authority).
+
+
+
+ currency must be the ISO code.
+
+ value = amount�10*exponent
+
+
+ Constructor from a given details.
+
+
+ value = amount�10^exponent
+
+ @param currency The currency. Must be the ISO code.
+ @param amount The amount
+ @param exponent The exponent
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+ @see Org.BouncyCastle.Asn1.IsisMtt.X509.AdmissionSyntax
+
+
+
+ Profession OIDs should always be defined under the OID branch of the
+ responsible naming authority. At the time of this writing, the work group
+ �Recht, Wirtschaft, Steuern� (�Law, Economy, Taxes�) is registered as the
+ first naming authority under the OID id-isismtt-at-namingAuthorities.
+
+
+ Constructor from Asn1Sequence.
+
+
+
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructor from given details.
+
+ All parameters can be combined.
+
+ @param namingAuthorityID ObjectIdentifier for naming authority.
+ @param namingAuthorityUrl URL for naming authority.
+ @param namingAuthorityText Textual representation of naming authority.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @return an Asn1Object
+
+
+ @return Returns the namingAuthorityID.
+
+
+ @return Returns the namingAuthorityText.
+
+
+ @return Returns the namingAuthorityUrl.
+
+
+ Attribute to indicate that the certificate holder may sign in the name of a
+ third person.
+
+ ISIS-MTT PROFILE: The corresponding ProcurationSyntax contains either the
+ name of the person who is represented (subcomponent thirdPerson) or a
+ reference to his/her base certificate (in the component signingFor,
+ subcomponent certRef), furthermore the optional components country and
+ typeSubstitution to indicate the country whose laws apply, and respectively
+ the type of procuration (e.g. manager, procuration, custody).
+
+
+ ISIS-MTT PROFILE: The GeneralName MUST be of type directoryName and MAY only
+ contain: - RFC3039 attributes, except pseudonym (countryName, commonName,
+ surname, givenName, serialNumber, organizationName, organizationalUnitName,
+ stateOrProvincename, localityName, postalAddress) and - SubjectDirectoryName
+ attributes (title, dateOfBirth, placeOfBirth, gender, countryOfCitizenship,
+ countryOfResidence and NameAtBirth).
+
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructor from a given details.
+
+
+ Either generalName or certRef MUST be
+ null.
+
+ @param country The country code whose laws apply.
+ @param typeOfSubstitution The type of procuration.
+ @param certRef Reference to certificate of the person who is represented.
+
+
+ Constructor from a given details.
+
+
+ Either generalName or certRef MUST be
+ null.
+
+ @param country The country code whose laws apply.
+ @param typeOfSubstitution The type of procuration.
+ @param thirdPerson The GeneralName of the person who is represented.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructor from given details.
+
+ professionItems is mandatory, all other parameters are
+ optional.
+
+ @param namingAuthority The naming authority.
+ @param professionItems Directory strings of the profession.
+ @param professionOids DERObjectIdentfier objects for the
+ profession.
+ @param registrationNumber Registration number.
+ @param addProfessionInfo Additional infos in encoded form.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @return an Asn1Object
+
+
+ @return Returns the professionItems.
+
+
+ @return Returns the professionOids.
+
+
+ @return Returns the addProfessionInfo.
+
+
+ @return Returns the namingAuthority.
+
+
+ @return Returns the registrationNumber.
+
+
+ Some other restriction regarding the usage of this certificate.
+
+
+
+ @param restriction A IAsn1String.
+
+
+ Constructor from a given details.
+
+ @param restriction The description of the restriction.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+ NetscapeCertType ::= BIT STRING {
+ SSLClient (0),
+ SSLServer (1),
+ S/MIME (2),
+ Object Signing (3),
+ Reserved (4),
+ SSL CA (5),
+ S/MIME CA (6),
+ Object Signing CA (7) }
+
+
+
+ Basic constructor.
+
+ @param usage - the bitwise OR of the Key Usage flags giving the
+ allowed uses for the key.
+ e.g. (X509NetscapeCertType.sslCA | X509NetscapeCertType.smimeCA)
+
+
+ This is designed to parse
+ the PublicKeyAndChallenge created by the KEYGEN tag included by
+ Mozilla based browsers.
+
+
+
+ Utility class for fetching curves using their NIST names as published in FIPS-PUB 186-2
+
+
+ return the X9ECParameters object for the named curve represented by
+ the passed in object identifier. Null if the curve isn't present.
+
+ @param oid an object identifier representing a named curve, if present.
+
+
+ return the object identifier signified by the passed in name. Null
+ if there is no object identifier associated with name.
+
+ @return the object identifier associated with name, if present.
+
+
+ return the named curve name represented by the given object identifier.
+
+
+ returns an enumeration containing the name strings for curves
+ contained in this structure.
+
+
+ From RFC 3657
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ class for breaking up an Oid into it's component tokens, ala
+ java.util.StringTokenizer. We need this class as some of the
+ lightweight Java environment don't support classes like
+ StringTokenizer.
+
+
+ return an Attribute object from the given object.
+
+ @param o the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Attr ::= Sequence {
+ attrType OBJECT IDENTIFIER,
+ attrValues Set OF AttributeValue
+ }
+
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ AlgorithmIdentifier ::= Sequence {
+ algorithm OBJECT IDENTIFIER,
+ parameters ANY DEFINED BY algorithm OPTIONAL }
+
+
+
+
+ MacData ::= SEQUENCE {
+ mac DigestInfo,
+ macSalt OCTET STRING,
+ iterations INTEGER DEFAULT 1
+ -- Note: The default is for historic reasons and its use is deprecated. A
+ -- higher value, like 1024 is recommended.
+
+ @return the basic DERObject construction.
+
+
+ the infamous Pfx from Pkcs12
+
+
+ write out an RSA private key with its associated information
+ as described in Pkcs8.
+
+ @return the asn1 primitive representing the parameters.
+
+
+ This outputs the key in Pkcs1v2 format.
+
+ RsaPrivateKey ::= Sequence {
+ version Version,
+ modulus Integer, -- n
+ publicExponent Integer, -- e
+ privateExponent Integer, -- d
+ prime1 Integer, -- p
+ prime2 Integer, -- q
+ exponent1 Integer, -- d mod (p-1)
+ exponent2 Integer, -- d mod (q-1)
+ coefficient Integer -- (inverse of q) mod p
+ }
+
+ Version ::= Integer
+
+
This routine is written to output Pkcs1 version 0, private keys.
+ @return the asn1 primitive representing the parameters.
+
+
+ a Pkcs#7 signed data object.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ the elliptic curve private key object from SEC 1
+
+
+ ECPrivateKey ::= SEQUENCE {
+ version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
+ privateKey OCTET STRING,
+ parameters [0] Parameters OPTIONAL,
+ publicKey [1] BIT STRING OPTIONAL }
+
+
+ return the X9ECParameters object for the named curve represented by
+ the passed in object identifier. Null if the curve isn't present.
+
+ @param oid an object identifier representing a named curve, if present.
+
+
+ return the object identifier signified by the passed in name. Null
+ if there is no object identifier associated with name.
+
+ @return the object identifier associated with name, if present.
+
+
+ return the named curve name represented by the given object identifier.
+
+
+ returns an enumeration containing the name strings for curves
+ contained in this structure.
+
+
+ EllipticCurve OBJECT IDENTIFIER ::= {
+ iso(1) identified-organization(3) certicom(132) curve(0)
+ }
+
+
+ Handler class for dealing with S/MIME Capabilities
+
+
+ general preferences
+
+
+ encryption algorithms preferences
+
+
+ return an Attr object from the given object.
+
+ @param o the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ returns an ArrayList with 0 or more objects of all the capabilities
+ matching the passed in capability Oid. If the Oid passed is null the
+ entire set is returned.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ SMIMECapabilities ::= Sequence OF SMIMECapability
+
+
+
+ return an Attr object from the given object.
+
+ @param o the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Attr ::= Sequence {
+ attrType OBJECT IDENTIFIER,
+ attrValues Set OF AttributeValue
+ }
+
+
+
+ general preferences
+
+
+ encryption algorithms preferences
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ SMIMECapability ::= Sequence {
+ capabilityID OBJECT IDENTIFIER,
+ parameters ANY DEFINED BY capabilityID OPTIONAL
+ }
+
+
+
+ Handler for creating a vector S/MIME Capabilities
+
+
+ The SmimeEncryptionKeyPreference object.
+
+
+
+ @param sKeyId the subjectKeyIdentifier value (normally the X.509 one)
+
+
+ elliptic curves defined in "ECC Brainpool Standard Curves and Curve Generation"
+ http://www.ecc-brainpool.org/download/draft_pkix_additional_ecc_dp.txt
+
+
+ return the X9ECParameters object for the named curve represented by
+ the passed in object identifier. Null if the curve isn't present.
+
+ @param oid an object identifier representing a named curve, if present.
+
+
+ return the object identifier signified by the passed in name. Null
+ if there is no object identifier associated with name.
+
+ @return the object identifier associated with name, if present.
+
+
+ return the named curve name represented by the given object identifier.
+
+
+ returns an enumeration containing the name strings for curves
+ contained in this structure.
+
+
+
+
+ TstInfo ::= SEQUENCE {
+ version INTEGER { v1(1) },
+ policy TSAPolicyId,
+ messageImprint MessageImprint,
+ -- MUST have the same value as the similar field in
+ -- TimeStampReq
+ serialNumber INTEGER,
+ -- Time-Stamping users MUST be ready to accommodate integers
+ -- up to 160 bits.
+ genTime GeneralizedTime,
+ accuracy Accuracy OPTIONAL,
+ ordering BOOLEAN DEFAULT FALSE,
+ nonce INTEGER OPTIONAL,
+ -- MUST be present if the similar field was present
+ -- in TimeStampReq. In that case it MUST have the same value.
+ tsa [0] GeneralName OPTIONAL,
+ extensions [1] IMPLICIT Extensions OPTIONAL }
+
+
+
+
+ dump a Der object as a formatted string with indentation
+
+ @param obj the Asn1Object to be dumped out.
+
+
+ dump out a DER object as a formatted string, in non-verbose mode
+
+ @param obj the Asn1Encodable to be dumped out.
+ @return the resulting string.
+
+
+ Dump out the object as a string
+
+ @param obj the Asn1Encodable to be dumped out.
+ @param verbose if true, dump out the contents of octet and bit strings.
+ @return the resulting string.
+
+
+
+
+
+ create an AccessDescription with the oid and location provided.
+
+
+
+ @return the access method.
+
+
+
+ @return the access location
+
+
+
+ Don't use this one if you are trying to be RFC 3281 compliant.
+ Use it for v1 attribute certificates only.
+
+ Our GeneralNames structure
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ AttCertIssuer ::= CHOICE {
+ v1Form GeneralNames, -- MUST NOT be used in this
+ -- profile
+ v2Form [0] V2Form -- v2 only
+ }
+
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+
+ *
+ * Calulates the keyidentifier using a SHA1 hash over the BIT STRING
+ * from SubjectPublicKeyInfo as defined in RFC2459.
+ *
+ * Example of making a AuthorityKeyIdentifier:
+ *
+ * SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence)new ASN1InputStream(
+ * publicKey.getEncoded()).readObject());
+ * AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
+ *
+ *
+ *
+
+
+ create an AuthorityKeyIdentifier with the GeneralNames tag and
+ the serial number provided as well.
+
+
+ create an AuthorityKeyIdentifier with the GeneralNames tag and
+ the serial number provided.
+
+
+ create an AuthorityKeyIdentifier with a precomputed key identifier
+
+
+ create an AuthorityKeyIdentifier with a precomupted key identifier
+ and the GeneralNames tag and the serial number provided as well.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+ create a cA=true object for the given path length constraint.
+
+ @param pathLenConstraint
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ This class helps to support crossCerfificatePairs in a LDAP directory
+ according RFC 2587
+
+
+ crossCertificatePairATTRIBUTE::={
+ WITH SYNTAX CertificatePair
+ EQUALITY MATCHING RULE certificatePairExactMatch
+ ID joint-iso-ccitt(2) ds(5) attributeType(4) crossCertificatePair(40)}
+
+
+
The forward elements of the crossCertificatePair attribute of a
+ CA's directory entry shall be used to store all, except self-issued
+ certificates issued to this CA. Optionally, the reverse elements of the
+ crossCertificatePair attribute, of a CA's directory entry may contain a
+ subset of certificates issued by this CA to other CAs. When both the forward
+ and the reverse elements are present in a single attribute value, issuer name
+ in one certificate shall match the subject name in the other and vice versa,
+ and the subject public key in one certificate shall be capable of verifying
+ the digital signature on the other certificate and vice versa.
+
+ When a reverse element is present, the forward element value and the reverse
+ element value need not be stored in the same attribute value; in other words,
+ they can be stored in either a single attribute value or two attribute
+ values.
+
+
+ CertificatePair ::= SEQUENCE {
+ forward [0] Certificate OPTIONAL,
+ reverse [1] Certificate OPTIONAL,
+ -- at least one of the pair shall be present -- }
+
+
+
+ Constructor from Asn1Sequence.
+
+ The sequence is of type CertificatePair:
+
+
+ CertificatePair ::= SEQUENCE {
+ forward [0] Certificate OPTIONAL,
+ reverse [1] Certificate OPTIONAL,
+ -- at least one of the pair shall be present -- }
+
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructor from a given details.
+
+ @param forward Certificates issued to this CA.
+ @param reverse Certificates issued by this CA to other CAs.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+ CertificatePair ::= SEQUENCE {
+ forward [0] Certificate OPTIONAL,
+ reverse [1] Certificate OPTIONAL,
+ -- at least one of the pair shall be present -- }
+
+
+ @return a DERObject
+
+
+ @return Returns the forward.
+
+
+ @return Returns the reverse.
+
+
+ CertPolicyId, used in the CertificatePolicies and PolicyMappings
+ X509V3 Extensions.
+
+
+ CertPolicyId ::= OBJECT IDENTIFIER
+
+
+
+ Return the distribution points making up the sequence.
+
+ @return DistributionPoint[]
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ CrlDistPoint ::= Sequence SIZE {1..MAX} OF DistributionPoint
+
+ @see PolicyQualifierInfo
+ @see PolicyInformation
+
+
+ Constant corresponding to ia5String encoding.
+
+
+
+ Constant corresponding to bmpString encoding.
+
+
+
+ Constant corresponding to utf8String encoding.
+
+
+
+ Constant corresponding to visibleString encoding.
+
+
+
+ Describe constant DisplayTextMaximumSize here.
+
+
+
+ Creates a new DisplayText instance.
+
+ @param type the desired encoding type for the text.
+ @param text the text to store. Strings longer than 200
+ characters are truncated.
+
+
+ Creates a new DisplayText instance.
+
+ @param text the text to encapsulate. Strings longer than 200
+ characters are truncated.
+
+
+ Creates a new DisplayText instance.
+
Useful when reading back a DisplayText class
+ from it's Asn1Encodable form.
+
+ @param contents an Asn1Encodable instance.
+
+
+ Returns the stored string object.
+
+ @return the stored text as a string.
+
+
+ The DistributionPoint object.
+
+ extendedKeyUsage ::= Sequence SIZE (1..MAX) OF KeyPurposeId
+
+
+
+ Returns all extended key usages.
+ The returned ArrayList contains DerObjectIdentifier instances.
+ @return An ArrayList with all key purposes.
+
+
+ The GeneralName object.
+
+
+
+ When the subjectAltName extension contains an Internet mail address,
+ the address MUST be included as an rfc822Name. The format of an
+ rfc822Name is an "addr-spec" as defined in RFC 822 [RFC 822].
+
+ When the subjectAltName extension contains a domain name service
+ label, the domain name MUST be stored in the dNSName (an IA5String).
+ The name MUST be in the "preferred name syntax," as specified by RFC
+ 1034 [RFC 1034].
+
+ When the subjectAltName extension contains a URI, the name MUST be
+ stored in the uniformResourceIdentifier (an IA5String). The name MUST
+ be a non-relative URL, and MUST follow the URL syntax and encoding
+ rules specified in [RFC 1738]. The name must include both a scheme
+ (e.g., "http" or "ftp") and a scheme-specific-part. The scheme-
+ specific-part must include a fully qualified domain name or IP
+ address as the host.
+
+ When the subjectAltName extension contains a iPAddress, the address
+ MUST be stored in the octet string in "network byte order," as
+ specified in RFC 791 [RFC 791]. The least significant bit (LSB) of
+ each octet is the LSB of the corresponding byte in the network
+ address. For IP Version 4, as specified in RFC 791, the octet string
+ MUST contain exactly four octets. For IP Version 6, as specified in
+ RFC 1883, the octet string MUST contain exactly sixteen octets [RFC
+ 1883].
+
+
+ Create a GeneralName for the given tag from the passed in string.
+
+ This constructor can handle:
+
+
rfc822Name
+
iPAddress
+
directoryName
+
dNSName
+
uniformResourceIdentifier
+
registeredID
+
+ For x400Address, otherName and ediPartyName there is no common string
+ format defined.
+
+ Note: A directory name can be encoded in different ways into a byte
+ representation. Be aware of this if the byte representation is used for
+ comparing results.
+
+
+ @param tag tag number
+ @param name string representation of name
+ @throws ArgumentException if the string encoding is not correct or
+ not supported.
+
+
+ Construct a GeneralNames object containing one GeneralName.
+ The name to be contained.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ GeneralNames ::= Sequence SIZE {1..MAX} OF GeneralName
+
+
+
+ Class for containing a restriction object subtrees in NameConstraints. See
+ RFC 3280.
+
+
+
+ @see org.bouncycastle.asn1.x509.NameConstraints
+
+
+
+ Constructor from a given details.
+
+ According RFC 3280, the minimum and maximum fields are not used with any
+ name forms, thus minimum MUST be zero, and maximum MUST be absent.
+
+ If minimum is null, zero is assumed, if
+ maximum is null, maximum is absent.
+
+ @param baseName
+ A restriction.
+ @param minimum
+ Minimum
+
+ @param maximum
+ Maximum
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @return a DERObject
+
+
+ The Holder object.
+
+ For an v2 attribute certificate this is:
+
+
+ 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
+ }
+
+
+
+ For an v1 attribute certificate this is:
+
+
+ subject CHOICE {
+ baseCertificateID [0] IssuerSerial,
+ -- associated with a Public Key Certificate
+ subjectName [1] GeneralNames },
+ -- associated with a name
+
+
+
+
+ Constructor for a holder for an v1 attribute certificate.
+
+ @param tagObj The ASN.1 tagged holder object.
+
+
+ Constructor for a holder for an v2 attribute certificate. *
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructs a holder from a IssuerSerial.
+ @param baseCertificateID The IssuerSerial.
+ @param version The version of the attribute certificate.
+
+
+ Constructs a holder with an entityName for v2 attribute certificates or
+ with a subjectName for v1 attribute certificates.
+
+ @param entityName The entity or subject name.
+
+
+ Constructs a holder with an entityName for v2 attribute certificates or
+ with a subjectName for v1 attribute certificates.
+
+ @param entityName The entity or subject name.
+ @param version The version of the attribute certificate.
+
+
+ Constructs a holder from an object digest info.
+
+ @param objectDigestInfo The object digest info object.
+
+
+ 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
+ }
+
+
+
+ Returns 1 for v2 attribute certificates or 0 for v1 attribute
+ certificates.
+ @return The version of the attribute certificate.
+
+
+ Returns the entityName for an v2 attribute certificate or the subjectName
+ for an v1 attribute certificate.
+
+ @return The entityname or subjectname.
+
+
+ Implementation of IetfAttrSyntax as specified by RFC3281.
+
+
+
+
+
+
+
+
+
+ Constructor from given details.
+
+ @param distributionPoint
+ May contain an URI as pointer to most current CRL.
+ @param onlyContainsUserCerts Covers revocation information for end certificates.
+ @param onlyContainsCACerts Covers revocation information for CA certificates.
+
+ @param onlySomeReasons
+ Which revocation reasons does this point cover.
+ @param indirectCRL
+ If true then the CRL contains revocation
+ information about certificates ssued by other CAs.
+ @param onlyContainsAttributeCerts Covers revocation information for attribute certificates.
+
+
+ Constructor from Asn1Sequence
+
+
+ @return Returns the distributionPoint.
+
+
+ @return Returns the onlySomeReasons.
+
+
+ The KeyPurposeID object.
+
+
+
+ Basic constructor.
+
+ @param usage - the bitwise OR of the Key Usage flags giving the
+ allowed uses for the key.
+ e.g. (KeyUsage.keyEncipherment | KeyUsage.dataEncipherment)
+
+
+ Constructor from a given details.
+
+
permitted and excluded are Vectors of GeneralSubtree objects.
+
+ @param permitted Permitted subtrees
+ @param excluded Excluded subtrees
+
+
+ NoticeReference class, used in
+ CertificatePolicies X509 V3 extensions
+ (in policy qualifiers).
+
+
+
+ @see PolicyQualifierInfo
+ @see PolicyInformation
+
+
+ Creates a new NoticeReference instance.
+
+ @param orgName a string value
+ @param numbers a ArrayList value
+
+
+ Creates a new NoticeReference instance.
+
+ @param orgName a string value
+ @param numbers an Asn1Sequence value
+
+
+ Creates a new NoticeReference instance.
+
+ @param displayTextType an int value
+ @param orgName a string value
+ @param numbers an Asn1Sequence value
+
+
+ Creates a new NoticeReference instance.
+
Useful for reconstructing a NoticeReference
+ instance from its encodable/encoded form.
+
+ @param as an Asn1Sequence value obtained from either
+ calling @{link ToAsn1Object()} for a NoticeReference
+ instance or from parsing it from a Der-encoded stream.
+
+
+ Describe ToAsn1Object method here.
+
+ @return a Asn1Object value
+
+
+ ObjectDigestInfo ASN.1 structure used in v2 attribute certificates.
+
+
+
+ ObjectDigestInfo ::= SEQUENCE {
+ digestedObjectType ENUMERATED {
+ publicKey (0),
+ publicKeyCert (1),
+ otherObjectTypes (2) },
+ -- otherObjectTypes MUST NOT
+ -- be used in this profile
+ otherObjectTypeID OBJECT IDENTIFIER OPTIONAL,
+ digestAlgorithm AlgorithmIdentifier,
+ objectDigest BIT STRING
+ }
+
+
+
+
+
+ The public key is hashed.
+
+
+ The public key certificate is hashed.
+
+
+ An other object is hashed.
+
+
+ Constructor from given details.
+
+ If digestedObjectType is not {@link #publicKeyCert} or
+ {@link #publicKey} otherObjectTypeID must be given,
+ otherwise it is ignored.
+
+ @param digestedObjectType The digest object type.
+ @param otherObjectTypeID The object type ID for
+ otherObjectDigest.
+ @param digestAlgorithm The algorithm identifier for the hash.
+ @param objectDigest The hash value.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ ObjectDigestInfo ::= SEQUENCE {
+ digestedObjectType ENUMERATED {
+ publicKey (0),
+ publicKeyCert (1),
+ otherObjectTypes (2) },
+ -- otherObjectTypes MUST NOT
+ -- be used in this profile
+ otherObjectTypeID OBJECT IDENTIFIER OPTIONAL,
+ digestAlgorithm AlgorithmIdentifier,
+ objectDigest BIT STRING
+ }
+
+
+
+
+ PolicyMappings V3 extension, described in RFC3280.
+
+
+ @see RFC 3280, section 4.2.1.6
+
+
+ Creates a new PolicyMappings instance.
+
+ @param seq an Asn1Sequence constructed as specified
+ in RFC 3280
+
+
+ Creates a new PolicyMappings instance.
+
+ @param mappings a HashMap value that maps
+ string oids
+ to other string oids.
+
+
+ PolicyQualifierId, used in the CertificatePolicies
+ X509V3 extension.
+
+
+
+
+ Policy qualifiers, used in the X509V3 CertificatePolicies
+ extension.
+
+
+ PolicyQualifierInfo ::= Sequence {
+ policyQualifierId PolicyQualifierId,
+ qualifier ANY DEFINED BY policyQualifierId }
+
+
+
+ Creates a new PolicyQualifierInfo instance.
+
+ @param policyQualifierId a PolicyQualifierId value
+ @param qualifier the qualifier, defined by the above field.
+
+
+ Creates a new PolicyQualifierInfo containing a
+ cPSuri qualifier.
+
+ @param cps the CPS (certification practice statement) uri as a
+ string.
+
+
+ Creates a new PolicyQualifierInfo instance.
+
+ @param as PolicyQualifierInfo X509 structure
+ encoded as an Asn1Sequence.
+
+
+ Returns a Der-encodable representation of this instance.
+
+ @return a Asn1Object value
+
+
+
+
+ Iso4217CurrencyCode ::= CHOICE {
+ alphabetic PrintableString (SIZE 3), --Recommended
+ numeric INTEGER (1..999) }
+ -- Alphabetic or numeric currency code as defined in ISO 4217
+ -- It is recommended that the Alphabetic form is used
+
+
+
+ @param reasons - the bitwise OR of the Key Reason flags giving the
+ allowed uses for the key.
+
+
+ Implementation of the RoleSyntax object as specified by the RFC3281.
+
+
+
+
+ RoleSyntax factory method.
+ @param obj the object used to construct an instance of
+ RoleSyntax. It must be an instance of RoleSyntax
+ or Asn1Sequence.
+ @return the instance of RoleSyntax built from the
+ supplied object.
+ @throws java.lang.ArgumentException if the object passed
+ to the factory is not an instance of RoleSyntax or
+ Asn1Sequence.
+
+
+ Constructor.
+ @param roleAuthority the role authority of this RoleSyntax.
+ @param roleName the role name of this RoleSyntax.
+
+
+ Constructor. Invoking this constructor is the same as invoking
+ new RoleSyntax(null, roleName).
+ @param roleName the role name of this RoleSyntax.
+
+
+ Utility constructor. Takes a string argument representing
+ the role name, builds a GeneralName to hold the role name
+ and calls the constructor that takes a GeneralName.
+ @param roleName
+
+
+ Constructor that builds an instance of RoleSyntax by
+ extracting the encoded elements from the Asn1Sequence
+ object supplied.
+ @param seq an instance of Asn1Sequence that holds
+ the encoded elements used to build this RoleSyntax.
+
+
+ Gets the role name as a java.lang.string object.
+ @return the role name of this RoleSyntax represented as a
+ string object.
+
+
+ Gets the role authority as a string[] object.
+ @return the role authority of this RoleSyntax represented as a
+ string[] array.
+
+
+ Implementation of the method ToAsn1Object as
+ required by the superclass ASN1Encodable.
+
+
+
+
+ Gets the role authority of this RoleSyntax.
+ @return an instance of GeneralNames holding the
+ role authority of this RoleSyntax.
+
+
+ Gets the role name of this RoleSyntax.
+ @return an instance of GeneralName holding the
+ role name of this RoleSyntax.
+
+
+ This outputs the key in Pkcs1v2 format.
+
+ RSAPublicKey ::= Sequence {
+ modulus Integer, -- n
+ publicExponent Integer, -- e
+ }
+
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructor from a given details.
+
+ @param pseudonym The pseudonym.
+
+
+ Constructor from a given details.
+
+ @param surname The surname.
+ @param givenName A sequence of directory strings making up the givenName
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @see org.bouncycastle.asn1.x509.sigi.NameOrPseudonym
+ @see org.bouncycastle.asn1.x509.sigi.SigIObjectIdentifiers
+
+
+ Constructor from Asn1Sequence.
+
+ The sequence is of type NameOrPseudonym:
+
+
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructor from a given details.
+
+ @param nameOrPseudonym Name or pseudonym.
+ @param nameDistinguisher Name distinguisher.
+ @param dateOfBirth Date of birth.
+ @param placeOfBirth Place of birth.
+ @param gender Gender.
+ @param postalAddress Postal Address.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @return an Asn1Object
+
+
+ Object Identifiers of SigI specifciation (German Signature Law
+ Interoperability specification).
+
+
+ Key purpose IDs for German SigI (Signature Interoperability
+ Specification)
+
+
+ Certificate policy IDs for German SigI (Signature Interoperability
+ Specification)
+
+
+ Other Name IDs for German SigI (Signature Interoperability Specification)
+
+
+ To be used for for the generation of directory service certificates.
+
+
+ ID for PersonalData
+
+
+ Certificate is conform to german signature law.
+
+
+ This extension may contain further X.500 attributes of the subject. See also
+ RFC 3039.
+
+
+ SubjectDirectoryAttributes ::= Attributes
+ Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
+ Attribute ::= SEQUENCE
+ {
+ type AttributeType
+ values SET OF AttributeValue
+ }
+
+ AttributeType ::= OBJECT IDENTIFIER
+ AttributeValue ::= ANY DEFINED BY AttributeType
+
+
+ @see org.bouncycastle.asn1.x509.X509Name for AttributeType ObjectIdentifiers.
+
+
+ Constructor from Asn1Sequence.
+
+ The sequence is of type SubjectDirectoryAttributes:
+
+
+ SubjectDirectoryAttributes ::= Attributes
+ Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
+ Attribute ::= SEQUENCE
+ {
+ type AttributeType
+ values SET OF AttributeValue
+ }
+
+ AttributeType ::= OBJECT IDENTIFIER
+ AttributeValue ::= ANY DEFINED BY AttributeType
+
+
+ @param seq
+ The ASN.1 sequence.
+
+
+ Constructor from an ArrayList of attributes.
+
+ The ArrayList consists of attributes of type {@link Attribute Attribute}
+
+ @param attributes The attributes.
+
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+ SubjectDirectoryAttributes ::= Attributes
+ Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
+ Attribute ::= SEQUENCE
+ {
+ type AttributeType
+ values SET OF AttributeValue
+ }
+
+ AttributeType ::= OBJECT IDENTIFIER
+ AttributeValue ::= ANY DEFINED BY AttributeType
+
+
+ @return a DERObject
+
+
+ @return Returns the attributes.
+
+
+ The SubjectKeyIdentifier object.
+
+ SubjectKeyIdentifier::= OCTET STRING
+
+
+
+ Calculates the keyIdentifier using a SHA1 hash over the BIT STRING
+ from SubjectPublicKeyInfo as defined in RFC3280.
+
+ @param spki the subject public key info.
+
+
+ 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 keyInfo the key info object containing the subjectPublicKey field.
+ @return the key identifier.
+
+
+ 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 keyInfo the key info object containing the subjectPublicKey field.
+ @return the key identifier.
+
+
+ The object that contains the public key stored in a certficate.
+
+ The GetEncoded() method in the public keys in the JCE produces a DER
+ encoded one of these.
+
+
+ for when the public key is an encoded object - if the bitstring
+ can't be decoded this routine raises an IOException.
+
+ @exception IOException - if the bit string doesn't represent a Der
+ encoded object.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ for when the public key is raw bits...
+
+
+ Target structure used in target information extension for attribute
+ certificates from RFC 3281.
+
+
+ The targetCert field is currently not supported and must not be used
+ according to RFC 3281.
+
+
+ Creates an instance of a Target from the given object.
+
+ obj can be a Target or a {@link Asn1TaggedObject}
+
+ @param obj The object.
+ @return A Target instance.
+ @throws ArgumentException if the given object cannot be
+ interpreted as Target.
+
+
+ Constructor from Asn1TaggedObject.
+
+ @param tagObj The tagged object.
+ @throws ArgumentException if the encoding is wrong.
+
+
+ Constructor from given details.
+
+ Exactly one of the parameters must be not null.
+
+ @param type the choice type to apply to the name.
+ @param name the general name.
+ @throws ArgumentException if type is invalid.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @return an Asn1Object
+
+
+ @return Returns the targetGroup.
+
+
+ @return Returns the targetName.
+
+
+ Target information extension for attributes certificates according to RFC
+ 3281.
+
+
+ SEQUENCE OF Targets
+
+
+
+
+ Creates an instance of a TargetInformation from the given object.
+
+ obj can be a TargetInformation or a {@link Asn1Sequence}
+
+ @param obj The object.
+ @return A TargetInformation instance.
+ @throws ArgumentException if the given object cannot be interpreted as TargetInformation.
+
+
+ Constructor from a Asn1Sequence.
+
+ @param seq The Asn1Sequence.
+ @throws ArgumentException if the sequence does not contain
+ correctly encoded Targets elements.
+
+
+ Returns the targets in this target information extension.
+
+ The ArrayList is cloned before it is returned.
+
+ @return Returns the targets.
+
+
+ Constructs a target information from a single targets element.
+ According to RFC 3281 only one targets element must be produced.
+
+ @param targets A Targets instance.
+
+
+ According to RFC 3281 only one targets element must be produced. If
+ multiple targets are given they must be merged in
+ into one targets element.
+
+ @param targets An array with {@link Targets}.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+ SEQUENCE OF Targets
+
+
+
+ According to RFC 3281 only one targets element must be produced. If
+ multiple targets are given in the constructor they are merged into one
+ targets element. If this was produced from a
+ {@link Org.BouncyCastle.Asn1.Asn1Sequence} the encoding is kept.
+
+ @return an Asn1Object
+
+
+ Targets structure used in target information extension for attribute
+ certificates from RFC 3281.
+
+
+
+ @see org.bouncycastle.asn1.x509.Target
+ @see org.bouncycastle.asn1.x509.TargetInformation
+
+
+ Creates an instance of a Targets from the given object.
+
+ obj can be a Targets or a {@link Asn1Sequence}
+
+ @param obj The object.
+ @return A Targets instance.
+ @throws ArgumentException if the given object cannot be interpreted as Target.
+
+
+ Constructor from Asn1Sequence.
+
+ @param targets The ASN.1 SEQUENCE.
+ @throws ArgumentException if the contents of the sequence are
+ invalid.
+
+
+ Constructor from given targets.
+
+ The ArrayList is copied.
+
+ @param targets An ArrayList of {@link Target}s.
+ @see Target
+ @throws ArgumentException if the ArrayList contains not only Targets.
+
+
+ Returns the targets in an ArrayList.
+
+ The ArrayList is cloned before it is returned.
+
+ @return Returns the targets.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+ Targets ::= SEQUENCE OF Target
+
+
+ @return an Asn1Object
+
+
+ The TbsCertificate object.
+
+ Note: issuerUniqueID and subjectUniqueID are both deprecated by the IETF. This class
+ will parse them, but you really shouldn't be creating new ones.
+
+
+ PKIX RFC-2459 - TbsCertList object.
+
+ TbsCertList ::= Sequence {
+ version Version OPTIONAL,
+ -- if present, shall be v2
+ signature AlgorithmIdentifier,
+ issuer Name,
+ thisUpdate Time,
+ nextUpdate Time OPTIONAL,
+ revokedCertificates Sequence OF Sequence {
+ userCertificate CertificateSerialNumber,
+ revocationDate Time,
+ crlEntryExtensions Extensions OPTIONAL
+ -- if present, shall be v2
+ } OPTIONAL,
+ crlExtensions [0] EXPLICIT Extensions OPTIONAL
+ -- if present, shall be v2
+ }
+
+
+
+ creates a time object from a given date - if the date is between 1950
+ and 2049 a UTCTime object is Generated, otherwise a GeneralizedTime
+ is used.
+
+
+
+ Return our time as DateTime.
+
+ A date time.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+ @see PolicyQualifierId
+ @see PolicyInformation
+
+
+ Creates a new UserNotice instance.
+
+ @param noticeRef a NoticeReference value
+ @param explicitText a DisplayText value
+
+
+ Creates a new UserNotice instance.
+
+ @param noticeRef a NoticeReference value
+ @param str the explicitText field as a string.
+
+
+ Creates a new UserNotice instance.
+
Useful from reconstructing a UserNotice instance
+ from its encodable/encoded form.
+
+ @param as an ASN1Sequence value obtained from either
+ calling @{link toASN1Object()} for a UserNotice
+ instance or from parsing it from a DER-encoded stream.
+
+
+ Generator for Version 1 TbsCertificateStructures.
+
+
+
+
+ @param attribute
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ V2Form ::= Sequence {
+ issuerName GeneralNames OPTIONAL,
+ baseCertificateID [0] IssuerSerial OPTIONAL,
+ objectDigestInfo [1] ObjectDigestInfo OPTIONAL
+ -- issuerName MUST be present in this profile
+ -- baseCertificateID and objectDigestInfo MUST NOT
+ -- be present in this profile
+ }
+
+
+
+ Generator for Version 2 TbsCertList structures.
+
+ TbsCertList ::= Sequence {
+ version Version OPTIONAL,
+ -- if present, shall be v2
+ signature AlgorithmIdentifier,
+ issuer Name,
+ thisUpdate Time,
+ nextUpdate Time OPTIONAL,
+ revokedCertificates Sequence OF Sequence {
+ userCertificate CertificateSerialNumber,
+ revocationDate Time,
+ crlEntryExtensions Extensions OPTIONAL
+ -- if present, shall be v2
+ } OPTIONAL,
+ crlExtensions [0] EXPLICIT Extensions OPTIONAL
+ -- if present, shall be v2
+ }
+
+
+ Note: This class may be subject to change
+
+
+ Generator for Version 3 TbsCertificateStructures.
+
+
+
+ The default converter for X509 DN entries when going from their
+ string value to ASN.1 strings.
+
+
+ * It turns out that the number of standard ways the fields in a DN should be
+ * encoded into their ASN.1 counterparts is rapidly approaching the
+ * number of machines on the internet. By default the X509Name class
+ * will produce UTF8Strings in line with the current recommendations (RFC 3280).
+ *
+ *
+
+
+ Convert an inline encoded hex string rendition of an ASN.1
+ object back into its corresponding ASN.1 object.
+
+ @param str the hex encoded object
+ @param off the index at which the encoding starts
+ @return the decoded object
+
+
+ return true if the passed in string can be represented without
+ loss as a PrintableString, false otherwise.
+
+
+ Convert the passed in string value into the appropriate ASN.1
+ encoded object.
+
+ @param oid the oid associated with the value in the DN.
+ @param value the value of the particular DN component.
+ @return the ASN.1 equivalent for the value.
+
+
+ Apply default conversion for the given value depending on the oid
+ and the character range of the value.
+
+ @param oid the object identifier for the DN entry
+ @param value the value associated with it
+ @return the ASN.1 equivalent for the string value.
+
+
+ an object for the elements in the X.509 V3 extension block.
+
+
+ Convert the value of the passed in extension to an object.
+ The extension to parse.
+ The object the value string contains.
+ If conversion is not possible.
+
+
+ Subject Directory Attributes
+
+
+ Subject Key Identifier
+
+
+ Key Usage
+
+
+ Private Key Usage Period
+
+
+ Subject Alternative Name
+
+
+ Issuer Alternative Name
+
+
+ Basic Constraints
+
+
+ CRL Number
+
+
+ Reason code
+
+
+ Hold Instruction Code
+
+
+ Invalidity Date
+
+
+ Delta CRL indicator
+
+
+ Issuing Distribution Point
+
+
+ Certificate Issuer
+
+
+ Name Constraints
+
+
+ CRL Distribution Points
+
+
+ Certificate Policies
+
+
+ Policy Mappings
+
+
+ Authority Key Identifier
+
+
+ Policy Constraints
+
+
+ Extended Key Usage
+
+
+ Freshest CRL
+
+
+ Inhibit Any Policy
+
+
+ Authority Info Access
+
+
+ Subject Info Access
+
+
+ Logo Type
+
+
+ BiometricInfo
+
+
+ QCStatements
+
+
+ Audit identity extension in attribute certificates.
+
+
+ NoRevAvail extension in attribute certificates.
+
+
+ TargetInformation extension in attribute certificates.
+
+
+ Constructor from Asn1Sequence.
+
+ the extensions are a list of constructed sequences, either with (Oid, OctetString) or (Oid, Boolean, OctetString)
+
+
+ constructor from a table of extensions.
+
+ it's is assumed the table contains Oid/string pairs.
+
+
+ Constructor from a table of extensions with ordering.
+
+ It's is assumed the table contains Oid/string pairs.
+
+
+ Constructor from two vectors
+
+ @param objectIDs an ArrayList of the object identifiers.
+ @param values an ArrayList of the extension values.
+
+
+ return the extension represented by the object identifier
+ passed in.
+
+ @return the extension if it's present, null otherwise.
+
+
+
+
+
+ return an Enumeration of the extension field's object ids.
+
+
+ Generator for X.509 extensions
+
+
+ Reset the generator
+
+
+
+ Add an extension with the given oid and the passed in value to be included
+ in the OCTET STRING associated with the extension.
+
+ OID for the extension.
+ True if critical, false otherwise.
+ The ASN.1 object to be included in the extension.
+
+
+
+ Add an extension with the given oid and the passed in byte array to be wrapped
+ in the OCTET STRING associated with the extension.
+
+ OID for the extension.
+ True if critical, false otherwise.
+ The byte array to be wrapped.
+
+
+ Generate an X509Extensions object based on the current state of the generator.
+ An X509Extensions object
+
+
+ Return true if there are no extension present in this generator.
+ True if empty, false otherwise
+
+
+
+ RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
+
+ RelativeDistinguishedName ::= SET SIZE (1..MAX) OF AttributeTypeAndValue
+
+ AttributeTypeAndValue ::= SEQUENCE {
+ type OBJECT IDENTIFIER,
+ value ANY }
+
+
+
+ country code - StringType(SIZE(2))
+
+
+ organization - StringType(SIZE(1..64))
+
+
+ organizational unit name - StringType(SIZE(1..64))
+
+
+ Title
+
+
+ common name - StringType(SIZE(1..64))
+
+
+ street - StringType(SIZE(1..64))
+
+
+ device serial number name - StringType(SIZE(1..64))
+
+
+ locality name - StringType(SIZE(1..64))
+
+
+ state, or province name - StringType(SIZE(1..64))
+
+
+ Naming attributes of type X520name
+
+
+ businessCategory - DirectoryString(SIZE(1..128)
+
+
+ postalCode - DirectoryString(SIZE(1..40)
+
+
+ dnQualifier - DirectoryString(SIZE(1..64)
+
+
+ RFC 3039 Pseudonym - DirectoryString(SIZE(1..64)
+
+
+ RFC 3039 DateOfBirth - GeneralizedTime - YYYYMMDD000000Z
+
+
+ RFC 3039 PlaceOfBirth - DirectoryString(SIZE(1..128)
+
+
+ RFC 3039 DateOfBirth - PrintableString (SIZE(1)) -- "M", "F", "m" or "f"
+
+
+ RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166
+ codes only
+
+
+ RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166
+ codes only
+
+
+ ISIS-MTT NameAtBirth - DirectoryString(SIZE(1..64)
+
+
+ RFC 3039 PostalAddress - SEQUENCE SIZE (1..6) OF
+ DirectoryString(SIZE(1..30))
+
+
+ RFC 2256 dmdName
+
+
+ id-at-telephoneNumber
+
+
+ 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.
+
+
+ more from PKCS#9
+
+
+ email address in Verisign certificates
+
+
+ LDAP User id.
+
+
+ default look up table translating OID values into their common symbols following
+ the convention in RFC 2253 with a few extras
+
+
+ look up table translating OID values into their common symbols following the convention in RFC 2253
+
+
+ look up table translating OID values into their common symbols following the convention in RFC 1779
+
+
+
+ look up table translating common symbols into their OIDS.
+
+
+ Return a X509Name based on the passed in tagged object.
+
+ @param obj tag object holding name.
+ @param explicitly true if explicitly tagged false otherwise.
+ @return the X509Name
+
+
+ Constructor from Asn1Sequence
+
+ the principal will be a list of constructed sets, each containing an (OID, string) pair.
+
+
+ Constructor from a table of attributes with ordering.
+
+ it's is assumed the table contains OID/string pairs, and the contents
+ of the table are copied into an internal table as part of the
+ construction process. The ordering ArrayList should contain the OIDs
+ in the order they are meant to be encoded or printed in ToString.
+
+
+ Constructor from a table of attributes with ordering.
+
+ it's is assumed the table contains OID/string pairs, and the contents
+ of the table are copied into an internal table as part of the
+ construction process. The ordering ArrayList should contain the OIDs
+ in the order they are meant to be encoded or printed in ToString.
+
+ The passed in converter will be used to convert the strings into their
+ ASN.1 counterparts.
+
+
+ Takes two vectors one of the oids and the other of the values.
+
+
+ Takes two vectors one of the oids and the other of the values.
+
+ The passed in converter will be used to convert the strings into their
+ ASN.1 counterparts.
+
+
+ Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ some such, converting it into an ordered set of name attributes.
+
+
+ Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ some such, converting it into an ordered set of name attributes with each
+ string value being converted to its associated ASN.1 type using the passed
+ in converter.
+
+
+ Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ some such, converting it into an ordered set of name attributes. If reverse
+ is true, create the encoded version of the sequence starting from the
+ last element in the string.
+
+
+ Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ some such, converting it into an ordered set of name attributes with each
+ string value being converted to its associated ASN.1 type using the passed
+ in converter. If reverse is true the ASN.1 sequence representing the DN will
+ be built by starting at the end of the string, rather than the start.
+
+
+ Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ some such, converting it into an ordered set of name attributes. lookUp
+ should provide a table of lookups, indexed by lowercase only strings and
+ yielding a DerObjectIdentifier, other than that OID. and numeric oids
+ will be processed automatically.
+
+ If reverse is true, create the encoded version of the sequence
+ starting from the last element in the string.
+ @param reverse true if we should start scanning from the end (RFC 2553).
+ @param lookUp table of names and their oids.
+ @param dirName the X.500 string to be parsed.
+
+
+ Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ some such, converting it into an ordered set of name attributes. lookUp
+ should provide a table of lookups, indexed by lowercase only strings and
+ yielding a DerObjectIdentifier, other than that OID. and numeric oids
+ will be processed automatically. The passed in converter is used to convert the
+ string values to the right of each equals sign to their ASN.1 counterparts.
+
+ @param reverse true if we should start scanning from the end, false otherwise.
+ @param lookUp table of names and oids.
+ @param dirName the string dirName
+ @param converter the converter to convert string values into their ASN.1 equivalents
+
+
+ return an IList of the oids in the name, in the order they were found.
+
+
+ return an IList of the values found in the name, in the order they
+ were found.
+
+
+ return an IList of the values found in the name, in the order they
+ were found, with the DN label corresponding to passed in oid.
+
+
+ The X509Name object to test equivalency against.
+ If true, the order of elements must be the same,
+ as well as the values associated with each element.
+
+
+ test for equivalence - note: case is ignored.
+
+
+ convert the structure to a string - if reverse is true the
+ oids and values are listed out starting with the last element
+ in the sequence (ala RFC 2253), otherwise the string will begin
+ with the first element of the structure. If no string definition
+ for the oid is found in oidSymbols the string value of the oid is
+ added. Two standard symbol tables are provided DefaultSymbols, and
+ RFC2253Symbols as part of this class.
+
+ @param reverse if true start at the end of the sequence and work back.
+ @param oidSymbols look up table strings for oids.
+
+
+ determines whether or not strings should be processed and printed
+ from back to front.
+
+
+ class for breaking up an X500 Name into it's component tokens, ala
+ java.util.StringTokenizer. We need this class as some of the
+ lightweight Java environment don't support classes like
+ StringTokenizer.
+
+
+ ASN.1 def for Diffie-Hellman key exchange KeySpecificInfo structure. See
+ RFC 2631, or X9.42, for further details.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ ANS.1 def for Diffie-Hellman key exchange OtherInfo structure. See
+ RFC 2631, or X9.42, for further details.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ table of the current named curves defined in X.962 EC-DSA.
+
+
+ return the X9ECParameters object for the named curve represented by
+ the passed in object identifier. Null if the curve isn't present.
+
+ @param oid an object identifier representing a named curve, if present.
+
+
+ return the object identifier signified by the passed in name. Null
+ if there is no object identifier associated with name.
+
+ @return the object identifier associated with name, if present.
+
+
+ return the named curve name represented by the given object identifier.
+
+
+ returns an enumeration containing the name strings for curves
+ contained in this structure.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ ASN.1 def for Elliptic-Curve Curve structure. See
+ X9.62, for further details.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Curve ::= Sequence {
+ a FieldElement,
+ b FieldElement,
+ seed BIT STRING OPTIONAL
+ }
+
+
+
+ ASN.1 def for Elliptic-Curve ECParameters structure. See
+ X9.62, for further details.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ class for describing an ECPoint as a Der object.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ ECPoint ::= OCTET STRING
+
+
+ Octet string produced using ECPoint.GetEncoded().
+
+
+ Class for processing an ECFieldElement as a DER object.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ FieldElement ::= OCTET STRING
+
+
+
+
if q is an odd prime then the field element is
+ processed as an Integer and converted to an octet string
+ according to x 9.62 4.3.1.
+
if q is 2m then the bit string
+ contained in the field element is converted into an octet
+ string with the same ordering padded at the front if necessary.
+
+
+
+
+
+ ASN.1 def for Elliptic-Curve Field ID structure. See
+ X9.62, for further details.
+
+
+ Constructor for elliptic curves over prime fields
+ F2.
+ @param primeP The prime p defining the prime field.
+
+
+ Constructor for elliptic curves over binary fields
+ F2m.
+ @param m The exponent m of
+ F2m.
+ @param k1 The integer k1 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param k2 The integer k2 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param k3 The integer k3 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z)..
+
+
+ Produce a Der encoding of the following structure.
+
+
+
+ X9.42
+
+
+ id-dsa-with-sha1 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
+ us(840) x9-57 (10040) x9cm(4) 3 }
+
+
+ X9.63
+
+
+ reader for Base64 armored objects - read the headers and then start returning
+ bytes when the data is reached. An IOException is thrown if the CRC check
+ fails.
+
+
+ decode the base 64 encoded input data.
+
+ @return the offset the data starts in out.
+
+
+ Create a stream for reading a PGP armoured message, parsing up to a header
+ and then reading the data that follows.
+
+ @param input
+
+
+ Create an armoured input stream which will assume the data starts
+ straight away, or parse for headers first depending on the value of
+ hasHeaders.
+
+ @param input
+ @param hasHeaders true if headers are to be looked for, false otherwise.
+
+
+ @return true if we are inside the clear text section of a PGP
+ signed message.
+
+
+ @return true if the stream is actually at end of file.
+
+
+ Return the armor header line (if there is one)
+ @return the armor header line, null if none present.
+
+
+ Return the armor headers (the lines after the armor header line),
+ @return an array of armor headers, null if there aren't any.
+
+
+ Basic output stream.
+
+
+ encode the input data producing a base 64 encoded byte array.
+
+
+ Set an additional header entry.
+
+ @param name the name of the header entry.
+ @param v the value of the header entry.
+
+
+ Reset the headers to only contain a Version string.
+
+
+ Start a clear text signed message.
+ @param hashAlgorithm
+
+
+ Note: Dispose does nor Dispose the underlying stream. So it is possible to write
+ multiple objects using armoring to a single stream.
+
+
+ Basic type for a image attribute packet.
+
+
+ Basic type for a user attribute sub-packet.
+
+
+ return the generic data making up the packet.
+
+
+ Reader for PGP objects.
+
+
+ Returns the next packet tag in the stream.
+
+
+
+ A stream that overlays our input stream, allowing the user to only read a segment of it.
+ NB: dataLength will be negative if the segment length is in the upper range above 2**31.
+
+
+
+ Base class for a PGP object.
+
+
+ Basic output stream.
+
+
+ Create a stream representing a general packet.
+ Output stream to write to.
+
+
+ Create a stream representing an old style partial object.
+ Output stream to write to.
+ The packet tag for the object.
+
+
+ Create a stream representing a general packet.
+ Output stream to write to.
+ Packet tag.
+ Size of chunks making up the packet.
+ If true, the header is written out in old format.
+
+
+ Create a new style partial input stream buffered into chunks.
+ Output stream to write to.
+ Packet tag.
+ Size of chunks making up the packet.
+
+
+ Create a new style partial input stream buffered into chunks.
+ Output stream to write to.
+ Packet tag.
+ Buffer to use for collecting chunks.
+
+
+ Flush the underlying stream.
+
+
+ Finish writing out the current packet without closing the underlying stream.
+
+
+ Generic compressed data object.
+
+
+ Note: you can only read from this once...
+
+
+ The algorithm tag value.
+
+
+ Basic tags for compression algorithms.
+
+
+ Basic type for a PGP packet.
+
+
+ Base class for a DSA public key.
+
+
+ Base interface for a PGP key.
+
+
+
+ The base format for this key - in the case of the symmetric keys it will generally
+ be raw indicating that the key is just a straight byte representation, for an asymmetric
+ key the format will be PGP, indicating the key is a string of MPIs encoded in PGP format.
+
+ "RAW" or "PGP".
+
+
+ The stream to read the packet from.
+
+
+ Return the standard PGP encoding of the key.
+
+
+ The format, as a string, always "PGP".
+
+
+ Base class for a DSA secret key.
+
+
+ @param in
+
+
+ Return the standard PGP encoding of the key.
+
+
+ The format, as a string, always "PGP".
+
+
+ @return x
+
+
+ Base class for an ElGamal public key.
+
+
+ Return the standard PGP encoding of the key.
+
+
+ The format, as a string, always "PGP".
+
+
+ Base class for an ElGamal secret key.
+
+
+ @param in
+
+
+ @param x
+
+
+ Return the standard PGP encoding of the key.
+
+
+ The format, as a string, always "PGP".
+
+
+ Basic packet for an experimental packet.
+
+
+ Basic tags for hash algorithms.
+
+
+ Generic literal data packet.
+
+
+ The format tag value.
+
+
+ The modification time of the file in milli-seconds (since Jan 1, 1970 UTC)
+
+
+ Basic type for a marker packet.
+
+
+ Basic packet for a modification detection code packet.
+
+
+ A multiple precision integer
+
+
+ Generic signature object
+
+
+ The encryption algorithm tag.
+
+
+ The hash algorithm tag.
+
+
+ Basic PGP packet tag types.
+
+
+ Public Key Algorithm tag numbers.
+
+
+ Basic packet for a PGP public key.
+
+
+ Basic packet for a PGP public key.
+
+
+ Construct a version 4 public key packet.
+
+
+ Basic packet for a PGP public subkey
+
+
+ Construct a version 4 public subkey packet.
+
+
+ Base class for an RSA public key.
+
+
+ Construct an RSA public key from the passed in stream.
+
+
+ The modulus.
+ The public exponent.
+
+
+ Return the standard PGP encoding of the key.
+
+
+ The format, as a string, always "PGP".
+
+
+ Base class for an RSA secret (or priate) key.
+
+
+ Return the standard PGP encoding of the key.
+
+
+ The format, as a string, always "PGP".
+
+
+ The string to key specifier class.
+
+
+ The IV for the key generation algorithm.
+
+
+ The hash algorithm.
+
+
+ The iteration count
+
+
+ The protection mode - only if GnuDummyS2K
+
+
+ Basic packet for a PGP secret key.
+
+
+ Basic packet for a PGP secret key.
+
+
+ Generic signature packet.
+
+
+ Generate a version 4 signature packet.
+
+ @param signatureType
+ @param keyAlgorithm
+ @param hashAlgorithm
+ @param hashedData
+ @param unhashedData
+ @param fingerprint
+ @param signature
+
+
+ Generate a version 2/3 signature packet.
+
+ @param signatureType
+ @param keyAlgorithm
+ @param hashAlgorithm
+ @param fingerprint
+ @param signature
+
+
+ return the signature trailer that must be included with the data
+ to reconstruct the signature
+
+ @return byte[]
+
+
+ * return the signature as a set of integers - note this is normalised to be the
+ * ASN.1 encoding of what appears in the signature packet.
+
+
+ Return the byte encoding of the signature section.
+ @return uninterpreted signature bytes.
+
+
+ return the keyId
+ @return the keyId that created the signature.
+
+
+ Return the creation time in milliseconds since 1 Jan., 1970 UTC.
+
+
+ Basic type for a PGP Signature sub-packet.
+
+
+ Return the generic data making up the packet.
+
+
+ reader for signature sub-packets
+
+
+ Basic PGP signature sub-packet tag types.
+
+
+ Packet embedded signature
+
+
+ packet giving signature creation time.
+
+
+ packet giving signature creation time.
+
+
+ packet giving time after creation at which the key expires.
+
+
+ Return the number of seconds after creation time a key is valid for.
+
+ @return second count for key validity.
+
+
+ Packet holding the key flag values.
+
+
+
+ Return the flag values contained in the first 4 octets (note: at the moment
+ the standard only uses the first one).
+
+
+
+ Class provided a NotationData object according to
+ RFC2440, Chapter 5.2.3.15. Notation Data
+
+
+ packet giving signature creation time.
+
+
+ packet giving whether or not the signature is signed using the primary user ID for the key.
+
+
+ packet giving whether or not is revocable.
+
+
+
+ Represents revocation key OpenPGP signature sub packet.
+
+
+
+
+ Represents revocation reason OpenPGP signature sub packet.
+
+
+
+ packet giving signature creation time.
+
+
+ packet giving signature expiration time.
+
+
+ return time in seconds before signature expires after creation time.
+
+
+ packet giving the User ID of the signer.
+
+
+ packet giving trust.
+
+
+ Basic type for a symmetric key encrypted packet.
+
+
+ Basic tags for symmetric key algorithms
+
+
+ Basic type for a symmetric encrypted session key packet
+
+
+ @return byte[]
+
+
+ @return int
+
+
+ @return S2k
+
+
+ @return int
+
+
+ Basic type for a trust packet.
+
+
+ Basic type for a user attribute packet.
+
+
+ reader for user attribute sub-packets
+
+
+ Basic PGP user attribute sub-packet tag types.
+
+
+ Basic type for a user ID packet.
+
+
+
+ The 'Signature' parameter is only available when generating unsigned attributes.
+
+
+
+ containing class for an CMS Authenticated Data object
+
+
+ return a store of the intended recipients for this message
+
+
+ return a table of the digested attributes indexed by
+ the OID of the attribute.
+
+
+ return a table of the undigested attributes indexed by
+ the OID of the attribute.
+
+
+ return the ASN.1 encoded representation of this object.
+
+
+ return the object identifier for the content MAC algorithm.
+
+
+ return the ContentInfo
+
+
+ General class for generating a CMS authenticated-data message.
+
+ A simple example of usage.
+
+
+ CMSAuthenticatedDataGenerator fact = new CMSAuthenticatedDataGenerator();
+
+ fact.addKeyTransRecipient(cert);
+
+ CMSAuthenticatedData data = fact.generate(content, algorithm, "BC");
+
+
+
+ General class for generating a CMS enveloped-data message.
+
+ A simple example of usage.
+
+
+ CMSEnvelopedDataGenerator fact = new CMSEnvelopedDataGenerator();
+
+ fact.addKeyTransRecipient(cert);
+
+ CMSEnvelopedData data = fact.generate(content, algorithm, "BC");
+
+
+
+ Constructor allowing specific source of randomness
+ Instance of SecureRandom to use.
+
+
+ add a recipient.
+
+ @param cert recipient's public key certificate
+ @exception ArgumentException if there is a problem with the certificate
+
+
+ add a recipient
+
+ @param key the public key used by the recipient
+ @param subKeyId the identifier for the recipient's public key
+ @exception ArgumentException if there is a problem with the key
+
+
+ add a KEK recipient.
+ @param key the secret key to use for wrapping
+ @param keyIdentifier the byte string that identifies the key
+
+
+ add a KEK recipient.
+ @param key the secret key to use for wrapping
+ @param keyIdentifier the byte string that identifies the key
+
+
+ Add a key agreement based recipient.
+
+ @param agreementAlgorithm key agreement algorithm to use.
+ @param senderPrivateKey private key to initialise sender side of agreement with.
+ @param senderPublicKey sender public key to include with message.
+ @param recipientCert recipient's public key certificate.
+ @param cekWrapAlgorithm OID for key wrapping algorithm to use.
+ @exception SecurityUtilityException if the algorithm requested cannot be found
+ @exception InvalidKeyException if the keys are inappropriate for the algorithm specified
+
+
+ Add multiple key agreement based recipients (sharing a single KeyAgreeRecipientInfo structure).
+
+ @param agreementAlgorithm key agreement algorithm to use.
+ @param senderPrivateKey private key to initialise sender side of agreement with.
+ @param senderPublicKey sender public key to include with message.
+ @param recipientCerts recipients' public key certificates.
+ @param cekWrapAlgorithm OID for key wrapping algorithm to use.
+ @exception SecurityUtilityException if the algorithm requested cannot be found
+ @exception InvalidKeyException if the keys are inappropriate for the algorithm specified
+
+
+ base constructor
+
+
+ constructor allowing specific source of randomness
+
+ @param rand instance of SecureRandom to use
+
+
+ base constructor
+
+
+ constructor allowing specific source of randomness
+ @param rand instance of SecureRandom to use
+
+
+ generate an enveloped object that contains an CMS Enveloped Data
+ object using the given provider and the passed in key generator.
+
+
+ generate an authenticated object that contains an CMS Authenticated Data object
+
+
+ Parsing class for an CMS Authenticated Data object from an input stream.
+
+ Note: that because we are in a streaming mode only one recipient can be tried and it is important
+ that the methods on the parser are called in the appropriate order.
+
+
+ Example of use - assuming the first recipient matches the private key we have.
+
+ CMSAuthenticatedDataParser ad = new CMSAuthenticatedDataParser(inputStream);
+
+ RecipientInformationStore recipients = ad.getRecipientInfos();
+
+ Collection c = recipients.getRecipients();
+ Iterator it = c.iterator();
+
+ if (it.hasNext())
+ {
+ RecipientInformation recipient = (RecipientInformation)it.next();
+
+ CMSTypedStream recData = recipient.getContentStream(privateKey, "BC");
+
+ processDataStream(recData.getContentStream());
+
+ if (!Arrays.equals(ad.getMac(), recipient.getMac())
+ {
+ System.err.println("Data corrupted!!!!");
+ }
+ }
+
+ Note: this class does not introduce buffering - if you are processing large files you should create
+ the parser with:
+
+ CMSAuthenticatedDataParser ep = new CMSAuthenticatedDataParser(new BufferedInputStream(inputStream, bufSize));
+
+ where bufSize is a suitably large buffer size.
+
+
+
+ Close the underlying data stream.
+ @throws IOException if the close fails.
+
+
+ return a store of the intended recipients for this message
+
+
+ return a table of the unauthenticated attributes indexed by
+ the OID of the attribute.
+ @exception java.io.IOException
+
+
+ return a table of the unauthenticated attributes indexed by
+ the OID of the attribute.
+ @exception java.io.IOException
+
+
+ return the object identifier for the mac algorithm.
+
+
+ return the ASN.1 encoded encryption algorithm parameters, or null if
+ there aren't any.
+
+
+ General class for generating a CMS authenticated-data message stream.
+
+
+
+
+ base constructor
+
+
+ constructor allowing specific source of randomness
+ @param rand instance of SecureRandom to use
+
+
+ Set the underlying string size for encapsulated data
+
+ @param bufferSize length of octet strings to buffer the data.
+
+
+ Use a BER Set to store the recipient information
+
+
+ generate an enveloped object that contains an CMS Enveloped Data
+ object using the given provider and the passed in key generator.
+ @throws java.io.IOException
+
+
+ generate an enveloped object that contains an CMS Enveloped Data object
+
+
+ generate an enveloped object that contains an CMS Enveloped Data object
+
+
+ containing class for an CMS AuthEnveloped Data object
+
+
+ containing class for an CMS Compressed Data object
+
+
+ Return the uncompressed content.
+
+ @return the uncompressed content
+ @throws CmsException if there is an exception uncompressing the data.
+
+
+ Return the uncompressed content, throwing an exception if the data size
+ is greater than the passed in limit. If the content is exceeded getCause()
+ on the CMSException will contain a StreamOverflowException
+
+ @param limit maximum number of bytes to read
+ @return the content read
+ @throws CMSException if there is an exception uncompressing the data.
+
+
+ return the ASN.1 encoded representation of this object.
+
+
+ return the ContentInfo
+
+
+ * General class for generating a compressed CMS message.
+ *
+ * A simple example of usage.
+ *
+ *
+ * CMSCompressedDataGenerator fact = new CMSCompressedDataGenerator();
+ * CMSCompressedData data = fact.Generate(content, algorithm);
+ *
+ *
+
+
+ Generate an object that contains an CMS Compressed Data
+
+
+ Class for reading a CMS Compressed Data stream.
+
+ CMSCompressedDataParser cp = new CMSCompressedDataParser(inputStream);
+
+ process(cp.GetContent().GetContentStream());
+
+ Note: this class does not introduce buffering - if you are processing large files you should create
+ the parser with:
+
+ CMSCompressedDataParser ep = new CMSCompressedDataParser(new BufferedInputStream(inputStream, bufSize));
+
+ where bufSize is a suitably large buffer size.
+
+
+ General class for generating a compressed CMS message stream.
+
+ A simple example of usage.
+
+
+ CMSCompressedDataStreamGenerator gen = new CMSCompressedDataStreamGenerator();
+
+ Stream cOut = gen.Open(outputStream, CMSCompressedDataStreamGenerator.ZLIB);
+
+ cOut.Write(data);
+
+ cOut.Close();
+
+
+
+ base constructor
+
+
+ Set the underlying string size for encapsulated data
+
+ @param bufferSize length of octet strings to buffer the data.
+
+
+ containing class for an CMS Enveloped Data object
+
+
+ return a store of the intended recipients for this message
+
+
+ return a table of the unprotected attributes indexed by
+ the OID of the attribute.
+
+
+ return the ASN.1 encoded representation of this object.
+
+
+ return the object identifier for the content encryption algorithm.
+
+
+ return the ContentInfo
+
+
+
+ General class for generating a CMS enveloped-data message.
+
+ A simple example of usage.
+
+
+ CmsEnvelopedDataGenerator fact = new CmsEnvelopedDataGenerator();
+
+ fact.AddKeyTransRecipient(cert);
+
+ CmsEnvelopedData data = fact.Generate(content, algorithm);
+
+
+
+
+ Constructor allowing specific source of randomness
+ Instance of SecureRandom to use.
+
+
+
+ Generate an enveloped object that contains a CMS Enveloped Data
+ object using the passed in key generator.
+
+
+
+ Generate an enveloped object that contains an CMS Enveloped Data object.
+
+
+ Generate an enveloped object that contains an CMS Enveloped Data object.
+
+
+ Parsing class for an CMS Enveloped Data object from an input stream.
+
+ Note: that because we are in a streaming mode only one recipient can be tried and it is important
+ that the methods on the parser are called in the appropriate order.
+
+
+ Example of use - assuming the first recipient matches the private key we have.
+
+ CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(inputStream);
+
+ RecipientInformationStore recipients = ep.GetRecipientInfos();
+
+ Collection c = recipients.getRecipients();
+ Iterator it = c.iterator();
+
+ if (it.hasNext())
+ {
+ RecipientInformation recipient = (RecipientInformation)it.next();
+
+ CMSTypedStream recData = recipient.getContentStream(privateKey);
+
+ processDataStream(recData.getContentStream());
+ }
+
+ Note: this class does not introduce buffering - if you are processing large files you should create
+ the parser with:
+
+ CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(new BufferedInputStream(inputStream, bufSize));
+
+ where bufSize is a suitably large buffer size.
+
+
+
+ return a store of the intended recipients for this message
+
+
+ return a table of the unprotected attributes indexed by
+ the OID of the attribute.
+ @throws IOException
+
+
+ return the object identifier for the content encryption algorithm.
+
+
+ return the ASN.1 encoded encryption algorithm parameters, or null if
+ there aren't any.
+
+
+ General class for generating a CMS enveloped-data message stream.
+
+
+
+
+ Constructor allowing specific source of randomness
+ Instance of SecureRandom to use.
+
+
+ Set the underlying string size for encapsulated data.
+ Length of octet strings to buffer the data.
+
+
+ Use a BER Set to store the recipient information.
+
+
+
+ Generate an enveloped object that contains an CMS Enveloped Data
+ object using the passed in key generator.
+
+
+
+ generate an enveloped object that contains an CMS Enveloped Data object
+ @throws IOException
+
+
+ generate an enveloped object that contains an CMS Enveloped Data object
+ @throws IOException
+
+
+ all parameter classes implement this.
+
+
+
+ Generic routine to copy out the data we want processed.
+
+
+ This routine may be called multiple times.
+
+
+
+ a holding class for a byte array of data to be processed.
+
+
+ A clone of the byte array
+
+
+ general class for handling a pkcs7-signature message.
+
+ A simple example of usage - note, in the example below the validity of
+ the certificate isn't verified, just the fact that one of the certs
+ matches the given signer...
+
+
+
+
+ Content with detached signature, digests precomputed
+
+ @param hashes a map of precomputed digests for content indexed by name of hash.
+ @param sigBlock the signature object.
+
+
+ base constructor - content with detached signature.
+
+ @param signedContent the content that was signed.
+ @param sigData the signature object.
+
+
+ base constructor - with encapsulated content
+
+
+ return the collection of signers that are associated with the
+ signatures for the message.
+
+
+ return a X509Store containing the attribute certificates, if any, contained
+ in this message.
+
+ @param type type of store to create
+ @return a store of attribute certificates
+ @exception NoSuchStoreException if the store type isn't available.
+ @exception CmsException if a general exception prevents creation of the X509Store
+
+
+ return a X509Store containing the public key certificates, if any, contained
+ in this message.
+
+ @param type type of store to create
+ @return a store of public key certificates
+ @exception NoSuchStoreException if the store type isn't available.
+ @exception CmsException if a general exception prevents creation of the X509Store
+
+
+ return a X509Store containing CRLs, if any, contained
+ in this message.
+
+ @param type type of store to create
+ @return a store of CRLs
+ @exception NoSuchStoreException if the store type isn't available.
+ @exception CmsException if a general exception prevents creation of the X509Store
+
+
+ return the ASN.1 encoded representation of this object.
+
+
+ Replace the signerinformation store associated with this
+ CmsSignedData object with the new one passed in. You would
+ probably only want to do this if you wanted to change the unsigned
+ attributes associated with a signer, or perhaps delete one.
+
+ @param signedData the signed data object to be used as a base.
+ @param signerInformationStore the new signer information store to use.
+ @return a new signed data object.
+
+
+ Replace the certificate and CRL information associated with this
+ CmsSignedData object with the new one passed in.
+
+ @param signedData the signed data object to be used as a base.
+ @param x509Certs the new certificates to be used.
+ @param x509Crls the new CRLs to be used.
+ @return a new signed data object.
+ @exception CmsException if there is an error processing the stores
+
+
+ Return the version number for this object.
+
+
+
+ Return the DerObjectIdentifier associated with the encapsulated
+ content info structure carried in the signed data.
+
+
+
+ return the ContentInfo
+
+
+ * general class for generating a pkcs7-signature message.
+ *
+ *
+
+
+ Default type for the signed data.
+
+
+ Constructor allowing specific source of randomness
+ Instance of SecureRandom to use.
+
+
+ Add the attribute certificates contained in the passed in store to the
+ generator.
+
+ @param store a store of Version 2 attribute certificates
+ @throws CmsException if an error occurse processing the store.
+
+
+ Add a store of precalculated signers to the generator.
+
+ @param signerStore store of signers
+
+
+ Return a map of oids and byte arrays representing the digests calculated on the content during
+ the last generate.
+
+ @return a map of oids (as String objects) and byte[] representing digests.
+
+
+ Constructor allowing specific source of randomness
+ Instance of SecureRandom to use.
+
+
+ * add a signer - no attributes other than the default ones will be
+ * provided here.
+ *
+ * @param key signing key to use
+ * @param cert certificate containing corresponding public key
+ * @param digestOID digest algorithm OID
+
+
+ add a signer, specifying the digest encryption algorithm to use - no attributes other than the default ones will be
+ provided here.
+
+ @param key signing key to use
+ @param cert certificate containing corresponding public key
+ @param encryptionOID digest encryption algorithm OID
+ @param digestOID digest algorithm OID
+
+
+ add a signer - no attributes other than the default ones will be
+ provided here.
+
+
+ add a signer, specifying the digest encryption algorithm to use - no attributes other than the default ones will be
+ provided here.
+
+
+ * add a signer with extra signed/unsigned attributes.
+ *
+ * @param key signing key to use
+ * @param cert certificate containing corresponding public key
+ * @param digestOID digest algorithm OID
+ * @param signedAttr table of attributes to be included in signature
+ * @param unsignedAttr table of attributes to be included as unsigned
+
+
+ add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes.
+
+ @param key signing key to use
+ @param cert certificate containing corresponding public key
+ @param encryptionOID digest encryption algorithm OID
+ @param digestOID digest algorithm OID
+ @param signedAttr table of attributes to be included in signature
+ @param unsignedAttr table of attributes to be included as unsigned
+
+
+ * add a signer with extra signed/unsigned attributes.
+ *
+ * @param key signing key to use
+ * @param subjectKeyID subjectKeyID of corresponding public key
+ * @param digestOID digest algorithm OID
+ * @param signedAttr table of attributes to be included in signature
+ * @param unsignedAttr table of attributes to be included as unsigned
+
+
+ add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes.
+
+ @param key signing key to use
+ @param subjectKeyID subjectKeyID of corresponding public key
+ @param encryptionOID digest encryption algorithm OID
+ @param digestOID digest algorithm OID
+ @param signedAttr table of attributes to be included in signature
+ @param unsignedAttr table of attributes to be included as unsigned
+
+
+ add a signer with extra signed/unsigned attributes based on generators.
+
+
+ add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes based on generators.
+
+
+ add a signer with extra signed/unsigned attributes based on generators.
+
+
+ add a signer, including digest encryption algorithm, with extra signed/unsigned attributes based on generators.
+
+
+ generate a signed object that for a CMS Signed Data object
+
+
+ generate a signed object that for a CMS Signed Data
+ object - if encapsulate is true a copy
+ of the message will be included in the signature. The content type
+ is set according to the OID represented by the string signedContentType.
+
+
+ generate a signed object that for a CMS Signed Data
+ object - if encapsulate is true a copy
+ of the message will be included in the signature with the
+ default content type "data".
+
+
+ generate a set of one or more SignerInformation objects representing counter signatures on
+ the passed in SignerInformation object.
+
+ @param signer the signer to be countersigned
+ @param sigProvider the provider to be used for counter signing.
+ @return a store containing the signers.
+
+
+ Parsing class for an CMS Signed Data object from an input stream.
+
+ Note: that because we are in a streaming mode only one signer can be tried and it is important
+ that the methods on the parser are called in the appropriate order.
+
+
+ A simple example of usage for an encapsulated signature.
+
+
+ Two notes: first, in the example below the validity of
+ the certificate isn't verified, just the fact that one of the certs
+ matches the given signer, and, second, because we are in a streaming
+ mode the order of the operations is important.
+
+ Note also: this class does not introduce buffering - if you are processing large files you should create
+ the parser with:
+
+ CmsSignedDataParser ep = new CmsSignedDataParser(new BufferedInputStream(encapSigData, bufSize));
+
+ where bufSize is a suitably large buffer size.
+
+
+ base constructor - with encapsulated content
+
+
+ base constructor
+
+ @param signedContent the content that was signed.
+ @param sigData the signature object.
+
+
+ return the collection of signers that are associated with the
+ signatures for the message.
+ @throws CmsException
+
+
+ return a X509Store containing the attribute certificates, if any, contained
+ in this message.
+
+ @param type type of store to create
+ @return a store of attribute certificates
+ @exception org.bouncycastle.x509.NoSuchStoreException if the store type isn't available.
+ @exception CmsException if a general exception prevents creation of the X509Store
+
+
+ return a X509Store containing the public key certificates, if any, contained
+ in this message.
+
+ @param type type of store to create
+ @return a store of public key certificates
+ @exception NoSuchStoreException if the store type isn't available.
+ @exception CmsException if a general exception prevents creation of the X509Store
+
+
+ return a X509Store containing CRLs, if any, contained
+ in this message.
+
+ @param type type of store to create
+ @return a store of CRLs
+ @exception NoSuchStoreException if the store type isn't available.
+ @exception CmsException if a general exception prevents creation of the X509Store
+
+
+ Replace the signerinformation store associated with the passed
+ in message contained in the stream original with the new one passed in.
+ You would probably only want to do this if you wanted to change the unsigned
+ attributes associated with a signer, or perhaps delete one.
+
+ The output stream is returned unclosed.
+
+ @param original the signed data stream to be used as a base.
+ @param signerInformationStore the new signer information store to use.
+ @param out the stream to Write the new signed data object to.
+ @return out.
+
+
+ Replace the certificate and CRL information associated with this
+ CMSSignedData object with the new one passed in.
+
+ The output stream is returned unclosed.
+
+ @param original the signed data stream to be used as a base.
+ @param certsAndCrls the new certificates and CRLs to be used.
+ @param out the stream to Write the new signed data object to.
+ @return out.
+ @exception CmsException if there is an error processing the CertStore
+
+
+ Return the version number for the SignedData object
+
+ @return the version number
+
+
+
+ Return the DerObjectIdentifier associated with the encapsulated
+ content info structure carried in the signed data.
+
+
+
+ General class for generating a pkcs7-signature message stream.
+
+
+
+ Constructor allowing specific source of randomness
+ Instance of SecureRandom to use.
+
+
+ Set the underlying string size for encapsulated data
+
+ @param bufferSize length of octet strings to buffer the data.
+
+
+ add a signer - no attributes other than the default ones will be
+ provided here.
+ @throws NoSuchAlgorithmException
+ @throws InvalidKeyException
+
+
+ add a signer, specifying the digest encryption algorithm - no attributes other than the default ones will be
+ provided here.
+ @throws NoSuchProviderException
+ @throws NoSuchAlgorithmException
+ @throws InvalidKeyException
+
+
+ add a signer with extra signed/unsigned attributes.
+ @throws NoSuchAlgorithmException
+ @throws InvalidKeyException
+
+
+ add a signer with extra signed/unsigned attributes - specifying digest
+ encryption algorithm.
+ @throws NoSuchProviderException
+ @throws NoSuchAlgorithmException
+ @throws InvalidKeyException
+
+
+ add a signer - no attributes other than the default ones will be
+ provided here.
+ @throws NoSuchAlgorithmException
+ @throws InvalidKeyException
+
+
+ add a signer - no attributes other than the default ones will be
+ provided here.
+ @throws NoSuchProviderException
+ @throws NoSuchAlgorithmException
+ @throws InvalidKeyException
+
+
+ add a signer with extra signed/unsigned attributes.
+ @throws NoSuchAlgorithmException
+ @throws InvalidKeyException
+
+
+ generate a signed object that for a CMS Signed Data object
+
+
+ generate a signed object that for a CMS Signed Data
+ object - if encapsulate is true a copy
+ of the message will be included in the signature with the
+ default content type "data".
+
+
+ generate a signed object that for a CMS Signed Data
+ object using the given provider - if encapsulate is true a copy
+ of the message will be included in the signature with the
+ default content type "data". If dataOutputStream is non null the data
+ being signed will be written to the stream as it is processed.
+ @param out stream the CMS object is to be written to.
+ @param encapsulate true if data should be encapsulated.
+ @param dataOutputStream output stream to copy the data being signed to.
+
+
+ generate a signed object that for a CMS Signed Data
+ object - if encapsulate is true a copy
+ of the message will be included in the signature. The content type
+ is set according to the OID represented by the string signedContentType.
+
+
+ generate a signed object that for a CMS Signed Data
+ object using the given provider - if encapsulate is true a copy
+ of the message will be included in the signature. The content type
+ is set according to the OID represented by the string signedContentType.
+ @param out stream the CMS object is to be written to.
+ @param signedContentType OID for data to be signed.
+ @param encapsulate true if data should be encapsulated.
+ @param dataOutputStream output stream to copy the data being signed to.
+
+
+ Return the digest algorithm using one of the standard JCA string
+ representations rather than the algorithm identifier (if possible).
+
+
+ Return the digest encryption algorithm using one of the standard
+ JCA string representations rather than the algorithm identifier (if
+ possible).
+
+
+ Default authenticated attributes generator.
+
+
+ Initialise to use all defaults
+
+
+ Initialise with some extra attributes or overrides.
+
+ @param attributeTable initial attribute table to use.
+
+
+ Create a standard attribute table from the passed in parameters - this will
+ normally include contentType and messageDigest. If the constructor
+ using an AttributeTable was used, entries in it for contentType and
+ messageDigest will override the generated ones.
+
+ @param parameters source parameters for table generation.
+
+ @return a filled in IDictionary of attributes.
+
+
+ @param parameters source parameters
+ @return the populated attribute table
+
+
+ Default signed attributes generator.
+
+
+ Initialise to use all defaults
+
+
+ Initialise with some extra attributes or overrides.
+
+ @param attributeTable initial attribute table to use.
+
+
+ Create a standard attribute table from the passed in parameters - this will
+ normally include contentType, signingTime, and messageDigest. If the constructor
+ using an AttributeTable was used, entries in it for contentType, signingTime, and
+ messageDigest will override the generated ones.
+
+ @param parameters source parameters for table generation.
+
+ @return a filled in Hashtable of attributes.
+
+
+ @param parameters source parameters
+ @return the populated attribute table
+
+
+
+ Generate a RecipientInfo object for the given key.
+
+
+ A
+
+
+ A
+
+
+ A
+
+
+
+
+ the RecipientInfo class for a recipient who has been sent a message
+ encrypted using a secret key known to the other side.
+
+
+ Return the MAC calculated for the content stream. Note: this call is only meaningful once all
+ the content has been read.
+
+ @return byte array containing the mac.
+
+
+ * return the object identifier for the key encryption algorithm.
+ *
+ * @return OID for key encryption algorithm.
+
+
+ * return the ASN.1 encoded key encryption algorithm parameters, or null if
+ * there aren't any.
+ *
+ * @return ASN.1 encoding of key encryption algorithm parameters.
+
+
+ decrypt the content and return an input stream.
+
+
+ the RecipientInfo class for a recipient who has been sent a message
+ encrypted using key agreement.
+
+
+ decrypt the content and return an input stream.
+
+
+ the KeyTransRecipientInformation class for a recipient who has been sent a secret
+ key encrypted using their public key that needs to be used to
+ extract the message.
+
+
+ decrypt the content and return it as a byte array.
+
+
+ a basic index for an originator.
+
+
+
+ An ISet of DerObjectIdentifier objects.
+
+
+
+ the RecipientInfo class for a recipient who has been sent a message
+ encrypted using a password.
+
+
+ decrypt the content and return an input stream.
+
+
+ return the object identifier for the key derivation algorithm, or null
+ if there is none present.
+
+ @return OID for key derivation algorithm, if present.
+
+
+
+ PKCS5 scheme-2 - password converted to bytes assuming ASCII.
+
+
+
+ PKCS5 scheme-2 - password converted to bytes using UTF-8.
+
+
+ Return the first RecipientInformation object that matches the
+ passed in selector. Null if there are no matches.
+
+ @param selector to identify a recipient
+ @return a single RecipientInformation object. Null if none matches.
+
+
+ Return all recipients in the collection
+
+ @return a collection of recipients.
+
+
+ Return possible empty collection with recipients matching the passed in RecipientID
+
+ @param selector a recipient id to select against.
+ @return a collection of RecipientInformation objects.
+
+
+ Return the number of recipients in the collection.
+
+ @return number of recipients identified.
+
+
+ a basic index for a signer.
+
+
+ an expanded SignerInfo block from a CMS Signed message
+
+
+ return the content digest that was calculated during verification.
+
+
+ return the encoded signature
+
+
+ Return a SignerInformationStore containing the counter signatures attached to this
+ signer. If no counter signatures are present an empty store is returned.
+
+
+ return the DER encoding of the signed attributes.
+ @throws IOException if an encoding error occurs.
+
+
+ verify that the given public key successfully handles and confirms the
+ signature associated with this signer.
+
+
+ verify that the given certificate successfully handles and confirms
+ the signature associated with this signer and, if a signingTime
+ attribute is available, that the certificate was valid at the time the
+ signature was generated.
+
+
+ Return the base ASN.1 CMS structure that this object contains.
+
+ @return an object containing a CMS SignerInfo structure.
+
+
+ Return a signer information object with the passed in unsigned
+ attributes replacing the ones that are current associated with
+ the object passed in.
+
+ @param signerInformation the signerInfo to be used as the basis.
+ @param unsignedAttributes the unsigned attributes to add.
+ @return a copy of the original SignerInformationObject with the changed attributes.
+
+
+ Return a signer information object with passed in SignerInformationStore representing counter
+ signatures attached as an unsigned attribute.
+
+ @param signerInformation the signerInfo to be used as the basis.
+ @param counterSigners signer info objects carrying counter signature.
+ @return a copy of the original SignerInformationObject with the changed attributes.
+
+
+ return the version number for this objects underlying SignerInfo structure.
+
+
+ return the object identifier for the signature.
+
+
+ return the signature parameters, or null if there aren't any.
+
+
+ return the object identifier for the signature.
+
+
+ return the signature/encryption algorithm parameters, or null if
+ there aren't any.
+
+
+ return a table of the signed attributes - indexed by
+ the OID of the attribute.
+
+
+ return a table of the unsigned attributes indexed by
+ the OID of the attribute.
+
+
+ Return the first SignerInformation object that matches the
+ passed in selector. Null if there are no matches.
+
+ @param selector to identify a signer
+ @return a single SignerInformation object. Null if none matches.
+
+
+ An ICollection of all signers in the collection
+
+
+ Return possible empty collection with signers matching the passed in SignerID
+
+ @param selector a signer id to select against.
+ @return a collection of SignerInformation objects.
+
+
+ The number of signers in the collection.
+
+
+ Basic generator that just returns a preconstructed attribute table
+
+
+ a Diffie-Hellman key exchange engine.
+
+ note: This uses MTI/A0 key agreement in order to make the key agreement
+ secure against passive attacks. If you're doing Diffie-Hellman and both
+ parties have long term public keys you should look at using this. For
+ further information have a look at RFC 2631.
+
+ It's possible to extend this to more than two parties as well, for the moment
+ that is left as an exercise for the reader.
+
+
+ calculate our initial message.
+
+
+ given a message from a given party and the corresponding public key
+ calculate the next message in the agreement sequence. In this case
+ this will represent the shared secret.
+
+
+ a Diffie-Hellman key agreement class.
+
+ note: This is only the basic algorithm, it doesn't take advantage of
+ long term public keys if they are available. See the DHAgreement class
+ for a "better" implementation.
+
+
+ The basic interface that basic Diffie-Hellman implementations
+ conforms to.
+
+
+ initialise the agreement engine.
+
+
+ given a public key from a given party calculate the next
+ message in the agreement sequence.
+
+
+ given a short term public key from a given party calculate the next
+ message in the agreement sequence.
+
+
+ P1363 7.2.1 ECSVDP-DH
+
+ ECSVDP-DH is Elliptic Curve Secret Value Derivation Primitive,
+ Diffie-Hellman version. It is based on the work of [DH76], [Mil86],
+ and [Kob87]. This primitive derives a shared secret value from one
+ party's private key and another party's public key, where both have
+ the same set of EC domain parameters. If two parties correctly
+ execute this primitive, they will produce the same output. This
+ primitive can be invoked by a scheme to derive a shared secret key;
+ specifically, it may be used with the schemes ECKAS-DH1 and
+ DL/ECKAS-DH2. It assumes that the input keys are valid (see also
+ Section 7.2.2).
+
+
+ P1363 7.2.2 ECSVDP-DHC
+
+ ECSVDP-DHC is Elliptic Curve Secret Value Derivation Primitive,
+ Diffie-Hellman version with cofactor multiplication. It is based on
+ the work of [DH76], [Mil86], [Kob87], [LMQ98] and [Kal98a]. This
+ primitive derives a shared secret value from one party's private key
+ and another party's public key, where both have the same set of EC
+ domain parameters. If two parties correctly execute this primitive,
+ they will produce the same output. This primitive can be invoked by a
+ scheme to derive a shared secret key; specifically, it may be used
+ with the schemes ECKAS-DH1 and DL/ECKAS-DH2. It does not assume the
+ validity of the input public key (see also Section 7.2.1).
+
+ Note: As stated P1363 compatibility mode with ECDH can be preset, and
+ in this case the implementation doesn't have a ECDH compatibility mode
+ (if you want that just use ECDHBasicAgreement and note they both implement
+ BasicAgreement!).
+
+
+ Parameters for key/byte stream derivation classes
+
+
+ RFC 2631 Diffie-hellman KEK derivation function.
+
+
+ base interface for general purpose byte derivation functions.
+
+
+ return the message digest used as the basis for the function
+
+
+ X9.63 based key derivation function for ECDH CMS.
+
+
+ Implements the client side SRP-6a protocol. Note that this class is stateful, and therefore NOT threadsafe.
+ This implementation of SRP is based on the optimized message sequence put forth by Thomas Wu in the paper
+ "SRP-6: Improvements and Refinements to the Secure Remote Password Protocol, 2002"
+
+
+ Initialises the client to begin new authentication attempt
+ @param N The safe prime associated with the client's verifier
+ @param g The group parameter associated with the client's verifier
+ @param digest The digest algorithm associated with the client's verifier
+ @param random For key generation
+
+
+ Generates client's credentials given the client's salt, identity and password
+ @param salt The salt used in the client's verifier.
+ @param identity The user's identity (eg. username)
+ @param password The user's password
+ @return Client's public value to send to server
+
+
+ Generates client's verification message given the server's credentials
+ @param serverB The server's credentials
+ @return Client's verification message for the server
+ @throws CryptoException If server's credentials are invalid
+
+
+ Implements the server side SRP-6a protocol. Note that this class is stateful, and therefore NOT threadsafe.
+ This implementation of SRP is based on the optimized message sequence put forth by Thomas Wu in the paper
+ "SRP-6: Improvements and Refinements to the Secure Remote Password Protocol, 2002"
+
+
+ Initialises the server to accept a new client authentication attempt
+ @param N The safe prime associated with the client's verifier
+ @param g The group parameter associated with the client's verifier
+ @param v The client's verifier
+ @param digest The digest algorithm associated with the client's verifier
+ @param random For key generation
+
+
+ Generates the server's credentials that are to be sent to the client.
+ @return The server's public value to the client
+
+
+ Processes the client's credentials. If valid the shared secret is generated and returned.
+ @param clientA The client's credentials
+ @return A shared secret BigInteger
+ @throws CryptoException If client's credentials are invalid
+
+
+ Generates new SRP verifier for user
+
+
+ Initialises generator to create new verifiers
+ @param N The safe prime to use (see DHParametersGenerator)
+ @param g The group parameter to use (see DHParametersGenerator)
+ @param digest The digest to use. The same digest type will need to be used later for the actual authentication
+ attempt. Also note that the final session key size is dependent on the chosen digest.
+
+
+ Creates a new SRP verifier
+ @param salt The salt to use, generally should be large and random
+ @param identity The user's identifying information (eg. username)
+ @param password The user's password
+ @return A new verifier for use in future SRP authentication
+
+
+ a holding class for public/private parameter pairs.
+
+
+ basic constructor.
+
+ @param publicParam a public key parameters object.
+ @param privateParam the corresponding private key parameters.
+
+
+ return the public key parameters.
+
+ @return the public key parameters.
+
+
+ return the private key parameters.
+
+ @return the private key parameters.
+
+
+ The AEAD block ciphers already handle buffering internally, so this class
+ just takes care of implementing IBufferedCipher methods.
+
+
+ Block cipher engines are expected to conform to this interface.
+
+
+ Initialise the cipher.
+ If true the cipher is initialised for encryption,
+ if false for decryption.
+ The key and other data required by the cipher.
+
+
+
+ Reset the cipher. After resetting the cipher is in the same state
+ as it was after the last init (if there was one).
+
+
+
+ The name of the algorithm this cipher implements.
+
+
+ initialise the cipher.
+
+ @param forEncryption if true the cipher is initialised for
+ encryption, if false for decryption.
+ @param param the key and other data required by the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ return the blocksize for the underlying cipher.
+
+ @return the blocksize for the underlying cipher.
+
+
+ return the size of the output buffer required for an update
+ an input of len bytes.
+
+ @param len the length of the input.
+ @return the space required to accommodate a call to update
+ with len bytes of input.
+
+
+ return the size of the output buffer required for an update plus a
+ doFinal with an input of len bytes.
+
+ @param len the length of the input.
+ @return the space required to accommodate a call to update and doFinal
+ with len bytes of input.
+
+
+ process a single byte, producing an output block if neccessary.
+
+ @param in the input byte.
+ @param out the space for any output that might be produced.
+ @param outOff the offset from which the output will be copied.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there isn't enough space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+
+
+ process an array of bytes, producing output if necessary.
+
+ @param in the input byte array.
+ @param inOff the offset at which the input data starts.
+ @param len the number of bytes to be copied out of the input array.
+ @param out the space for any output that might be produced.
+ @param outOff the offset from which the output will be copied.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there isn't enough space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+
+
+ Process the last block in the buffer.
+
+ @param out the array the block currently being held is copied into.
+ @param outOff the offset at which the copying starts.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there is insufficient space in out for
+ the output, or the input is not block size aligned and should be.
+ @exception InvalidOperationException if the underlying cipher is not
+ initialised.
+ @exception InvalidCipherTextException if padding is expected and not found.
+ @exception DataLengthException if the input is not block size
+ aligned.
+
+
+ Reset the buffer and cipher. After resetting the object is in the same
+ state as it was after the last init (if there was one).
+
+
+ a buffer wrapper for an asymmetric block cipher, allowing input
+ to be accumulated in a piecemeal fashion until final processing.
+
+
+ base constructor.
+
+ @param cipher the cipher this buffering object wraps.
+
+
+ return the amount of data sitting in the buffer.
+
+ @return the amount of data sitting in the buffer.
+
+
+ initialise the buffer and the underlying cipher.
+
+ @param forEncryption if true the cipher is initialised for
+ encryption, if false for decryption.
+ @param param the key and other data required by the cipher.
+
+
+ process the contents of the buffer using the underlying
+ cipher.
+
+ @return the result of the encryption/decryption process on the
+ buffer.
+ @exception InvalidCipherTextException if we are given a garbage block.
+
+
+ Reset the buffer
+
+
+ A wrapper class that allows block ciphers to be used to process data in
+ a piecemeal fashion. The BufferedBlockCipher outputs a block only when the
+ buffer is full and more data is being added, or on a doFinal.
+
+ Note: in the case where the underlying cipher is either a CFB cipher or an
+ OFB one the last block may not be a multiple of the block size.
+
+
+
+ constructor for subclasses
+
+
+ Create a buffered block cipher without padding.
+
+ @param cipher the underlying block cipher this buffering object wraps.
+ false otherwise.
+
+
+ initialise the cipher.
+
+ @param forEncryption if true the cipher is initialised for
+ encryption, if false for decryption.
+ @param param the key and other data required by the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ return the blocksize for the underlying cipher.
+
+ @return the blocksize for the underlying cipher.
+
+
+ return the size of the output buffer required for an update
+ an input of len bytes.
+
+ @param len the length of the input.
+ @return the space required to accommodate a call to update
+ with len bytes of input.
+
+
+ return the size of the output buffer required for an update plus a
+ doFinal with an input of len bytes.
+
+ @param len the length of the input.
+ @return the space required to accommodate a call to update and doFinal
+ with len bytes of input.
+
+
+ process a single byte, producing an output block if neccessary.
+
+ @param in the input byte.
+ @param out the space for any output that might be produced.
+ @param outOff the offset from which the output will be copied.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there isn't enough space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+
+
+ process an array of bytes, producing output if necessary.
+
+ @param in the input byte array.
+ @param inOff the offset at which the input data starts.
+ @param len the number of bytes to be copied out of the input array.
+ @param out the space for any output that might be produced.
+ @param outOff the offset from which the output will be copied.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there isn't enough space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+
+
+ Process the last block in the buffer.
+
+ @param out the array the block currently being held is copied into.
+ @param outOff the offset at which the copying starts.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there is insufficient space in out for
+ the output, or the input is not block size aligned and should be.
+ @exception InvalidOperationException if the underlying cipher is not
+ initialised.
+ @exception InvalidCipherTextException if padding is expected and not found.
+ @exception DataLengthException if the input is not block size
+ aligned.
+
+
+ Reset the buffer and cipher. After resetting the object is in the same
+ state as it was after the last init (if there was one).
+
+
+ The base class for symmetric, or secret, cipher key generators.
+
+
+ initialise the key generator.
+
+ @param param the parameters to be used for key generation
+
+
+ Generate a secret key.
+
+ @return a byte array containing the key value.
+
+
+ this exception is thrown if a buffer that is meant to have output
+ copied into it turns out to be too short, or if we've been given
+ insufficient input. In general this exception will Get thrown rather
+ than an ArrayOutOfBounds exception.
+
+
+ base constructor.
+
+
+ create a DataLengthException with the given message.
+
+ @param message the message to be carried with the exception.
+
+
+ base implementation of MD4 family style digest as outlined in
+ "Handbook of Applied Cryptography", pages 344 - 347.
+
+
+ interface that a message digest conforms to.
+
+
+ return the size, in bytes, of the digest produced by this message digest.
+
+ @return the size, in bytes, of the digest produced by this message digest.
+
+
+ return the size, in bytes, of the internal buffer used by this digest.
+
+ @return the size, in bytes, of the internal buffer used by this digest.
+
+
+ update the message digest with a single byte.
+
+ @param inByte the input byte to be entered.
+
+
+ update the message digest with a block of bytes.
+
+ @param input the byte array containing the data.
+ @param inOff the offset into the byte array where the data starts.
+ @param len the length of the data.
+
+
+ Close the digest, producing the final digest value. The doFinal
+ call leaves the digest reset.
+
+ @param output the array the digest is to be copied into.
+ @param outOff the offset into the out array the digest is to start at.
+
+
+ reset the digest back to it's initial state.
+
+
+ return the algorithm name
+
+ @return the algorithm name
+
+
+ implementation of GOST R 34.11-94
+
+
+ Standard constructor
+
+
+ Constructor to allow use of a particular sbox with GOST28147
+ @see GOST28147Engine#getSBox(String)
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables to the IV values.
+
+
+ Base class for SHA-384 and SHA-512.
+
+
+ Constructor for variable length word
+
+
+ Copy constructor. We are using copy constructors in place
+ of the object.Clone() interface as this interface is not
+ supported by J2ME.
+
+
+ adjust the byte counts so that byteCount2 represents the
+ upper long (less 3 bits) word of the byte count.
+
+
+ implementation of MD2
+ as outlined in RFC1319 by B.Kaliski from RSA Laboratories April 1992
+
+
+ Close the digest, producing the final digest value. The doFinal
+ call leaves the digest reset.
+
+ @param out the array the digest is to be copied into.
+ @param outOff the offset into the out array the digest is to start at.
+
+
+ reset the digest back to it's initial state.
+
+
+ update the message digest with a single byte.
+
+ @param in the input byte to be entered.
+
+
+ update the message digest with a block of bytes.
+
+ @param in the byte array containing the data.
+ @param inOff the offset into the byte array where the data starts.
+ @param len the length of the data.
+
+
+ return the algorithm name
+
+ @return the algorithm name
+
+
+ implementation of MD4 as RFC 1320 by R. Rivest, MIT Laboratory for
+ Computer Science and RSA Data Security, Inc.
+
+ NOTE: This algorithm is only included for backwards compatibility
+ with legacy applications, it's not secure, don't use it for anything new!
+
+
+ Standard constructor
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables to the IV values.
+
+
+ implementation of MD5 as outlined in "Handbook of Applied Cryptography", pages 346 - 347.
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables to the IV values.
+
+
+ implementation of RipeMD128
+
+
+ Standard constructor
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables to the IV values.
+
+
+ implementation of RipeMD see,
+ http://www.esat.kuleuven.ac.be/~bosselae/ripemd160.html
+
+
+ Standard constructor
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables to the IV values.
+
+
+
+
Implementation of RipeMD256.
+
Note: this algorithm offers the same level of security as RipeMD128.
+
+
+
+ Standard constructor
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+
+ reset the chaining variables to the IV values.
+
+
+
+
Implementation of RipeMD 320.
+
Note: this algorithm offers the same level of security as RipeMD160.
+
+
+
+ Standard constructor
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+
+ reset the chaining variables to the IV values.
+
+
+ implementation of SHA-1 as outlined in "Handbook of Applied Cryptography", pages 346 - 349.
+
+ It is interesting to ponder why the, apart from the extra IV, the other difference here from MD5
+ is the "endienness" of the word processing!
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables
+
+
+ SHA-224 as described in RFC 3874
+
+
+
+ Standard constructor
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables
+
+
+ Draft FIPS 180-2 implementation of SHA-256. Note: As this is
+ based on a draft this implementation is subject to change.
+
+
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables
+
+
+ Draft FIPS 180-2 implementation of SHA-384. Note: As this is
+ based on a draft this implementation is subject to change.
+
+
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables
+
+
+ Draft FIPS 180-2 implementation of SHA-512. Note: As this is
+ based on a draft this implementation is subject to change.
+
+
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables
+
+
+ Wrapper class that reduces the output length of a particular digest to
+ only the first n bytes of the digest function.
+
+
+ Base constructor.
+
+ @param baseDigest underlying digest to use.
+ @param length length in bytes of the output of doFinal.
+ @exception ArgumentException if baseDigest is null, or length is greater than baseDigest.GetDigestSize().
+
+
+ implementation of Tiger based on:
+
+ http://www.cs.technion.ac.il/~biham/Reports/Tiger
+
+
+ Standard constructor
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables
+
+
+ Implementation of WhirlpoolDigest, based on Java source published by Barreto
+ and Rijmen.
+
+
+
+ Copy constructor. This will copy the state of the provided message
+ digest.
+
+
+ Reset the chaining variables
+
+
+ ISO 9796-1 padding. Note in the light of recent results you should
+ only use this with RSA (rather than the "simpler" Rabin keys) and you
+ should never use it with anything other than a hash (ie. even if the
+ message is small don't sign the message, sign it's hash) or some "random"
+ value. See your favorite search engine for details.
+
+
+ Base interface for a public/private key block cipher.
+
+
+ Initialise the cipher.
+ Initialise for encryption if true, for decryption if false.
+ The key or other data required by the cipher.
+
+
+ The maximum size, in bytes, an input block may be.
+
+
+ The maximum size, in bytes, an output block will be.
+
+
+ Process a block.
+ The input buffer.
+ The offset into inBuf that the input block begins.
+ The length of the input block.
+ Input decrypts improperly.
+ Input is too large for the cipher.
+
+
+ The name of the algorithm this cipher implements.
+
+
+ return the input block size. The largest message we can process
+ is (key_size_in_bits + 3)/16, which in our world comes to
+ key_size_in_bytes / 2.
+
+
+ return the maximum possible size for the output.
+
+
+ set the number of bits in the next message to be treated as
+ pad bits.
+
+
+ retrieve the number of pad bits in the last decoded message.
+
+
+ @exception InvalidCipherTextException if the decrypted block is not a valid ISO 9796 bit string
+
+
+ Optimal Asymmetric Encryption Padding (OAEP) - see PKCS 1 V 2.
+
+
+ @exception InvalidCipherTextException if the decrypted block turns out to
+ be badly formatted.
+
+
+ int to octet string.
+
+
+ mask generator function, as described in PKCS1v2.
+
+
+ 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.
+
+
+ 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.BouncyCastle.Pkcs1.Strict to false.
+
+
+ Basic constructor.
+ @param cipher
+
+
+ @exception InvalidCipherTextException if the decrypted block is not in Pkcs1 format.
+
+
+ The same effect can be achieved by setting the static property directly
+
+ The static property is checked during construction of the encoding object, it is set to
+ true by default.
+
+
+
+ an implementation of the AES (Rijndael), from FIPS-197.
+
+ For further details see: http://csrc.nist.gov/encryption/aes/.
+
+ This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at
+ http://fp.gladman.plus.com/cryptography_technology/rijndael/
+
+ There are three levels of tradeoff of speed vs memory
+ Because java has no preprocessor, they are written as three separate classes from which to choose
+
+ The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption
+ and 4 for decryption.
+
+ The middle performance version uses only one 256 word table for each, for a total of 2Kbytes,
+ adding 12 rotate operations per round to compute the values contained in the other tables from
+ the contents of the first.
+
+ The slowest version uses no static tables at all and computes the values in each round.
+
+
+ This file contains the middle performance version with 2Kbytes of static tables for round precomputation.
+
+
+
+ Base interface for a symmetric key block cipher.
+
+
+ Initialise the cipher.
+ Initialise for encryption if true, for decryption if false.
+ The key or other data required by the cipher.
+
+
+ The block size for this cipher, in bytes.
+
+
+ Process a block.
+ The input buffer.
+ The offset into inBuf that the input block begins.
+ The output buffer.
+ The offset into outBuf to write the output block.
+ If input block is wrong size, or outBuf too small.
+ The number of bytes processed and produced.
+
+
+
+ Reset the cipher to the same state as it was after the last init (if there was one).
+
+
+
+ The name of the algorithm this cipher implements.
+
+
+ Indicates whether this cipher can handle partial blocks.
+
+
+ Calculate the necessary round keys
+ The number of calculations depends on key size and block size
+ AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits
+ This code is written assuming those are the only possible values
+
+
+ default constructor - 128 bit block size.
+
+
+ initialise an AES cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ an implementation of the AES (Rijndael)), from FIPS-197.
+
+ For further details see: http://csrc.nist.gov/encryption/aes/.
+
+ This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at
+ http://fp.gladman.plus.com/cryptography_technology/rijndael/
+
+ There are three levels of tradeoff of speed vs memory
+ Because java has no preprocessor), they are written as three separate classes from which to choose
+
+ The fastest uses 8Kbytes of static tables to precompute round calculations), 4 256 word tables for encryption
+ and 4 for decryption.
+
+ The middle performance version uses only one 256 word table for each), for a total of 2Kbytes),
+ adding 12 rotate operations per round to compute the values contained in the other tables from
+ the contents of the first
+
+ The slowest version uses no static tables at all and computes the values in each round
+
+
+ This file contains the fast version with 8Kbytes of static tables for round precomputation
+
+
+
+ Calculate the necessary round keys
+ The number of calculations depends on key size and block size
+ AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits
+ This code is written assuming those are the only possible values
+
+
+ default constructor - 128 bit block size.
+
+
+ initialise an AES cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ an implementation of the AES (Rijndael), from FIPS-197.
+
+ For further details see: http://csrc.nist.gov/encryption/aes/.
+
+ This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at
+ http://fp.gladman.plus.com/cryptography_technology/rijndael/
+
+ There are three levels of tradeoff of speed vs memory
+ Because java has no preprocessor, they are written as three separate classes from which to choose
+
+ The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption
+ and 4 for decryption.
+
+ The middle performance version uses only one 256 word table for each, for a total of 2Kbytes,
+ adding 12 rotate operations per round to compute the values contained in the other tables from
+ the contents of the first
+
+ The slowest version uses no static tables at all and computes the values
+ in each round.
+
+
+ This file contains the slowest performance version with no static tables
+ for round precomputation, but it has the smallest foot print.
+
+
+
+ Calculate the necessary round keys
+ The number of calculations depends on key size and block size
+ AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits
+ This code is written assuming those are the only possible values
+
+
+ default constructor - 128 bit block size.
+
+
+ initialise an AES cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+
+ An implementation of the AES Key Wrapper from the NIST Key Wrap Specification.
+
+ For further details see: http://csrc.nist.gov/encryption/kms/key-wrap.pdf.
+
+
+
+
+ An implementation of the AES Key Wrapper from the NIST Key Wrap
+ Specification as described in RFC 3394.
+
+ For further details see: http://www.ietf.org/rfc/rfc3394.txt
+ and http://csrc.nist.gov/encryption/kms/key-wrap.pdf.
+
+
+
+ The name of the algorithm this cipher implements.
+
+
+ A class that provides Blowfish key encryption operations,
+ such as encoding data and generating keys.
+ All the algorithms herein are from Applied Cryptography
+ and implement a simplified cryptography interface.
+
+
+ initialise a Blowfish cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ apply the encryption cycle to each value pair in the table.
+
+
+ Encrypt the given input starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+ The input will be an exact multiple of our blocksize.
+
+
+ Decrypt the given input starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+ The input will be an exact multiple of our blocksize.
+
+
+ Camellia - based on RFC 3713.
+
+
+ Camellia - based on RFC 3713, smaller implementation, about half the size of CamelliaEngine.
+
+
+
+ An implementation of the Camellia key wrapper based on RFC 3657/RFC 3394.
+
+ For further details see: http://www.ietf.org/rfc/rfc3657.txt.
+
+
+
+ A class that provides CAST key encryption operations,
+ such as encoding data and generating keys.
+
+ All the algorithms herein are from the Internet RFC's
+
+ RFC2144 - Cast5 (64bit block, 40-128bit key)
+ RFC2612 - CAST6 (128bit block, 128-256bit key)
+
+ and implement a simplified cryptography interface.
+
+
+ initialise a CAST cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ Encrypt the given input starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+
+ @param src The plaintext buffer
+ @param srcIndex An offset into src
+ @param dst The ciphertext buffer
+ @param dstIndex An offset into dst
+
+
+ Decrypt the given input starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+
+ @param src The plaintext buffer
+ @param srcIndex An offset into src
+ @param dst The ciphertext buffer
+ @param dstIndex An offset into dst
+
+
+ The first of the three processing functions for the
+ encryption and decryption.
+
+ @param D the input to be processed
+ @param Kmi the mask to be used from Km[n]
+ @param Kri the rotation value to be used
+
+
+
+ The second of the three processing functions for the
+ encryption and decryption.
+
+ @param D the input to be processed
+ @param Kmi the mask to be used from Km[n]
+ @param Kri the rotation value to be used
+
+
+
+ The third of the three processing functions for the
+ encryption and decryption.
+
+ @param D the input to be processed
+ @param Kmi the mask to be used from Km[n]
+ @param Kri the rotation value to be used
+
+
+
+ Does the 16 rounds to encrypt the block.
+
+ @param L0 the LH-32bits of the plaintext block
+ @param R0 the RH-32bits of the plaintext block
+
+
+ A class that provides CAST6 key encryption operations,
+ such as encoding data and generating keys.
+
+ All the algorithms herein are from the Internet RFC
+
+ RFC2612 - CAST6 (128bit block, 128-256bit key)
+
+ and implement a simplified cryptography interface.
+
+
+ Encrypt the given input starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+
+ @param src The plaintext buffer
+ @param srcIndex An offset into src
+ @param dst The ciphertext buffer
+ @param dstIndex An offset into dst
+
+
+ Decrypt the given input starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+
+ @param src The plaintext buffer
+ @param srcIndex An offset into src
+ @param dst The ciphertext buffer
+ @param dstIndex An offset into dst
+
+
+ Does the 12 quad rounds rounds to encrypt the block.
+
+ @param A the 00-31 bits of the plaintext block
+ @param B the 32-63 bits of the plaintext block
+ @param C the 64-95 bits of the plaintext block
+ @param D the 96-127 bits of the plaintext block
+ @param result the resulting ciphertext
+
+
+ Does the 12 quad rounds rounds to decrypt the block.
+
+ @param A the 00-31 bits of the ciphertext block
+ @param B the 32-63 bits of the ciphertext block
+ @param C the 64-95 bits of the ciphertext block
+ @param D the 96-127 bits of the ciphertext block
+ @param result the resulting plaintext
+
+
+ A class that provides a basic DESede (or Triple DES) engine.
+
+
+ A class that provides a basic DES engine.
+
+
+ initialise a DES cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ what follows is mainly taken from "Applied Cryptography", by
+ Bruce Schneier, however it also bears great resemblance to Richard
+ Outerbridge's D3DES...
+
+
+ Generate an integer based working key based on our secret key
+ and what we processing we are planning to do.
+
+ Acknowledgements for this routine go to James Gillogly and Phil Karn.
+ (whoever, and wherever they are!).
+
+
+ the DES engine.
+
+
+ initialise a DESede cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ * Wrap keys according to
+ *
+ * draft-ietf-smime-key-wrap-01.txt.
+ *
+ * Note:
+ *
+ *
this is based on a draft, and as such is subject to change - don't use this class for anything requiring long term storage.
+ *
if you are using this to wrap triple-des keys you need to set the
+ * parity bits on the key and, if it's a two-key triple-des key, pad it
+ * yourself.
+ *
+ *
+
+
+ Field engine
+
+
+ Field param
+
+
+ Field paramPlusIV
+
+
+ Field iv
+
+
+ Field forWrapping
+
+
+ Field IV2
+
+
+ Method init
+
+ @param forWrapping
+ @param param
+
+
+ Method wrap
+
+ @param in
+ @param inOff
+ @param inLen
+ @return
+
+
+ Method unwrap
+
+ @param in
+ @param inOff
+ @param inLen
+ @return
+ @throws InvalidCipherTextException
+
+
+ Some key wrap algorithms make use of the Key Checksum defined
+ in CMS [CMS-Algorithms]. This is used to provide an integrity
+ check value for the key being wrapped. The algorithm is
+
+ - Compute the 20 octet SHA-1 hash on the key being wrapped.
+ - Use the first 8 octets of this hash as the checksum value.
+
+ @param key
+ @return
+ @throws Exception
+ @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
+
+
+ @param key
+ @param checksum
+ @return
+ @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
+
+
+ Method GetAlgorithmName
+
+ @return
+
+
+ this does your basic ElGamal algorithm.
+
+
+ initialise the ElGamal engine.
+
+ @param forEncryption true if we are encrypting, false otherwise.
+ @param param the necessary ElGamal key parameters.
+
+
+ Return the maximum size for an input block to this engine.
+ For ElGamal this is always one byte less than the size of P on
+ encryption, and twice the length as the size of P on decryption.
+
+ @return maximum size for an input block.
+
+
+ Return the maximum size for an output block to this engine.
+ For ElGamal this is always one byte less than the size of P on
+ decryption, and twice the length as the size of P on encryption.
+
+ @return maximum size for an output block.
+
+
+ Process a single block using the basic ElGamal algorithm.
+
+ @param in the input array.
+ @param inOff the offset into the input buffer where the data starts.
+ @param length the length of the data to be processed.
+ @return the result of the ElGamal process.
+ @exception DataLengthException the input block is too large.
+
+
+ implementation of GOST 28147-89
+
+
+ standard constructor.
+
+
+ initialise an Gost28147 cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is inappropriate.
+
+
+ Return the S-Box associated with SBoxName
+ @param sBoxName name of the S-Box
+ @return byte array representing the S-Box
+
+
+ HC-128 is a software-efficient stream cipher created by Hongjun Wu. It
+ generates keystream from a 128-bit secret key and a 128-bit initialization
+ vector.
+
+ It is a third phase candidate in the eStream contest, and is patent-free.
+ No attacks are known as of today (April 2007). See
+
+ http://www.ecrypt.eu.org/stream/hcp3.html
+
+
+
+ The interface stream ciphers conform to.
+
+
+ Initialise the cipher.
+ If true the cipher is initialised for encryption,
+ if false for decryption.
+ The key and other data required by the cipher.
+
+ If the parameters argument is inappropriate.
+
+
+
+ encrypt/decrypt a single byte returning the result.
+ the byte to be processed.
+ the result of processing the input byte.
+
+
+
+ Process a block of bytes from input putting the result into output.
+
+ The input byte array.
+
+ The offset into input where the data to be processed starts.
+
+ The number of bytes to be processed.
+ The output buffer the processed bytes go into.
+
+ The offset into output the processed data starts at.
+
+ If the output buffer is too small.
+
+
+
+ Reset the cipher to the same state as it was after the last init (if there was one).
+
+
+
+ The name of the algorithm this cipher implements.
+
+
+ Initialise a HC-128 cipher.
+
+ @param forEncryption whether or not we are for encryption. Irrelevant, as
+ encryption and decryption are the same.
+ @param params the parameters required to set up the cipher.
+ @throws ArgumentException if the params argument is
+ inappropriate (ie. the key is not 128 bit long).
+
+
+ HC-256 is a software-efficient stream cipher created by Hongjun Wu. It
+ generates keystream from a 256-bit secret key and a 256-bit initialization
+ vector.
+
+ Its brother, HC-128, is a third phase candidate in the eStream contest.
+ The algorithm is patent-free. No attacks are known as of today (April 2007).
+ See
+
+ http://www.ecrypt.eu.org/stream/hcp3.html
+
+
+
+ Initialise a HC-256 cipher.
+
+ @param forEncryption whether or not we are for encryption. Irrelevant, as
+ encryption and decryption are the same.
+ @param params the parameters required to set up the cipher.
+ @throws ArgumentException if the params argument is
+ inappropriate (ie. the key is not 256 bit long).
+
+
+ support class for constructing intergrated encryption ciphers
+ for doing basic message exchanges on top of key agreement ciphers
+
+
+ set up for use with stream mode, where the key derivation function
+ is used to provide a stream of bytes to xor with the message.
+
+ @param agree the key agreement used as the basis for the encryption
+ @param kdf the key derivation function used for byte generation
+ @param mac the message authentication code generator for the message
+
+
+ set up for use in conjunction with a block cipher to handle the
+ message.
+
+ @param agree the key agreement used as the basis for the encryption
+ @param kdf the key derivation function used for byte generation
+ @param mac the message authentication code generator for the message
+ @param cipher the cipher to used for encrypting the message
+
+
+ Initialise the encryptor.
+
+ @param forEncryption whether or not this is encryption/decryption.
+ @param privParam our private key parameters
+ @param pubParam the recipient's/sender's public key parameters
+ @param param encoding and derivation parameters.
+
+
+ Implementation of Bob Jenkin's ISAAC (Indirection Shift Accumulate Add and Count).
+ see: http://www.burtleburtle.net/bob/rand/isaacafa.html
+
+
+ initialise an ISAAC cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param params the parameters required to set up the cipher.
+ @exception ArgumentException if the params argument is
+ inappropriate.
+
+
+ NaccacheStern Engine. For details on this cipher, please see
+ http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
+
+
+ Initializes this algorithm. Must be called before all other Functions.
+
+ @see org.bouncycastle.crypto.AsymmetricBlockCipher#init(bool,
+ org.bouncycastle.crypto.CipherParameters)
+
+
+ Returns the input block size of this algorithm.
+
+ @see org.bouncycastle.crypto.AsymmetricBlockCipher#GetInputBlockSize()
+
+
+ Returns the output block size of this algorithm.
+
+ @see org.bouncycastle.crypto.AsymmetricBlockCipher#GetOutputBlockSize()
+
+
+ Process a single Block using the Naccache-Stern algorithm.
+
+ @see org.bouncycastle.crypto.AsymmetricBlockCipher#ProcessBlock(byte[],
+ int, int)
+
+
+ Encrypts a BigInteger aka Plaintext with the public key.
+
+ @param plain
+ The BigInteger to encrypt
+ @return The byte[] representation of the encrypted BigInteger (i.e.
+ crypted.toByteArray())
+
+
+ Adds the contents of two encrypted blocks mod sigma
+
+ @param block1
+ the first encrypted block
+ @param block2
+ the second encrypted block
+ @return encrypt((block1 + block2) mod sigma)
+ @throws InvalidCipherTextException
+
+
+ Convenience Method for data exchange with the cipher.
+
+ Determines blocksize and splits data to blocksize.
+
+ @param data the data to be processed
+ @return the data after it went through the NaccacheSternEngine.
+ @throws InvalidCipherTextException
+
+
+ Computes the integer x that is expressed through the given primes and the
+ congruences with the chinese remainder theorem (CRT).
+
+ @param congruences
+ the congruences c_i
+ @param primes
+ the primes p_i
+ @return an integer x for that x % p_i == c_i
+
+
+ A Noekeon engine, using direct-key mode.
+
+
+ Create an instance of the Noekeon encryption algorithm
+ and set some defaults
+
+
+ initialise
+
+ @param forEncryption whether or not we are for encryption.
+ @param params the parameters required to set up the cipher.
+ @exception ArgumentException if the params argument is
+ inappropriate.
+
+
+ Re-key the cipher.
+
+ @param key the key to be used
+
+
+ The no-op engine that just copies bytes through, irrespective of whether encrypting and decrypting.
+ Provided for the sake of completeness.
+
+
+ an implementation of RC2 as described in RFC 2268
+ "A Description of the RC2(r) Encryption Algorithm" R. Rivest.
+
+
+ initialise a RC2 cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ return the result rotating the 16 bit number in x left by y
+
+
+ Wrap keys according to RFC 3217 - RC2 mechanism
+
+
+ Field engine
+
+
+ Field param
+
+
+ Field paramPlusIV
+
+
+ Field iv
+
+
+ Field forWrapping
+
+
+ Field IV2
+
+
+ Method init
+
+ @param forWrapping
+ @param param
+
+
+ Method wrap
+
+ @param in
+ @param inOff
+ @param inLen
+ @return
+
+
+ Method unwrap
+
+ @param in
+ @param inOff
+ @param inLen
+ @return
+ @throws InvalidCipherTextException
+
+
+ Some key wrap algorithms make use of the Key Checksum defined
+ in CMS [CMS-Algorithms]. This is used to provide an integrity
+ check value for the key being wrapped. The algorithm is
+
+ - Compute the 20 octet SHA-1 hash on the key being wrapped.
+ - Use the first 8 octets of this hash as the checksum value.
+
+ @param key
+ @return
+ @throws Exception
+ @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
+
+
+ @param key
+ @param checksum
+ @return
+ @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
+
+
+ Method GetAlgorithmName
+
+ @return
+
+
+ initialise a RC4 cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ The specification for RC5 came from the RC5 Encryption Algorithm
+ publication in RSA CryptoBytes, Spring of 1995.
+ http://www.rsasecurity.com/rsalabs/cryptobytes.
+
+ This implementation has a word size of 32 bits.
+
+
+ Create an instance of the RC5 encryption algorithm
+ and set some defaults
+
+
+ initialise a RC5-32 cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ Re-key the cipher.
+
+ @param key the key to be used
+
+
+ Encrypt the given block starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+
+ @param in in byte buffer containing data to encrypt
+ @param inOff offset into src buffer
+ @param out out buffer where encrypted data is written
+ @param outOff offset into out buffer
+
+
+ Perform a left "spin" of the word. The rotation of the given
+ word x is rotated left by y bits.
+ Only the lg(32) low-order bits of y
+ are used to determine the rotation amount. Here it is
+ assumed that the wordsize used is a power of 2.
+
+ @param x word to rotate
+ @param y number of bits to rotate % 32
+
+
+ Perform a right "spin" of the word. The rotation of the given
+ word x is rotated left by y bits.
+ Only the lg(32) low-order bits of y
+ are used to determine the rotation amount. Here it is
+ assumed that the wordsize used is a power of 2.
+
+ @param x word to rotate
+ @param y number of bits to rotate % 32
+
+
+ The specification for RC5 came from the RC5 Encryption Algorithm
+ publication in RSA CryptoBytes, Spring of 1995.
+ http://www.rsasecurity.com/rsalabs/cryptobytes.
+
+ This implementation is set to work with a 64 bit word size.
+
+
+ Create an instance of the RC5 encryption algorithm
+ and set some defaults
+
+
+ initialise a RC5-64 cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ Re-key the cipher.
+
+ @param key the key to be used
+
+
+ Encrypt the given block starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+
+ @param in in byte buffer containing data to encrypt
+ @param inOff offset into src buffer
+ @param out out buffer where encrypted data is written
+ @param outOff offset into out buffer
+
+
+ Perform a left "spin" of the word. The rotation of the given
+ word x is rotated left by y bits.
+ Only the lg(wordSize) low-order bits of y
+ are used to determine the rotation amount. Here it is
+ assumed that the wordsize used is a power of 2.
+
+ @param x word to rotate
+ @param y number of bits to rotate % wordSize
+
+
+ Perform a right "spin" of the word. The rotation of the given
+ word x is rotated left by y bits.
+ Only the lg(wordSize) low-order bits of y
+ are used to determine the rotation amount. Here it is
+ assumed that the wordsize used is a power of 2.
+
+ @param x word to rotate
+ @param y number of bits to rotate % wordSize
+
+
+ An RC6 engine.
+
+
+ Create an instance of the RC6 encryption algorithm
+ and set some defaults
+
+
+ initialise a RC5-32 cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ Re-key the cipher.
+
+ @param inKey the key to be used
+
+
+ Perform a left "spin" of the word. The rotation of the given
+ word x is rotated left by y bits.
+ Only the lg(wordSize) low-order bits of y
+ are used to determine the rotation amount. Here it is
+ assumed that the wordsize used is a power of 2.
+
+ @param x word to rotate
+ @param y number of bits to rotate % wordSize
+
+
+ Perform a right "spin" of the word. The rotation of the given
+ word x is rotated left by y bits.
+ Only the lg(wordSize) low-order bits of y
+ are used to determine the rotation amount. Here it is
+ assumed that the wordsize used is a power of 2.
+
+ @param x word to rotate
+ @param y number of bits to rotate % wordSize
+
+
+ an implementation of the RFC 3211 Key Wrap
+ Specification.
+
+
+ an implementation of Rijndael, based on the documentation and reference implementation
+ by Paulo Barreto, Vincent Rijmen, for v2.0 August '99.
+
+ Note: this implementation is based on information prior to readonly NIST publication.
+
+
+
+ multiply two elements of GF(2^m)
+ needed for MixColumn and InvMixColumn
+
+
+ xor corresponding text input and round key input bytes
+
+
+ Row 0 remains unchanged
+ The other three rows are shifted a variable amount
+
+
+ Replace every byte of the input by the byte at that place
+ in the nonlinear S-box
+
+
+ Mix the bytes of every column in a linear way
+
+
+ Mix the bytes of every column in a linear way
+ This is the opposite operation of Mixcolumn
+
+
+ Calculate the necessary round keys
+ The number of calculations depends on keyBits and blockBits
+
+
+ default constructor - 128 bit block size.
+
+
+ basic constructor - set the cipher up for a given blocksize
+
+ @param blocksize the blocksize in bits, must be 128, 192, or 256.
+
+
+ initialise a Rijndael cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ this does your basic RSA algorithm with blinding
+
+
+ initialise the RSA engine.
+
+ @param forEncryption true if we are encrypting, false otherwise.
+ @param param the necessary RSA key parameters.
+
+
+ Return the maximum size for an input block to this engine.
+ For RSA this is always one byte less than the key size on
+ encryption, and the same length as the key size on decryption.
+
+ @return maximum size for an input block.
+
+
+ Return the maximum size for an output block to this engine.
+ For RSA this is always one byte less than the key size on
+ decryption, and the same length as the key size on encryption.
+
+ @return maximum size for an output block.
+
+
+ Process a single block using the basic RSA algorithm.
+
+ @param inBuf the input array.
+ @param inOff the offset into the input buffer where the data starts.
+ @param inLen the length of the data to be processed.
+ @return the result of the RSA process.
+ @exception DataLengthException the input block is too large.
+
+
+ This does your basic RSA Chaum's blinding and unblinding as outlined in
+ "Handbook of Applied Cryptography", page 475. You need to use this if you are
+ trying to get another party to generate signatures without them being aware
+ of the message they are signing.
+
+
+ Initialise the blinding engine.
+
+ @param forEncryption true if we are encrypting (blinding), false otherwise.
+ @param param the necessary RSA key parameters.
+
+
+ Return the maximum size for an input block to this engine.
+ For RSA this is always one byte less than the key size on
+ encryption, and the same length as the key size on decryption.
+
+ @return maximum size for an input block.
+
+
+ Return the maximum size for an output block to this engine.
+ For RSA this is always one byte less than the key size on
+ decryption, and the same length as the key size on encryption.
+
+ @return maximum size for an output block.
+
+
+ Process a single block using the RSA blinding algorithm.
+
+ @param in the input array.
+ @param inOff the offset into the input buffer where the data starts.
+ @param inLen the length of the data to be processed.
+ @return the result of the RSA process.
+ @throws DataLengthException the input block is too large.
+
+
+ this does your basic RSA algorithm.
+
+
+ initialise the RSA engine.
+
+ @param forEncryption true if we are encrypting, false otherwise.
+ @param param the necessary RSA key parameters.
+
+
+ Return the maximum size for an input block to this engine.
+ For RSA this is always one byte less than the key size on
+ encryption, and the same length as the key size on decryption.
+
+ @return maximum size for an input block.
+
+
+ Return the maximum size for an output block to this engine.
+ For RSA this is always one byte less than the key size on
+ decryption, and the same length as the key size on encryption.
+
+ @return maximum size for an output block.
+
+
+ this does your basic RSA algorithm.
+
+
+ initialise the RSA engine.
+
+ @param forEncryption true if we are encrypting, false otherwise.
+ @param param the necessary RSA key parameters.
+
+
+ Return the maximum size for an input block to this engine.
+ For RSA this is always one byte less than the key size on
+ encryption, and the same length as the key size on decryption.
+
+ @return maximum size for an input block.
+
+
+ Return the maximum size for an output block to this engine.
+ For RSA this is always one byte less than the key size on
+ decryption, and the same length as the key size on encryption.
+
+ @return maximum size for an output block.
+
+
+ Process a single block using the basic RSA algorithm.
+
+ @param inBuf the input array.
+ @param inOff the offset into the input buffer where the data starts.
+ @param inLen the length of the data to be processed.
+ @return the result of the RSA process.
+ @exception DataLengthException the input block is too large.
+
+
+ Implementation of Daniel J. Bernstein's Salsa20 stream cipher, Snuffle 2005
+
+
+ Constants
+
+
+ initialise a Salsa20 cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param params the parameters required to set up the cipher.
+ @exception ArgumentException if the params argument is
+ inappropriate.
+
+
+ Implementation of the SEED algorithm as described in RFC 4009
+
+
+
+ An implementation of the SEED key wrapper based on RFC 4010/RFC 3394.
+
+ For further details see: http://www.ietf.org/rfc/rfc4010.txt.
+
+
+
+ * Serpent is a 128-bit 32-round block cipher with variable key lengths,
+ * including 128, 192 and 256 bit keys conjectured to be at least as
+ * secure as three-key triple-DES.
+ *
+ * Serpent was designed by Ross Anderson, Eli Biham and Lars Knudsen as a
+ * candidate algorithm for the NIST AES Quest.>
+ *
+
+
+ initialise a Serpent cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ Process one block of input from the array in and write it to
+ the out array.
+
+ @param in the array containing the input data.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the output data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ Expand a user-supplied key material into a session key.
+
+ @param key The user-key bytes (multiples of 4) to use.
+ @exception ArgumentException
+
+
+ Encrypt one block of plaintext.
+
+ @param in the array containing the input data.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the output data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+
+
+ Decrypt one block of ciphertext.
+
+ @param in the array containing the input data.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the output data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+
+
+ S0 - { 3, 8,15, 1,10, 6, 5,11,14,13, 4, 2, 7, 0, 9,12 } - 15 terms.
+
+
+ InvSO - {13, 3,11, 0,10, 6, 5,12, 1,14, 4, 7,15, 9, 8, 2 } - 15 terms.
+
+
+ S1 - {15,12, 2, 7, 9, 0, 5,10, 1,11,14, 8, 6,13, 3, 4 } - 14 terms.
+
+
+ InvS1 - { 5, 8, 2,14,15, 6,12, 3,11, 4, 7, 9, 1,13,10, 0 } - 14 steps.
+
+
+ S2 - { 8, 6, 7, 9, 3,12,10,15,13, 1,14, 4, 0,11, 5, 2 } - 16 terms.
+
+
+ InvS2 - {12, 9,15, 4,11,14, 1, 2, 0, 3, 6,13, 5, 8,10, 7 } - 16 steps.
+
+
+ S3 - { 0,15,11, 8,12, 9, 6, 3,13, 1, 2, 4,10, 7, 5,14 } - 16 terms.
+
+
+ InvS3 - { 0, 9,10, 7,11,14, 6,13, 3, 5,12, 2, 4, 8,15, 1 } - 15 terms
+
+
+ S4 - { 1,15, 8, 3,12, 0,11, 6, 2, 5, 4,10, 9,14, 7,13 } - 15 terms.
+
+
+ InvS4 - { 5, 0, 8, 3,10, 9, 7,14, 2,12,11, 6, 4,15,13, 1 } - 15 terms.
+
+
+ S5 - {15, 5, 2,11, 4,10, 9,12, 0, 3,14, 8,13, 6, 7, 1 } - 16 terms.
+
+
+ InvS5 - { 8,15, 2, 9, 4, 1,13,14,11, 6, 5, 3, 7,12,10, 0 } - 16 terms.
+
+
+ S6 - { 7, 2,12, 5, 8, 4, 6,11,14, 9, 1,15,13, 3,10, 0 } - 15 terms.
+
+
+ InvS6 - {15,10, 1,13, 5, 3, 6, 0, 4, 9,14, 7, 2,12, 8,11 } - 15 terms.
+
+
+ S7 - { 1,13,15, 0,14, 8, 2,11, 7, 4,12,10, 9, 3, 5, 6 } - 16 terms.
+
+
+ InvS7 - { 3, 0, 6,13, 9,14,15, 8, 5,12,11, 7,10, 1, 4, 2 } - 17 terms.
+
+
+ Apply the linear transformation to the register set.
+
+
+ Apply the inverse of the linear transformation to the register set.
+
+
+ a class that provides a basic SKIPJACK engine.
+
+
+ initialise a SKIPJACK cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ The G permutation
+
+
+ the inverse of the G permutation.
+
+
+ An TEA engine.
+
+
+ Create an instance of the TEA encryption algorithm
+ and set some defaults
+
+
+ initialise
+
+ @param forEncryption whether or not we are for encryption.
+ @param params the parameters required to set up the cipher.
+ @exception ArgumentException if the params argument is
+ inappropriate.
+
+
+ Re-key the cipher.
+
+ @param key the key to be used
+
+
+ A class that provides Twofish encryption operations.
+
+ This Java implementation is based on the Java reference
+ implementation provided by Bruce Schneier and developed
+ by Raif S. Naffah.
+
+
+ Define the fixed p0/p1 permutations used in keyed S-box lookup.
+ By changing the following constant definitions, the S-boxes will
+ automatically Get changed in the Twofish engine.
+
+
+ gSubKeys[] and gSBox[] are eventually used in the
+ encryption and decryption methods.
+
+
+ initialise a Twofish cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ Encrypt the given input starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+ The input will be an exact multiple of our blocksize.
+
+ encryptBlock uses the pre-calculated gSBox[] and subKey[]
+ arrays.
+
+
+ Decrypt the given input starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+ The input will be an exact multiple of our blocksize.
+
+
+ Use (12, 8) Reed-Solomon code over GF(256) to produce
+ a key S-box 32-bit entity from 2 key material 32-bit
+ entities.
+
+ @param k0 first 32-bit entity
+ @param k1 second 32-bit entity
+ @return Remainder polynomial Generated using RS code
+
+
+ * Reed-Solomon code parameters: (12,8) reversible code:
+ *
+ * where a = primitive root of field generator 0x14D
+ *
+
+
+ initialise a VMPC cipher.
+
+ @param forEncryption
+ whether or not we are for encryption.
+ @param params
+ the parameters required to set up the cipher.
+ @exception ArgumentException
+ if the params argument is inappropriate.
+
+
+ An XTEA engine.
+
+
+ Create an instance of the TEA encryption algorithm
+ and set some defaults
+
+
+ initialise
+
+ @param forEncryption whether or not we are for encryption.
+ @param params the parameters required to set up the cipher.
+ @exception ArgumentException if the params argument is
+ inappropriate.
+
+
+ Re-key the cipher.
+
+ @param key the key to be used
+
+
+ Basic KDF generator for derived keys and ivs as defined by IEEE P1363a/ISO 18033
+
+ This implementation is based on ISO 18033/P1363a.
+
+
+ Construct a KDF Parameters generator.
+
+ @param counterStart value of counter.
+ @param digest the digest to be used as the source of derived keys.
+
+
+ fill len bytes of the output buffer with bytes generated from
+ the derivation function.
+
+ @throws ArgumentException if the size of the request will cause an overflow.
+ @throws DataLengthException if the out buffer is too small.
+
+
+ return the underlying digest.
+
+
+ initialise the key generator - if strength is set to zero
+ the key generated will be 64 bits in size, otherwise
+ strength can be 64 or 56 bits (if you don't count the parity bits).
+
+ @param param the parameters to be used for key generation
+
+
+ initialise the key generator - if strength is set to zero
+ the key Generated will be 192 bits in size, otherwise
+ strength can be 128 or 192 (or 112 or 168 if you don't count
+ parity bits), depending on whether you wish to do 2-key or 3-key
+ triple DES.
+
+ @param param the parameters to be used for key generation
+
+
+ a basic Diffie-Hellman key pair generator.
+
+ This generates keys consistent for use with the basic algorithm for
+ Diffie-Hellman.
+
+
+ interface that a public/private key pair generator should conform to.
+
+
+ intialise the key pair generator.
+
+ @param the parameters the key pair is to be initialised with.
+
+
+ return an AsymmetricCipherKeyPair containing the Generated keys.
+
+ @return an AsymmetricCipherKeyPair containing the Generated keys.
+
+
+ a Diffie-Hellman key pair generator.
+
+ This generates keys consistent for use in the MTI/A0 key agreement protocol
+ as described in "Handbook of Applied Cryptography", Pages 516-519.
+
+
+ which Generates the p and g values from the given parameters,
+ returning the DHParameters object.
+
+ Note: can take a while...
+
+
+ * a DSA key pair generator.
+ *
+ * This Generates DSA keys in line with the method described
+ * in FIPS 186-3 B.1 FFC Key Pair Generation.
+
+
+ Generate suitable parameters for DSA, in line with FIPS 186-2.
+
+
+ initialise the key generator.
+
+ @param size size of the key (range 2^512 -> 2^1024 - 64 bit increments)
+ @param certainty measure of robustness of prime (for FIPS 186-2 compliance this should be at least 80).
+ @param random random byte source.
+
+
+ which Generates the p and g values from the given parameters,
+ returning the DsaParameters object.
+
+ Note: can take a while...
+
+
+ generate suitable parameters for DSA, in line with
+ FIPS 186-3 A.1 Generation of the FFC Primes p and q.
+
+
+ Given the domain parameters this routine Generates an EC key
+ pair in accordance with X9.62 section 5.2.1 pages 26, 27.
+
+
+ a ElGamal key pair generator.
+
+ This Generates keys consistent for use with ElGamal as described in
+ page 164 of "Handbook of Applied Cryptography".
+
+
+ * which Generates the p and g values from the given parameters,
+ * returning the ElGamalParameters object.
+ *
+ * Note: can take a while...
+ *
+
+
+ a GOST3410 key pair generator.
+ This generates GOST3410 keys in line with the method described
+ in GOST R 34.10-94.
+
+
+ generate suitable parameters for GOST3410.
+
+
+ initialise the key generator.
+
+ @param size size of the key
+ @param typeProcedure type procedure A,B = 1; A',B' - else
+ @param random random byte source.
+
+
+ Procedure C
+ procedure generates the a value from the given p,q,
+ returning the a value.
+
+
+ which generates the p , q and a values from the given parameters,
+ returning the Gost3410Parameters object.
+
+
+ KFD2 generator for derived keys and ivs as defined by IEEE P1363a/ISO 18033
+
+ This implementation is based on IEEE P1363/ISO 18033.
+
+
+ Construct a KDF1 byte generator.
+
+ @param digest the digest to be used as the source of derived keys.
+
+
+ KDF2 generator for derived keys and ivs as defined by IEEE P1363a/ISO 18033
+
+ This implementation is based on IEEE P1363/ISO 18033.
+
+
+ Construct a KDF2 bytes generator. Generates key material
+ according to IEEE P1363 or ISO 18033 depending on the initialisation.
+
+ @param digest the digest to be used as the source of derived keys.
+
+
+ Generator for MGF1 as defined in Pkcs 1v2
+
+
+ @param digest the digest to be used as the source of Generated bytes
+
+
+ int to octet string.
+
+
+ fill len bytes of the output buffer with bytes Generated from
+ the derivation function.
+
+ @throws DataLengthException if the out buffer is too small.
+
+
+ return the underlying digest.
+
+
+ Key generation parameters for NaccacheStern cipher. For details on this cipher, please see
+
+ http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
+
+
+ Generates a permuted ArrayList from the original one. The original List
+ is not modified
+
+ @param arr
+ the ArrayList to be permuted
+ @param rand
+ the source of Randomness for permutation
+ @return a new ArrayList with the permuted elements.
+
+
+ Finds the first 'count' primes starting with 3
+
+ @param count
+ the number of primes to find
+ @return a vector containing the found primes as Integer
+
+
+ Generator for PBE derived keys and ivs as usd by OpenSSL.
+
+ The scheme is a simple extension of PKCS 5 V2.0 Scheme 1 using MD5 with an
+ iteration count of 1.
+
+
+
+ super class for all Password Based Encyrption (Pbe) parameter generator classes.
+
+
+ base constructor.
+
+
+ initialise the Pbe generator.
+
+ @param password the password converted into bytes (see below).
+ @param salt the salt to be mixed with the password.
+ @param iterationCount the number of iterations the "mixing" function
+ is to be applied for.
+
+
+ return the password byte array.
+
+ @return the password byte array.
+
+
+ return the salt byte array.
+
+ @return the salt byte array.
+
+
+ Generate derived parameters for a key of length keySize.
+
+ @param keySize the length, in bits, of the key required.
+ @return a parameters object representing a key.
+
+
+ Generate derived parameters for a key of length keySize, and
+ an initialisation vector (IV) of length ivSize.
+
+ @param keySize the length, in bits, of the key required.
+ @param ivSize the length, in bits, of the iv required.
+ @return a parameters object representing a key and an IV.
+
+
+ Generate derived parameters for a key of length keySize, specifically
+ for use with a MAC.
+
+ @param keySize the length, in bits, of the key required.
+ @return a parameters object representing a key.
+
+
+ converts a password to a byte array according to the scheme in
+ Pkcs5 (ascii, no padding)
+
+ @param password a character array representing the password.
+ @return a byte array representing the password.
+
+
+ converts a password to a byte array according to the scheme in
+ PKCS5 (UTF-8, no padding)
+
+ @param password a character array representing the password.
+ @return a byte array representing the password.
+
+
+ converts a password to a byte array according to the scheme in
+ Pkcs12 (unicode, big endian, 2 zero pad bytes at the end).
+
+ @param password a character array representing the password.
+ @return a byte array representing the password.
+
+
+ return the iteration count.
+
+ @return the iteration count.
+
+
+ Construct a OpenSSL Parameters generator.
+
+
+ Initialise - note the iteration count for this algorithm is fixed at 1.
+
+ @param password password to use.
+ @param salt salt to use.
+
+
+ the derived key function, the ith hash of the password and the salt.
+
+
+ Generate a key parameter derived from the password, salt, and iteration
+ count we are currently initialised with.
+
+ @param keySize the size of the key we want (in bits)
+ @return a KeyParameter object.
+ @exception ArgumentException if the key length larger than the base hash size.
+
+
+ Generate a key with initialisation vector parameter derived from
+ the password, salt, and iteration count we are currently initialised
+ with.
+
+ @param keySize the size of the key we want (in bits)
+ @param ivSize the size of the iv we want (in bits)
+ @return a ParametersWithIV object.
+ @exception ArgumentException if keySize + ivSize is larger than the base hash size.
+
+
+ Generate a key parameter for use with a MAC derived from the password,
+ salt, and iteration count we are currently initialised with.
+
+ @param keySize the size of the key we want (in bits)
+ @return a KeyParameter object.
+ @exception ArgumentException if the key length larger than the base hash size.
+
+
+ Generator for Pbe derived keys and ivs as defined by Pkcs 12 V1.0.
+
+ The document this implementation is based on can be found at
+
+ RSA's Pkcs12 Page
+
+
+
+ Construct a Pkcs 12 Parameters generator.
+
+ @param digest the digest to be used as the source of derived keys.
+ @exception ArgumentException if an unknown digest is passed in.
+
+
+ add a + b + 1, returning the result in a. The a value is treated
+ as a BigInteger of length (b.Length * 8) bits. The result is
+ modulo 2^b.Length in case of overflow.
+
+
+ generation of a derived key ala Pkcs12 V1.0.
+
+
+ Generate a key parameter derived from the password, salt, and iteration
+ count we are currently initialised with.
+
+ @param keySize the size of the key we want (in bits)
+ @return a KeyParameter object.
+
+
+ Generate a key with initialisation vector parameter derived from
+ the password, salt, and iteration count we are currently initialised
+ with.
+
+ @param keySize the size of the key we want (in bits)
+ @param ivSize the size of the iv we want (in bits)
+ @return a ParametersWithIV object.
+
+
+ Generate a key parameter for use with a MAC derived from the password,
+ salt, and iteration count we are currently initialised with.
+
+ @param keySize the size of the key we want (in bits)
+ @return a KeyParameter object.
+
+
+ Generator for Pbe derived keys and ivs as defined by Pkcs 5 V2.0 Scheme 1.
+ Note this generator is limited to the size of the hash produced by the
+ digest used to drive it.
+
+ The document this implementation is based on can be found at
+
+ RSA's Pkcs5 Page
+
+
+
+ Construct a Pkcs 5 Scheme 1 Parameters generator.
+
+ @param digest the digest to be used as the source of derived keys.
+
+
+ the derived key function, the ith hash of the mPassword and the mSalt.
+
+
+ Generate a key parameter derived from the mPassword, mSalt, and iteration
+ count we are currently initialised with.
+
+ @param keySize the size of the key we want (in bits)
+ @return a KeyParameter object.
+ @exception ArgumentException if the key length larger than the base hash size.
+
+
+ Generate a key with initialisation vector parameter derived from
+ the mPassword, mSalt, and iteration count we are currently initialised
+ with.
+
+ @param keySize the size of the key we want (in bits)
+ @param ivSize the size of the iv we want (in bits)
+ @return a ParametersWithIV object.
+ @exception ArgumentException if keySize + ivSize is larger than the base hash size.
+
+
+ Generate a key parameter for use with a MAC derived from the mPassword,
+ mSalt, and iteration count we are currently initialised with.
+
+ @param keySize the size of the key we want (in bits)
+ @return a KeyParameter object.
+ @exception ArgumentException if the key length larger than the base hash size.
+
+
+ Generator for Pbe derived keys and ivs as defined by Pkcs 5 V2.0 Scheme 2.
+ This generator uses a SHA-1 HMac as the calculation function.
+
+ The document this implementation is based on can be found at
+
+ RSA's Pkcs5 Page
+
+
+ construct a Pkcs5 Scheme 2 Parameters generator.
+
+
+ Generate a key parameter derived from the password, salt, and iteration
+ count we are currently initialised with.
+
+ @param keySize the size of the key we want (in bits)
+ @return a KeyParameter object.
+
+
+ Generate a key with initialisation vector parameter derived from
+ the password, salt, and iteration count we are currently initialised
+ with.
+
+ @param keySize the size of the key we want (in bits)
+ @param ivSize the size of the iv we want (in bits)
+ @return a ParametersWithIV object.
+
+
+ Generate a key parameter for use with a MAC derived from the password,
+ salt, and iteration count we are currently initialised with.
+
+ @param keySize the size of the key we want (in bits)
+ @return a KeyParameter object.
+
+
+ Generate a random factor suitable for use with RSA blind signatures
+ as outlined in Chaum's blinding and unblinding as outlined in
+ "Handbook of Applied Cryptography", page 475.
+
+
+ Initialise the factor generator
+
+ @param param the necessary RSA key parameters.
+
+
+ Generate a suitable blind factor for the public key the generator was initialised with.
+
+ @return a random blind factor
+
+
+ an RSA key pair generator.
+
+
+ interface for classes implementing the Digital Signature Algorithm
+
+
+ initialise the signer for signature generation or signature
+ verification.
+
+ @param forSigning true if we are generating a signature, false
+ otherwise.
+ @param param key parameters for signature generation.
+
+
+ sign the passed in message (usually the output of a hash function).
+
+ @param message the message to be signed.
+ @return two big integers representing the r and s values respectively.
+
+
+ verify the message message against the signature values r and s.
+
+ @param message the message that was supposed to have been signed.
+ @param r the r signature value.
+ @param s the s signature value.
+
+
+ The base interface for implementations of message authentication codes (MACs).
+
+
+ Initialise the MAC.
+
+ @param param the key and other data required by the MAC.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ Return the block size for this MAC (in bytes).
+
+ @return the block size for this MAC in bytes.
+
+
+ add a single byte to the mac for processing.
+
+ @param in the byte to be processed.
+ @exception InvalidOperationException if the MAC is not initialised.
+
+
+ @param in the array containing the input.
+ @param inOff the index in the array the data begins at.
+ @param len the length of the input starting at inOff.
+ @exception InvalidOperationException if the MAC is not initialised.
+ @exception DataLengthException if there isn't enough data in in.
+
+
+ Compute the final stage of the MAC writing the output to the out
+ parameter.
+
+ doFinal leaves the MAC in the same state it was after the last init.
+
+ @param out the array the MAC is to be output to.
+ @param outOff the offset into the out buffer the output is to start at.
+ @exception DataLengthException if there isn't enough space in out.
+ @exception InvalidOperationException if the MAC is not initialised.
+
+
+ Reset the MAC. At the end of resetting the MAC should be in the
+ in the same state it was after the last init (if there was one).
+
+
+ Return the name of the algorithm the MAC implements.
+
+ @return the name of the algorithm the MAC implements.
+
+
+ this exception is thrown whenever we find something we don't expect in a
+ message.
+
+
+ base constructor.
+
+
+ create a InvalidCipherTextException with the given message.
+
+ @param message the message to be carried with the exception.
+
+
+ Initialise the signer for signing or verification.
+
+ @param forSigning true if for signing, false otherwise
+ @param param necessary parameters.
+
+
+ update the internal digest with the byte b
+
+
+ update the internal digest with the byte array in
+
+
+ Generate a signature for the message we've been loaded with using
+ the key we were initialised with.
+
+
+ return true if the internal state represents the signature described
+ in the passed in array.
+
+
+ reset the internal state
+
+
+ Return the name of the algorithm the signer implements.
+
+ @return the name of the algorithm the signer implements.
+
+
+ Signer with message recovery.
+
+
+ Returns true if the signer has recovered the full message as
+ part of signature verification.
+
+ @return true if full message recovered.
+
+
+ Returns a reference to what message was recovered (if any).
+
+ @return full/partial message, null if nothing.
+
+
+ Perform an update with the recovered message before adding any other data. This must
+ be the first update method called, and calling it will result in the signer assuming
+ that further calls to update will include message content past what is recoverable.
+
+ @param signature the signature that we are in the process of verifying.
+ @throws IllegalStateException
+
+
+ The base class for parameters to key generators.
+
+
+ initialise the generator with a source of randomness
+ and a strength (in bits).
+
+ @param random the random byte source.
+ @param strength the size, in bits, of the keys we want to produce.
+
+
+ return the random source associated with this
+ generator.
+
+ @return the generators random source.
+
+
+ return the bit strength for keys produced by this generator,
+
+ @return the strength of the keys this generator produces (in bits).
+
+
+ standard CBC Block Cipher MAC - if no padding is specified the default of
+ pad of zeroes is used.
+
+
+ create a standard MAC based on a CBC block cipher. This will produce an
+ authentication code half the length of the block size of the cipher.
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+
+
+ create a standard MAC based on a CBC block cipher. This will produce an
+ authentication code half the length of the block size of the cipher.
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param padding the padding to be used to complete the last block.
+
+
+ create a standard MAC based on a block cipher with the size of the
+ MAC been given in bits. This class uses CBC mode as the basis for the
+ MAC generation.
+
+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ and in general should be less than the size of the block cipher as it reduces
+ the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
+
+
+ create a standard MAC based on a block cipher with the size of the
+ MAC been given in bits. This class uses CBC mode as the basis for the
+ MAC generation.
+
+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ and in general should be less than the size of the block cipher as it reduces
+ the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
+ @param padding the padding to be used to complete the last block.
+
+
+ Reset the mac generator.
+
+
+ implements a Cipher-FeedBack (CFB) mode on top of a simple cipher.
+
+
+ Basic constructor.
+
+ @param cipher the block cipher to be used as the basis of the
+ feedback mode.
+ @param blockSize the block size in bits (note: a multiple of 8)
+
+
+ Initialise the cipher and, possibly, the initialisation vector (IV).
+ If an IV isn't passed as part of the parameter, the IV will be all zeros.
+ An IV which is too short is handled in FIPS compliant fashion.
+
+ @param param the key and other data required by the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ return the block size we are operating at.
+
+ @return the block size we are operating at (in bytes).
+
+
+ Process one block of input from the array in and write it to
+ the out array.
+
+ @param in the array containing the input data.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the output data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ reset the chaining vector back to the IV and reset the underlying
+ cipher.
+
+
+ return the algorithm name and mode.
+
+ @return the name of the underlying algorithm followed by "/CFB"
+ and the block size in bits.
+
+
+ create a standard MAC based on a CFB block cipher. This will produce an
+ authentication code half the length of the block size of the cipher, with
+ the CFB mode set to 8 bits.
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+
+
+ create a standard MAC based on a CFB block cipher. This will produce an
+ authentication code half the length of the block size of the cipher, with
+ the CFB mode set to 8 bits.
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param padding the padding to be used.
+
+
+ create a standard MAC based on a block cipher with the size of the
+ MAC been given in bits. This class uses CFB mode as the basis for the
+ MAC generation.
+
+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ and in general should be less than the size of the block cipher as it reduces
+ the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param cfbBitSize the size of an output block produced by the CFB mode.
+ @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
+
+
+ create a standard MAC based on a block cipher with the size of the
+ MAC been given in bits. This class uses CFB mode as the basis for the
+ MAC generation.
+
+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ and in general should be less than the size of the block cipher as it reduces
+ the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param cfbBitSize the size of an output block produced by the CFB mode.
+ @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
+ @param padding a padding to be used.
+
+
+ Reset the mac generator.
+
+
+ CMAC - as specified at www.nuee.nagoya-u.ac.jp/labs/tiwata/omac/omac.html
+
+ CMAC is analogous to OMAC1 - see also en.wikipedia.org/wiki/CMAC
+
+ CMAC is a NIST recomendation - see
+ csrc.nist.gov/CryptoToolkit/modes/800-38_Series_Publications/SP800-38B.pdf
+
+ CMAC/OMAC1 is a blockcipher-based message authentication code designed and
+ analyzed by Tetsu Iwata and Kaoru Kurosawa.
+
+ CMAC/OMAC1 is a simple variant of the CBC MAC (Cipher Block Chaining Message
+ Authentication Code). OMAC stands for One-Key CBC MAC.
+
+ It supports 128- or 64-bits block ciphers, with any key size, and returns
+ a MAC with dimension less or equal to the block size of the underlying
+ cipher.
+
+
+
+ create a standard MAC based on a CBC block cipher (64 or 128 bit block).
+ This will produce an authentication code the length of the block size
+ of the cipher.
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+
+
+ create a standard MAC based on a block cipher with the size of the
+ MAC been given in bits.
+
+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ and in general should be less than the size of the block cipher as it reduces
+ the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param macSizeInBits the size of the MAC in bits, must be a multiple of 8 and @lt;= 128.
+
+
+ Reset the mac generator.
+
+
+ implementation of GOST 28147-89 MAC
+
+
+ HMAC implementation based on RFC2104
+
+ H(K XOR opad, H(K XOR ipad, text))
+
+
+ Reset the mac generator.
+
+
+ DES based CBC Block Cipher MAC according to ISO9797, algorithm 3 (ANSI X9.19 Retail MAC)
+
+ This could as well be derived from CBCBlockCipherMac, but then the property mac in the base
+ class must be changed to protected
+
+
+ create a Retail-MAC based on a CBC block cipher. This will produce an
+ authentication code of the length of the block size of the cipher.
+
+ @param cipher the cipher to be used as the basis of the MAC generation. This must
+ be DESEngine.
+
+
+ create a Retail-MAC based on a CBC block cipher. This will produce an
+ authentication code of the length of the block size of the cipher.
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param padding the padding to be used to complete the last block.
+
+
+ create a Retail-MAC based on a block cipher with the size of the
+ MAC been given in bits. This class uses single DES CBC mode as the basis for the
+ MAC generation.
+
+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ and in general should be less than the size of the block cipher as it reduces
+ the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
+
+
+ create a standard MAC based on a block cipher with the size of the
+ MAC been given in bits. This class uses single DES CBC mode as the basis for the
+ MAC generation. The final block is decrypted and then encrypted using the
+ middle and right part of the key.
+
+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ and in general should be less than the size of the block cipher as it reduces
+ the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
+ @param padding the padding to be used to complete the last block.
+
+
+ Reset the mac generator.
+
+
+
+ This exception is thrown whenever a cipher requires a change of key, iv
+ or similar after x amount of bytes enciphered
+
+
+
+ implements Cipher-Block-Chaining (CBC) mode on top of a simple cipher.
+
+
+ Basic constructor.
+
+ @param cipher the block cipher to be used as the basis of chaining.
+
+
+ return the underlying block cipher that we are wrapping.
+
+ @return the underlying block cipher that we are wrapping.
+
+
+ Initialise the cipher and, possibly, the initialisation vector (IV).
+ If an IV isn't passed as part of the parameter, the IV will be all zeros.
+
+ @param forEncryption if true the cipher is initialised for
+ encryption, if false for decryption.
+ @param param the key and other data required by the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ return the block size of the underlying cipher.
+
+ @return the block size of the underlying cipher.
+
+
+ Process one block of input from the array in and write it to
+ the out array.
+
+ @param in the array containing the input data.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the output data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ reset the chaining vector back to the IV and reset the underlying
+ cipher.
+
+
+ Do the appropriate chaining step for CBC mode encryption.
+
+ @param in the array containing the data to be encrypted.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the encrypted data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ Do the appropriate chaining step for CBC mode decryption.
+
+ @param in the array containing the data to be decrypted.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the decrypted data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ return the algorithm name and mode.
+
+ @return the name of the underlying algorithm followed by "/CBC".
+
+
+ * Implements the Counter with Cipher Block Chaining mode (CCM) detailed in
+ * NIST Special Publication 800-38C.
+ *
+ * Note: this mode is a packet mode - it needs all the data up front.
+ *
+
+
+
+ A block cipher mode that includes authenticated encryption with a streaming mode
+ and optional associated data.
+
+
+
+ Initialise the cipher.
+ Parameter can either be an AeadParameters or a ParametersWithIV object.
+ Initialise for encryption if true, for decryption if false.
+ The key or other data required by the cipher.
+
+
+ The block size for this cipher, in bytes.
+
+
+ Encrypt/decrypt a single byte.
+
+ @param input the byte to be processed.
+ @param outBytes the output buffer the processed byte goes into.
+ @param outOff the offset into the output byte array the processed data starts at.
+ @return the number of bytes written to out.
+ @exception DataLengthException if the output buffer is too small.
+
+
+ Process a block of bytes from in putting the result into out.
+
+ @param inBytes the input byte array.
+ @param inOff the offset into the in array where the data to be processed starts.
+ @param len the number of bytes to be processed.
+ @param outBytes the output buffer the processed bytes go into.
+ @param outOff the offset into the output byte array the processed data starts at.
+ @return the number of bytes written to out.
+ @exception DataLengthException if the output buffer is too small.
+
+
+ Finish the operation either appending or verifying the MAC at the end of the data.
+
+ @param outBytes space for any resulting output data.
+ @param outOff offset into out to start copying the data at.
+ @return number of bytes written into out.
+ @throws InvalidOperationException if the cipher is in an inappropriate state.
+ @throws InvalidCipherTextException if the MAC fails to match.
+
+
+ Return the value of the MAC associated with the last stream processed.
+
+ @return MAC for plaintext data.
+
+
+ Return the size of the output buffer required for a ProcessBytes
+ an input of len bytes.
+
+ @param len the length of the input.
+ @return the space required to accommodate a call to ProcessBytes
+ with len bytes of input.
+
+
+ Return the size of the output buffer required for a ProcessBytes plus a
+ DoFinal with an input of len bytes.
+
+ @param len the length of the input.
+ @return the space required to accommodate a call to ProcessBytes and DoFinal
+ with len bytes of input.
+
+
+
+ Reset the cipher to the same state as it was after the last init (if there was one).
+
+
+
+ The name of the algorithm this cipher implements.
+
+
+ Basic constructor.
+
+ @param cipher the block cipher to be used.
+
+
+ return the underlying block cipher that we are wrapping.
+
+ @return the underlying block cipher that we are wrapping.
+
+
+ Returns a byte array containing the mac calculated as part of the
+ last encrypt or decrypt operation.
+
+ @return the last mac calculated.
+
+
+ implements a Cipher-FeedBack (CFB) mode on top of a simple cipher.
+
+
+ Basic constructor.
+
+ @param cipher the block cipher to be used as the basis of the
+ feedback mode.
+ @param blockSize the block size in bits (note: a multiple of 8)
+
+
+ return the underlying block cipher that we are wrapping.
+
+ @return the underlying block cipher that we are wrapping.
+
+
+ Initialise the cipher and, possibly, the initialisation vector (IV).
+ If an IV isn't passed as part of the parameter, the IV will be all zeros.
+ An IV which is too short is handled in FIPS compliant fashion.
+
+ @param forEncryption if true the cipher is initialised for
+ encryption, if false for decryption.
+ @param param the key and other data required by the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ return the block size we are operating at.
+
+ @return the block size we are operating at (in bytes).
+
+
+ Process one block of input from the array in and write it to
+ the out array.
+
+ @param in the array containing the input data.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the output data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ Do the appropriate processing for CFB mode encryption.
+
+ @param in the array containing the data to be encrypted.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the encrypted data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ Do the appropriate processing for CFB mode decryption.
+
+ @param in the array containing the data to be decrypted.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the encrypted data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ reset the chaining vector back to the IV and reset the underlying
+ cipher.
+
+
+ return the algorithm name and mode.
+
+ @return the name of the underlying algorithm followed by "/CFB"
+ and the block size in bits.
+
+
+ A Cipher Text Stealing (CTS) mode cipher. CTS allows block ciphers to
+ be used to produce cipher text which is the same outLength as the plain text.
+
+
+ Create a buffered block cipher that uses Cipher Text Stealing
+
+ @param cipher the underlying block cipher this buffering object wraps.
+
+
+ return the size of the output buffer required for an update of 'length' bytes.
+
+ @param length the outLength of the input.
+ @return the space required to accommodate a call to update
+ with length bytes of input.
+
+
+ return the size of the output buffer required for an update plus a
+ doFinal with an input of length bytes.
+
+ @param length the outLength of the input.
+ @return the space required to accommodate a call to update and doFinal
+ with length bytes of input.
+
+
+ process a single byte, producing an output block if neccessary.
+
+ @param in the input byte.
+ @param out the space for any output that might be produced.
+ @param outOff the offset from which the output will be copied.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there isn't enough space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+
+
+ process an array of bytes, producing output if necessary.
+
+ @param in the input byte array.
+ @param inOff the offset at which the input data starts.
+ @param length the number of bytes to be copied out of the input array.
+ @param out the space for any output that might be produced.
+ @param outOff the offset from which the output will be copied.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there isn't enough space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+
+
+ Process the last block in the buffer.
+
+ @param out the array the block currently being held is copied into.
+ @param outOff the offset at which the copying starts.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there is insufficient space in out for
+ the output.
+ @exception InvalidOperationException if the underlying cipher is not
+ initialised.
+ @exception InvalidCipherTextException if cipher text decrypts wrongly (in
+ case the exception will never Get thrown).
+
+
+ A Two-Pass Authenticated-Encryption Scheme Optimized for Simplicity and
+ Efficiency - by M. Bellare, P. Rogaway, D. Wagner.
+
+ http://www.cs.ucdavis.edu/~rogaway/papers/eax.pdf
+
+ EAX is an AEAD scheme based on CTR and OMAC1/CMAC, that uses a single block
+ cipher to encrypt and authenticate data. It's on-line (the length of a
+ message isn't needed to begin processing it), has good performances, it's
+ simple and provably secure (provided the underlying block cipher is secure).
+
+ Of course, this implementations is NOT thread-safe.
+
+
+ Constructor that accepts an instance of a block cipher engine.
+
+ @param cipher the engine to use
+
+
+
+ Implements the Galois/Counter mode (GCM) detailed in
+ NIST Special Publication 800-38D.
+
+
+
+ implements the GOST 28147 OFB counter mode (GCTR).
+
+
+ Basic constructor.
+
+ @param cipher the block cipher to be used as the basis of the
+ counter mode (must have a 64 bit block size).
+
+
+ return the underlying block cipher that we are wrapping.
+
+ @return the underlying block cipher that we are wrapping.
+
+
+ Initialise the cipher and, possibly, the initialisation vector (IV).
+ If an IV isn't passed as part of the parameter, the IV will be all zeros.
+ An IV which is too short is handled in FIPS compliant fashion.
+
+ @param encrypting if true the cipher is initialised for
+ encryption, if false for decryption.
+ @param parameters the key and other data required by the cipher.
+ @exception ArgumentException if the parameters argument is inappropriate.
+
+
+ return the block size we are operating at (in bytes).
+
+ @return the block size we are operating at (in bytes).
+
+
+ Process one block of input from the array in and write it to
+ the out array.
+
+ @param in the array containing the input data.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the output data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ reset the feedback vector back to the IV and reset the underlying
+ cipher.
+
+
+ return the algorithm name and mode.
+
+ @return the name of the underlying algorithm followed by "/GCTR"
+ and the block size in bits
+
+
+ implements a Output-FeedBack (OFB) mode on top of a simple cipher.
+
+
+ Basic constructor.
+
+ @param cipher the block cipher to be used as the basis of the
+ feedback mode.
+ @param blockSize the block size in bits (note: a multiple of 8)
+
+
+ return the underlying block cipher that we are wrapping.
+
+ @return the underlying block cipher that we are wrapping.
+
+
+ Initialise the cipher and, possibly, the initialisation vector (IV).
+ If an IV isn't passed as part of the parameter, the IV will be all zeros.
+ An IV which is too short is handled in FIPS compliant fashion.
+
+ @param forEncryption if true the cipher is initialised for
+ encryption, if false for decryption.
+ @param param the key and other data required by the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ return the block size we are operating at (in bytes).
+
+ @return the block size we are operating at (in bytes).
+
+
+ Process one block of input from the array in and write it to
+ the out array.
+
+ @param in the array containing the input data.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the output data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ reset the feedback vector back to the IV and reset the underlying
+ cipher.
+
+
+ return the algorithm name and mode.
+
+ @return the name of the underlying algorithm followed by "/OFB"
+ and the block size in bits
+
+
+ * Implements OpenPGP's rather strange version of Cipher-FeedBack (CFB) mode
+ * on top of a simple cipher. This class assumes the IV has been prepended
+ * to the data stream already, and just accomodates the reset after
+ * (blockSize + 2) bytes have been read.
+ *
+
+
+ Basic constructor.
+
+ @param cipher the block cipher to be used as the basis of the
+ feedback mode.
+
+
+ return the underlying block cipher that we are wrapping.
+
+ @return the underlying block cipher that we are wrapping.
+
+
+ return the block size we are operating at.
+
+ @return the block size we are operating at (in bytes).
+
+
+ Process one block of input from the array in and write it to
+ the out array.
+
+ @param in the array containing the input data.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the output data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ reset the chaining vector back to the IV and reset the underlying
+ cipher.
+
+
+ Initialise the cipher and, possibly, the initialisation vector (IV).
+ If an IV isn't passed as part of the parameter, the IV will be all zeros.
+ An IV which is too short is handled in FIPS compliant fashion.
+
+ @param forEncryption if true the cipher is initialised for
+ encryption, if false for decryption.
+ @param parameters the key and other data required by the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ Encrypt one byte of data according to CFB mode.
+ @param data the byte to encrypt
+ @param blockOff offset in the current block
+ @returns the encrypted byte
+
+
+ Do the appropriate processing for CFB IV mode encryption.
+
+ @param in the array containing the data to be encrypted.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the encrypted data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ Do the appropriate processing for CFB IV mode decryption.
+
+ @param in the array containing the data to be decrypted.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the encrypted data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ return the algorithm name and mode.
+
+ @return the name of the underlying algorithm followed by "/PGPCFB"
+ and the block size in bits.
+
+
+ Implements the Segmented Integer Counter (SIC) mode on top of a simple
+ block cipher.
+
+
+ Basic constructor.
+
+ @param c the block cipher to be used.
+
+
+ return the underlying block cipher that we are wrapping.
+
+ @return the underlying block cipher that we are wrapping.
+
+
+ Block cipher padders are expected to conform to this interface
+
+
+ Initialise the padder.
+
+ @param param parameters, if any required.
+
+
+ add the pad bytes to the passed in block, returning the
+ number of bytes added.
+
+
+ return the number of pad bytes present in the block.
+ @exception InvalidCipherTextException if the padding is badly formed
+ or invalid.
+
+
+ Return the name of the algorithm the cipher implements.
+
+ @return the name of the algorithm the cipher implements.
+
+
+ A padder that adds ISO10126-2 padding to a block.
+
+
+ Initialise the padder.
+
+ @param random a SecureRandom if available.
+
+
+ add the pad bytes to the passed in block, returning the
+ number of bytes added.
+
+
+ return the number of pad bytes present in the block.
+
+
+ Return the name of the algorithm the cipher implements.
+
+ @return the name of the algorithm the cipher implements.
+
+
+ A padder that adds the padding according to the scheme referenced in
+ ISO 7814-4 - scheme 2 from ISO 9797-1. The first byte is 0x80, rest is 0x00
+
+
+ Initialise the padder.
+
+ @param random - a SecureRandom if available.
+
+
+ add the pad bytes to the passed in block, returning the
+ number of bytes added.
+
+
+ return the number of pad bytes present in the block.
+
+
+ Return the name of the algorithm the padder implements.
+
+ @return the name of the algorithm the padder implements.
+
+
+ A wrapper class that allows block ciphers to be used to process data in
+ a piecemeal fashion with padding. The PaddedBufferedBlockCipher
+ outputs a block only when the buffer is full and more data is being added,
+ or on a doFinal (unless the current block in the buffer is a pad block).
+ The default padding mechanism used is the one outlined in Pkcs5/Pkcs7.
+
+
+ Create a buffered block cipher with the desired padding.
+
+ @param cipher the underlying block cipher this buffering object wraps.
+ @param padding the padding type.
+
+
+ Create a buffered block cipher Pkcs7 padding
+
+ @param cipher the underlying block cipher this buffering object wraps.
+
+
+ initialise the cipher.
+
+ @param forEncryption if true the cipher is initialised for
+ encryption, if false for decryption.
+ @param param the key and other data required by the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ return the minimum size of the output buffer required for an update
+ plus a doFinal with an input of len bytes.
+
+ @param len the length of the input.
+ @return the space required to accommodate a call to update and doFinal
+ with len bytes of input.
+
+
+ return the size of the output buffer required for an update
+ an input of len bytes.
+
+ @param len the length of the input.
+ @return the space required to accommodate a call to update
+ with len bytes of input.
+
+
+ process a single byte, producing an output block if neccessary.
+
+ @param in the input byte.
+ @param out the space for any output that might be produced.
+ @param outOff the offset from which the output will be copied.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there isn't enough space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+
+
+ process an array of bytes, producing output if necessary.
+
+ @param in the input byte array.
+ @param inOff the offset at which the input data starts.
+ @param len the number of bytes to be copied out of the input array.
+ @param out the space for any output that might be produced.
+ @param outOff the offset from which the output will be copied.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there isn't enough space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+
+
+ Process the last block in the buffer. If the buffer is currently
+ full and padding needs to be added a call to doFinal will produce
+ 2 * GetBlockSize() bytes.
+
+ @param out the array the block currently being held is copied into.
+ @param outOff the offset at which the copying starts.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there is insufficient space in out for
+ the output or we are decrypting and the input is not block size aligned.
+ @exception InvalidOperationException if the underlying cipher is not
+ initialised.
+ @exception InvalidCipherTextException if padding is expected and not found.
+
+
+ A padder that adds Pkcs7/Pkcs5 padding to a block.
+
+
+ Initialise the padder.
+
+ @param random - a SecureRandom if available.
+
+
+ add the pad bytes to the passed in block, returning the
+ number of bytes added.
+
+
+ return the number of pad bytes present in the block.
+
+
+ Return the name of the algorithm the cipher implements.
+
+ @return the name of the algorithm the cipher implements.
+
+
+ A padder that adds Trailing-Bit-Compliment padding to a block.
+
+ This padding pads the block out compliment of the last bit
+ of the plain text.
+
+
+
+
+ Initialise the padder.
+ - a SecureRandom if available.
+
+
+
+ add the pad bytes to the passed in block, returning the
+ number of bytes added.
+
+ Note: this assumes that the last block of plain text is always
+ passed to it inside in. i.e. if inOff is zero, indicating the
+ entire block is to be overwritten with padding the value of in
+ should be the same as the last block of plain text.
+
+
+
+
+ return the number of pad bytes present in the block.
+
+
+ Return the name of the algorithm the cipher implements.
+ the name of the algorithm the cipher implements.
+
+
+
+ A padder that adds X9.23 padding to a block - if a SecureRandom is
+ passed in random padding is assumed, otherwise padding with zeros is used.
+
+
+ Initialise the padder.
+
+ @param random a SecureRandom if one is available.
+
+
+ add the pad bytes to the passed in block, returning the
+ number of bytes added.
+
+
+ return the number of pad bytes present in the block.
+
+
+ Return the name of the algorithm the cipher implements.
+
+ @return the name of the algorithm the cipher implements.
+
+
+ A padder that adds Null byte padding to a block.
+
+
+ Initialise the padder.
+
+
+ - a SecureRandom if available.
+
+
+
+ add the pad bytes to the passed in block, returning the
+ number of bytes added.
+
+
+
+ return the number of pad bytes present in the block.
+
+
+ Return the name of the algorithm the cipher implements.
+
+
+ the name of the algorithm the cipher implements.
+
+
+
+ Base constructor.
+
+ @param key key to be used by underlying cipher
+ @param macSize macSize in bits
+ @param nonce nonce to be used
+ @param associatedText associated text, if any
+
+
+ Base constructor.
+
+ @param key key to be used by underlying cipher
+ @param macSize macSize in bits
+ @param nonce nonce to be used
+ @param associatedText associated text, if any
+
+
+ DES has 16 weak keys. This method will check
+ if the given DES key material is weak or semi-weak.
+ Key material that is too short is regarded as weak.
+
+ @return true if the given DES key material is weak or semi-weak,
+ false otherwise.
+
+
+ DES Keys use the LSB as the odd parity bit. This can
+ be used to check for corrupt keys.
+
+ @param bytes the byte array to set the parity on.
+
+
+ return true if the passed in key is a DES-EDE weak key.
+
+ @param key bytes making up the key
+ @param offset offset into the byte array the key starts at
+ @param length number of bytes making up the key
+
+
+ return true if the passed in key is a DES-EDE weak key.
+
+ @param key bytes making up the key
+ @param offset offset into the byte array the key starts at
+
+
+ The minimum bitlength of the private value.
+
+
+ The bitlength of the private value.
+
+
+ return the generator - g
+
+
+ return private value limit - l
+
+
+ parameters for using an integrated cipher in stream mode.
+
+
+ @param derivation the derivation parameter for the KDF function.
+ @param encoding the encoding parameter for the KDF function.
+ @param macKeySize the size of the MAC key (in bits).
+
+
+ @param derivation the derivation parameter for the KDF function.
+ @param encoding the encoding parameter for the KDF function.
+ @param macKeySize the size of the MAC key (in bits).
+ @param cipherKeySize the size of the associated Cipher key (in bits).
+
+
+ parameters for Key derivation functions for ISO-18033
+
+
+ parameters for Key derivation functions for IEEE P1363a
+
+
+ Parameters for mask derivation functions.
+
+
+ Parameters for NaccacheStern public private key generation. For details on
+ this cipher, please see
+
+ http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
+
+
+ Parameters for generating a NaccacheStern KeyPair.
+
+ @param random
+ The source of randomness
+ @param strength
+ The desired strength of the Key in Bits
+ @param certainty
+ the probability that the generated primes are not really prime
+ as integer: 2^(-certainty) is then the probability
+ @param countSmallPrimes
+ How many small key factors are desired
+
+
+ Parameters for a NaccacheStern KeyPair.
+
+ @param random
+ The source of randomness
+ @param strength
+ The desired strength of the Key in Bits
+ @param certainty
+ the probability that the generated primes are not really prime
+ as integer: 2^(-certainty) is then the probability
+ @param cntSmallPrimes
+ How many small key factors are desired
+ @param debug
+ Turn debugging on or off (reveals secret information, use with
+ caution)
+
+
+ @return Returns the certainty.
+
+
+ @return Returns the countSmallPrimes.
+
+
+ Public key parameters for NaccacheStern cipher. For details on this cipher,
+ please see
+
+ http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
+
+
+ @param privateKey
+
+
+ @return Returns the g.
+
+
+ @return Returns the lowerSigmaBound.
+
+
+ @return Returns the n.
+
+
+ Private key parameters for NaccacheStern cipher. For details on this cipher,
+ please see
+
+ http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
+
+
+ Constructs a NaccacheSternPrivateKey
+
+ @param g
+ the public enryption parameter g
+ @param n
+ the public modulus n = p*q
+ @param lowerSigmaBound
+ the public lower sigma bound up to which data can be encrypted
+ @param smallPrimes
+ the small primes, of which sigma is constructed in the right
+ order
+ @param phi_n
+ the private modulus phi(n) = (p-1)(q-1)
+
+
+ Cipher parameters with a fixed salt value associated with them.
+
+
+ Random generation based on the digest with counter. Calling AddSeedMaterial will
+ always increase the entropy of the hash.
+
+ Internal access to the digest is synchronized so a single one of these can be shared.
+
+
+
+ Generic interface for objects generating random bytes.
+
+
+ Add more seed material to the generator.
+ A byte array to be mixed into the generator's state.
+
+
+ Add more seed material to the generator.
+ A long value to be mixed into the generator's state.
+
+
+ Fill byte array with random values.
+ Array to be filled.
+
+
+ Fill byte array with random values.
+ Array to receive bytes.
+ Index to start filling at.
+ Length of segment to fill.
+
+
+
+ Takes bytes generated by an underling RandomGenerator and reverses the order in
+ each small window (of configurable size).
+
+ Access to internals is synchronized so a single one of these can be shared.
+
+
+
+
+ Add more seed material to the generator.
+ A byte array to be mixed into the generator's state.
+
+
+ Add more seed material to the generator.
+ A long value to be mixed into the generator's state.
+
+
+ Fill byte array with random values.
+ Array to be filled.
+
+
+ Fill byte array with random values.
+ Array to receive bytes.
+ Index to start filling at.
+ Length of segment to fill.
+
+
+ A thread based seed generator - one source of randomness.
+
+ Based on an idea from Marcus Lippert.
+
+
+
+ Generate seed bytes. Set fast to false for best quality.
+
+ If fast is set to true, the code should be round about 8 times faster when
+ generating a long sequence of random bytes. 20 bytes of random values using
+ the fast mode take less than half a second on a Nokia e70. If fast is set to false,
+ it takes round about 2500 ms.
+
+ @param numBytes the number of bytes to generate
+ @param fast true if fast mode should be used
+
+
+
+ Permutation generated by code:
+
+ // First 1850 fractional digit of Pi number.
+ byte[] key = new BigInteger("14159265358979323846...5068006422512520511").ToByteArray();
+ s = 0;
+ P = new byte[256];
+ for (int i = 0; i < 256; i++)
+ {
+ P[i] = (byte) i;
+ }
+ for (int m = 0; m < 768; m++)
+ {
+ s = P[(s + P[m & 0xff] + key[m % key.length]) & 0xff];
+ byte temp = P[m & 0xff];
+ P[m & 0xff] = P[s & 0xff];
+ P[s & 0xff] = temp;
+ }
+
+
+
+ Value generated in the same way as P.
+
+
+ update the internal digest with the byte b
+
+
+ update the internal digest with the byte array in
+
+
+ Generate a signature for the message we've been loaded with using
+ the key we were initialised with.
+
+
+ true if the internal state represents the signature described in the passed in array.
+
+
+ Reset the internal state
+
+
+ The Digital Signature Algorithm - as described in "Handbook of Applied
+ Cryptography", pages 452 - 453.
+
+
+ Generate a signature for the given message using the key we were
+ initialised with. For conventional DSA the message should be a SHA-1
+ hash of the message of interest.
+
+ @param message the message that will be verified later.
+
+
+ return true if the value r and s represent a DSA signature for
+ the passed in message for standard DSA the message should be a
+ SHA-1 hash of the real message to be verified.
+
+
+ EC-DSA as described in X9.62
+
+
+ Generate a signature for the given message using the key we were
+ initialised with. For conventional DSA the message should be a SHA-1
+ hash of the message of interest.
+
+ @param message the message that will be verified later.
+
+
+ return true if the value r and s represent a DSA signature for
+ the passed in message (for standard DSA the message should be
+ a SHA-1 hash of the real message to be verified).
+
+
+ GOST R 34.10-2001 Signature Algorithm
+
+
+ generate a signature for the given message using the key we were
+ initialised with. For conventional GOST3410 the message should be a GOST3411
+ hash of the message of interest.
+
+ @param message the message that will be verified later.
+
+
+ return true if the value r and s represent a GOST3410 signature for
+ the passed in message (for standard GOST3410 the message should be
+ a GOST3411 hash of the real message to be verified).
+
+
+ EC-NR as described in IEEE 1363-2000
+
+
+ generate a signature for the given message using the key we were
+ initialised with. Generally, the order of the curve should be at
+ least as long as the hash of the message of interest, and with
+ ECNR it *must* be at least as long.
+
+ @param digest the digest to be signed.
+ @exception DataLengthException if the digest is longer than the key allows
+
+
+ return true if the value r and s represent a signature for the
+ message passed in. Generally, the order of the curve should be at
+ least as long as the hash of the message of interest, and with
+ ECNR, it *must* be at least as long. But just in case the signer
+ applied mod(n) to the longer digest, this implementation will
+ apply mod(n) during verification.
+
+ @param digest the digest to be verified.
+ @param r the r value of the signature.
+ @param s the s value of the signature.
+ @exception DataLengthException if the digest is longer than the key allows
+
+
+ initialise the signer for signing or verification.
+
+ @param forSigning
+ true if for signing, false otherwise
+ @param parameters
+ necessary parameters.
+
+
+ update the internal digest with the byte b
+
+
+ update the internal digest with the byte array in
+
+
+ Generate a signature for the message we've been loaded with using the key
+ we were initialised with.
+
+
+ return true if the internal state represents the signature described in
+ the passed in array.
+
+
+ update the internal digest with the byte b
+
+
+ update the internal digest with the byte array in
+
+
+ Generate a signature for the message we've been loaded with using
+ the key we were initialised with.
+
+
+ true if the internal state represents the signature described in the passed in array.
+
+
+ Reset the internal state
+
+
+ Gost R 34.10-94 Signature Algorithm
+
+
+ generate a signature for the given message using the key we were
+ initialised with. For conventional Gost3410 the message should be a Gost3411
+ hash of the message of interest.
+
+ @param message the message that will be verified later.
+
+
+ return true if the value r and s represent a Gost3410 signature for
+ the passed in message for standard Gost3410 the message should be a
+ Gost3411 hash of the real message to be verified.
+
+
+ ISO9796-2 - mechanism using a hash function with recovery (scheme 2 and 3).
+
+ Note: the usual length for the salt is the length of the hash
+ function used in bytes.
+
+
+
+
+ Return a reference to the recoveredMessage message.
+
+ The full/partial recoveredMessage message.
+
+
+
+
+ Generate a signer for the with either implicit or explicit trailers
+ for ISO9796-2, scheme 2 or 3.
+
+ base cipher to use for signature creation/verification
+ digest to use.
+ length of salt in bytes.
+ whether or not the trailer is implicit or gives the hash.
+
+
+ Constructor for a signer with an explicit digest trailer.
+
+
+ cipher to use.
+
+ digest to sign with.
+
+ length of salt in bytes.
+
+
+
+ Initialise the signer.
+ true if for signing, false if for verification.
+ parameters for signature generation/verification. If the
+ parameters are for generation they should be a ParametersWithRandom,
+ a ParametersWithSalt, or just an RsaKeyParameters object. If RsaKeyParameters
+ are passed in a SecureRandom will be created.
+
+ if wrong parameter type or a fixed
+ salt is passed in which is the wrong length.
+
+
+
+ compare two byte arrays - constant time.
+
+
+ clear possible sensitive data
+
+
+ update the internal digest with the byte b
+
+
+ update the internal digest with the byte array in
+
+
+ reset the internal state
+
+
+ Generate a signature for the loaded message using the key we were
+ initialised with.
+
+
+
+ return true if the signature represents a ISO9796-2 signature
+ for the passed in message.
+
+
+
+
+ Return true if the full message was recoveredMessage.
+
+ true on full message recovery, false otherwise, or if not sure.
+
+
+
+ int to octet string.
+ int to octet string.
+
+
+ long to octet string.
+
+
+ mask generator function, as described in Pkcs1v2.
+
+
+ ISO9796-2 - mechanism using a hash function with recovery (scheme 1)
+
+
+
+ Return a reference to the recoveredMessage message.
+
+ The full/partial recoveredMessage message.
+
+
+
+
+ Generate a signer for the with either implicit or explicit trailers
+ for ISO9796-2.
+
+ base cipher to use for signature creation/verification
+ digest to use.
+ whether or not the trailer is implicit or gives the hash.
+
+
+ Constructor for a signer with an explicit digest trailer.
+
+
+ cipher to use.
+
+ digest to sign with.
+
+
+
+ compare two byte arrays - constant time.
+
+
+ clear possible sensitive data
+
+
+ update the internal digest with the byte b
+
+
+ update the internal digest with the byte array in
+
+
+ reset the internal state
+
+
+ Generate a signature for the loaded message using the key we were
+ initialised with.
+
+
+
+ return true if the signature represents a ISO9796-2 signature
+ for the passed in message.
+
+
+
+
+ Return true if the full message was recoveredMessage.
+
+ true on full message recovery, false otherwise.
+
+
+
+ RSA-PSS as described in Pkcs# 1 v 2.1.
+
+ Note: the usual value for the salt length is the number of
+ bytes in the hash function.
+
+
+
+ Basic constructor
+ the asymmetric cipher to use.
+ the digest to use.
+ the length of the salt to use (in bytes).
+
+
+ clear possible sensitive data
+
+
+ update the internal digest with the byte b
+
+
+ update the internal digest with the byte array in
+
+
+ reset the internal state
+
+
+ Generate a signature for the message we've been loaded with using
+ the key we were initialised with.
+
+
+
+ return true if the internal state represents the signature described
+ in the passed in array.
+
+
+
+ int to octet string.
+
+
+ mask generator function, as described in Pkcs1v2.
+
+
+
+ Load oid table.
+
+
+
+ Initialise the signer for signing or verification.
+
+ @param forSigning true if for signing, false otherwise
+ @param param necessary parameters.
+
+
+ update the internal digest with the byte b
+
+
+ update the internal digest with the byte array in
+
+
+ Generate a signature for the message we've been loaded with using
+ the key we were initialised with.
+
+
+ return true if the internal state represents the signature described
+ in the passed in array.
+
+
+ a wrapper for block ciphers with a single byte block size, so that they
+ can be treated like stream ciphers.
+
+
+ basic constructor.
+
+ @param cipher the block cipher to be wrapped.
+ @exception ArgumentException if the cipher has a block size other than
+ one.
+
+
+ initialise the underlying cipher.
+
+ @param forEncryption true if we are setting up for encryption, false otherwise.
+ @param param the necessary parameters for the underlying cipher to be initialised.
+
+
+ encrypt/decrypt a single byte returning the result.
+
+ @param in the byte to be processed.
+ @return the result of processing the input byte.
+
+
+ process a block of bytes from in putting the result into out.
+
+ @param in the input byte array.
+ @param inOff the offset into the in array where the data to be processed starts.
+ @param len the number of bytes to be processed.
+ @param out the output buffer the processed bytes go into.
+ @param outOff the offset into the output byte array the processed data stars at.
+ @exception DataLengthException if the output buffer is too small.
+
+
+ reset the underlying cipher. This leaves it in the same state
+ it was at after the last init (if there was one).
+
+
+ return the name of the algorithm we are wrapping.
+
+ @return the name of the algorithm we are wrapping.
+
+
+
+ RFC 2246 7.2
+
+
+
+
+ RFC 2246 7.2
+
+
+
+
+ A certificate verifyer, that will always return true.
+
+ DO NOT USE THIS FILE UNLESS YOU KNOW EXACTLY WHAT YOU ARE DOING.
+
+
+
+
+
+ This should be implemented by any class which can find out, if a given
+ certificate chain is being accepted by an client.
+
+
+
+ The certs, which are part of the chain.
+ True, if the chain is accepted, false otherwise
+
+
+ Return true.
+
+
+
+ A queue for bytes.
+
+ This file could be more optimized.
+
+
+
+
+ The initial size for our buffer.
+
+
+ The smallest number which can be written as 2^x which is bigger than i.
+
+
+ The buffer where we store our data.
+
+
+ How many bytes at the beginning of the buffer are skipped.
+
+
+ How many bytes in the buffer are valid data.
+
+
+ Read data from the buffer.
+ The buffer where the read data will be copied to.
+ How many bytes to skip at the beginning of buf.
+ How many bytes to read at all.
+ How many bytes from our data to skip.
+
+
+ Add some data to our buffer.
+ A byte-array to read data from.
+ How many bytes to skip at the beginning of the array.
+ How many bytes to read from the array.
+
+
+ Remove some bytes from our data from the beginning.
+ How many bytes to remove.
+
+
+ The number of bytes which are available in this buffer.
+
+
+ A representation for a certificate chain.
+
+
+ The certificates.
+
+
+ Parse the ServerCertificate message.
+
+ @param inStr The stream where to parse from.
+ @return A Certificate object with the certs, the server has sended.
+ @throws IOException If something goes wrong during parsing.
+
+
+ Encodes version of the ClientCertificate message
+
+ @param outStr stream to write the message to
+ @throws IOException If something goes wrong
+
+
+ Private constructor from a cert array.
+
+ @param certs The certs the chain should contain.
+
+
+ An array which contains the certs, this chain contains.
+
+
+ A of X509Name
+
+
+
+ RFC 2246 A.5
+
+
+
+
+ RFC 2246 7.4.4
+
+
+
+ A combined hash, which implements md5(m) || sha1(m).
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ RFC 2246 6.1
+
+
+
+
+ RFC 2246 6.2.1
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Called at the start of a new TLS session, before any other methods.
+
+
+ A
+
+
+
+
+ Get the list of cipher suites that this client supports.
+
+
+ An array of , each specifying a supported cipher suite.
+
+
+
+
+ Get the list of compression methods that this client supports.
+
+
+ An array of , each specifying a supported compression method.
+
+
+
+
+ Get the (optional) table of client extensions to be included in (extended) client hello.
+
+
+ A ( -> byte[]). May be null.
+
+
+
+
+
+ Reports the session ID once it has been determined.
+
+
+ A
+
+
+
+
+ Report the cipher suite that was selected by the server.
+
+
+ The protocol handler validates this value against the offered cipher suites
+
+
+
+ A
+
+
+
+
+ Report the compression method that was selected by the server.
+
+
+ The protocol handler validates this value against the offered compression methods
+
+
+
+ A
+
+
+
+
+ Report whether the server supports secure renegotiation
+
+
+ The protocol handler automatically processes the relevant extensions
+
+
+ A , true if the server supports secure renegotiation
+
+
+
+
+
+ Report the extensions from an extended server hello.
+
+
+ Will only be called if we returned a non-null result from .
+
+
+ A ( -> byte[])
+
+
+
+
+ Return an implementation of to negotiate the key exchange
+ part of the protocol.
+
+
+ A
+
+
+
+
+
+ Return an implementation of to handle authentication
+ part of the protocol.
+
+
+
+
+
+ Return an implementation of to handle record compression.
+
+
+
+
+
+ Return an implementation of to use for encryption/decryption.
+
+
+ A
+
+
+
+
+
+
+
+
+ RFC 4492 5.4
+
+
+
+ Indicates the elliptic curve domain parameters are conveyed verbosely, and the
+ underlying finite field is a prime field.
+
+
+ Indicates the elliptic curve domain parameters are conveyed verbosely, and the
+ underlying finite field is a characteristic-2 field.
+
+
+ Indicates that a named curve is used. This option SHOULD be used when applicable.
+
+
+
+ RFC 4492 5.1.2
+
+
+
+
+ RFC 4366 2.3
+
+
+
+
+ RFC 2246 7.4
+
+
+
+
+ A temporary class to wrap old CertificateVerifyer stuff for new TlsAuthentication.
+
+
+
+
+ Called by the protocol handler to report the server certificate.
+
+
+ This method is responsible for certificate verification and validation
+
+ The server received
+
+
+
+
+ Return client credentials in response to server's certificate request
+
+
+ A containing server certificate request details
+
+
+ A to be used for client authentication
+ (or null for no client authentication)
+
+
+
+
+
+ A temporary class to use LegacyTlsAuthentication
+
+
+
+
+ RFC 4492 5.1.1
+ The named curves defined here are those specified in SEC 2 [13]. Note that many of
+ these curves are also recommended in ANSI X9.62 [7] and FIPS 186-2 [11]. Values 0xFE00
+ through 0xFEFF are reserved for private use. Values 0xFF01 and 0xFF02 indicate that the
+ client supports arbitrary prime and characteristic-2 curves, respectively (the curve
+ parameters must be encoded explicitly in ECParameters).
+
+
+
+ An implementation of the TLS 1.0 record layer.
+
+
+ HMAC implementation based on original internet draft for HMAC (RFC 2104)
+
+ The difference is that padding is concatentated versus XORed with the key
+
+ H(K + opad, H(K + ipad, text))
+
+
+ Base constructor for one of the standard digest algorithms that the byteLength of
+ the algorithm is know for. Behaviour is undefined for digests other than MD5 or SHA1.
+
+ @param digest the digest.
+
+
+ Reset the mac generator.
+
+
+
+ A generic TLS 1.0 block cipher. This can be used for AES or 3DES for example.
+
+
+
+
+
+
+
+
+
+
+ TLS 1.0 DH key exchange.
+
+
+
+
+ A generic interface for key exchange implementations in TLS 1.0.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ECDHE key exchange (see RFC 4492)
+
+
+ ECDH key exchange (see RFC 4492)
+
+
+
+ A generic TLS MAC implementation, which can be used with any kind of
+ IDigest to act as an HMAC.
+
+
+
+ Generate a new instance of an TlsMac.
+
+ @param digest The digest to use.
+ @param key_block A byte-array where the key for this mac is located.
+ @param offset The number of bytes to skip, before the key starts in the buffer.
+ @param len The length of the key.
+
+
+ @return the MAC write secret
+
+
+ Increment the current write sequence number
+
+
+ Calculate the mac for some given data.
+
+ TlsMac will keep track of the sequence number internally.
+
+ @param type The message type of the message.
+ @param message A byte-buffer containing the message.
+ @param offset The number of bytes to skip, before the message starts.
+ @param len The length of the message.
+ @return A new byte-buffer containing the mac value.
+
+
+ @return the current write sequence number
+
+
+ @return The Keysize of the mac.
+
+
+
+ A NULL cipher suite, for use during handshake.
+
+
+
+ An implementation of all high level protocols in TLS 1.0.
+
+
+ Both streams can be the same object
+
+
+ Both streams can be the same object
+
+
+ This method is called, when a change cipher spec message is received.
+
+ @throws IOException If the message has an invalid content or the
+ handshake is not in the correct state.
+
+
+ Connects to the remote system.
+ Will be used when a certificate is received to verify
+ that this certificate is accepted by the client.
+ If handshake was not successful
+
+
+ Read data from the network. The method will return immediately, if there is
+ still some data left in the buffer, or block until some application
+ data has been read from the network.
+
+ @param buf The buffer where the data will be copied to.
+ @param offset The position where the data will be placed in the buffer.
+ @param len The maximum number of bytes to read.
+ @return The number of bytes read.
+ @throws IOException If something goes wrong during reading data.
+
+
+ Send some application data to the remote system.
+
+ The method will handle fragmentation internally.
+
+ @param buf The buffer with the data.
+ @param offset The position in the buffer where the data is placed.
+ @param len The length of the data.
+ @throws IOException If something goes wrong during sending.
+
+
+ Terminate this connection with an alert.
+
+ Can be used for normal closure too.
+
+ @param alertLevel The level of the alert, an be AlertLevel.fatal or AL_warning.
+ @param alertDescription The exact alert message.
+ @throws IOException If alert was fatal.
+
+
+ Closes this connection
+ If something goes wrong during closing.
+
+
+ Make sure the Stream is now empty. Fail otherwise.
+
+ @param is The Stream to check.
+ @throws IOException If is is not empty.
+
+
+ A Stream which can be used to send data.
+
+
+ A Stream which can be used to read data.
+
+
+ The secure bidirectional stream for this connection
+
+
+
+ TLS 1.0 RSA key exchange.
+
+
+
+
+ TLS 1.1 SRP key exchange.
+
+
+
+ Some helper fuctions for MicroTLS.
+
+
+ return a = a + b - b preserved.
+
+
+ unsigned comparison on two arrays - note the arrays may
+ start with leading zeros.
+
+
+ return z = x / y - done in place (z value preserved, x contains the
+ remainder)
+
+
+ return whether or not a BigInteger is probably prime with a
+ probability of 1 - (1/2)**certainty.
+
From Knuth Vol 2, pg 395.
+
+
+ Calculate the numbers u1, u2, and u3 such that:
+
+ u1 * a + u2 * b = u3
+
+ where u3 is the greatest common divider of a and b.
+ a and b using the extended Euclid algorithm (refer p. 323
+ of The Art of Computer Programming vol 2, 2nd ed).
+ This also seems to have the side effect of calculating
+ some form of multiplicative inverse.
+
+ @param a First number to calculate gcd for
+ @param b Second number to calculate gcd for
+ @param u1Out the return object for the u1 value
+ @param u2Out the return object for the u2 value
+ @return The greatest common divisor of a and b
+
+
+ return w with w = x * x - w is assumed to have enough space.
+
+
+ return x with x = y * z - x is assumed to have enough space.
+
+
+ Calculate mQuote = -m^(-1) mod b with b = 2^32 (32 = word size)
+
+
+ Montgomery multiplication: a = x * y * R^(-1) mod m
+
+ Based algorithm 14.36 of Handbook of Applied Cryptography.
+
+
m, x, y should have length n
+
a should have length (n + 1)
+
b = 2^32, R = b^n
+
+ The result is put in x
+
+ NOTE: the indices of x, y, m, a different in HAC and in Java
+
+
+ return x = x % y - done in place (y value preserved)
+
+
+ do a left shift - this returns a new array.
+
+
+ do a right shift - this does it in place.
+
+
+ do a right shift by one - this does it in place.
+
+
+ returns x = x - y - we assume x is >= y
+
+
+ Class representing a simple version of a big decimal. A
+ SimpleBigDecimal is basically a
+ {@link java.math.BigInteger BigInteger} with a few digits on the right of
+ the decimal point. The number of (binary) digits on the right of the decimal
+ point is called the scale of the SimpleBigDecimal.
+ Unlike in {@link java.math.BigDecimal BigDecimal}, the scale is not adjusted
+ automatically, but must be set manually. All SimpleBigDecimals
+ taking part in the same arithmetic operation must have equal scale. The
+ result of a multiplication of two SimpleBigDecimals returns a
+ SimpleBigDecimal with double scale.
+
+
+ Returns a SimpleBigDecimal representing the same numerical
+ value as value.
+ @param value The value of the SimpleBigDecimal to be
+ created.
+ @param scale The scale of the SimpleBigDecimal to be
+ created.
+ @return The such created SimpleBigDecimal.
+
+
+ Constructor for SimpleBigDecimal. The value of the
+ constructed SimpleBigDecimal Equals bigInt /
+ 2scale.
+ @param bigInt The bigInt value parameter.
+ @param scale The scale of the constructed SimpleBigDecimal.
+
+
+ Class holding methods for point multiplication based on the window
+ τ-adic nonadjacent form (WTNAF). The algorithms are based on the
+ paper "Improved Algorithms for Arithmetic on Anomalous Binary Curves"
+ by Jerome A. Solinas. The paper first appeared in the Proceedings of
+ Crypto 1997.
+
+
+ The window width of WTNAF. The standard value of 4 is slightly less
+ than optimal for running time, but keeps space requirements for
+ precomputation low. For typical curves, a value of 5 or 6 results in
+ a better running time. When changing this value, the
+ αu's must be computed differently, see
+ e.g. "Guide to Elliptic Curve Cryptography", Darrel Hankerson,
+ Alfred Menezes, Scott Vanstone, Springer-Verlag New York Inc., 2004,
+ p. 121-122
+
+
+ 24
+
+
+ The αu's for a=0 as an array
+ of ZTauElements.
+
+
+ The αu's for a=0 as an array
+ of TNAFs.
+
+
+ The αu's for a=1 as an array
+ of ZTauElements.
+
+
+ The αu's for a=1 as an array
+ of TNAFs.
+
+
+ Computes the norm of an element λ of
+ Z[τ].
+ @param mu The parameter μ of the elliptic curve.
+ @param lambda The element λ of
+ Z[τ].
+ @return The norm of λ.
+
+
+ Computes the norm of an element λ of
+ R[τ], where λ = u + vτ
+ and u and u are real numbers (elements of
+ R).
+ @param mu The parameter μ of the elliptic curve.
+ @param u The real part of the element λ of
+ R[τ].
+ @param v The τ-adic part of the element
+ λ of R[τ].
+ @return The norm of λ.
+
+
+ Rounds an element λ of R[τ]
+ to an element of Z[τ], such that their difference
+ has minimal norm. λ is given as
+ λ = λ0 + λ1τ.
+ @param lambda0 The component λ0.
+ @param lambda1 The component λ1.
+ @param mu The parameter μ of the elliptic curve. Must
+ equal 1 or -1.
+ @return The rounded element of Z[τ].
+ @throws ArgumentException if lambda0 and
+ lambda1 do not have same scale.
+
+
+ Approximate division by n. For an integer
+ k, the value λ = s k / n is
+ computed to c bits of accuracy.
+ @param k The parameter k.
+ @param s The curve parameter s0 or
+ s1.
+ @param vm The Lucas Sequence element Vm.
+ @param a The parameter a of the elliptic curve.
+ @param m The bit length of the finite field
+ Fm.
+ @param c The number of bits of accuracy, i.e. the scale of the returned
+ SimpleBigDecimal.
+ @return The value λ = s k / n computed to
+ c bits of accuracy.
+
+
+ Computes the τ-adic NAF (non-adjacent form) of an
+ element λ of Z[τ].
+ @param mu The parameter μ of the elliptic curve.
+ @param lambda The element λ of
+ Z[τ].
+ @return The τ-adic NAF of λ.
+
+
+ Applies the operation τ() to an
+ F2mPoint.
+ @param p The F2mPoint to which τ() is applied.
+ @return τ(p)
+
+
+ Returns the parameter μ of the elliptic curve.
+ @param curve The elliptic curve from which to obtain μ.
+ The curve must be a Koblitz curve, i.e. a Equals
+ 0 or 1 and b Equals
+ 1.
+ @return μ of the elliptic curve.
+ @throws ArgumentException if the given ECCurve is not a Koblitz
+ curve.
+
+
+ Calculates the Lucas Sequence elements Uk-1 and
+ Uk or Vk-1 and
+ Vk.
+ @param mu The parameter μ of the elliptic curve.
+ @param k The index of the second element of the Lucas Sequence to be
+ returned.
+ @param doV If set to true, computes Vk-1 and
+ Vk, otherwise Uk-1 and
+ Uk.
+ @return An array with 2 elements, containing Uk-1
+ and Uk or Vk-1
+ and Vk.
+
+
+ Computes the auxiliary value tw. If the width is
+ 4, then for mu = 1, tw = 6 and for
+ mu = -1, tw = 10
+ @param mu The parameter μ of the elliptic curve.
+ @param w The window width of the WTNAF.
+ @return the auxiliary value tw
+
+
+ Computes the auxiliary values s0 and
+ s1 used for partial modular reduction.
+ @param curve The elliptic curve for which to compute
+ s0 and s1.
+ @throws ArgumentException if curve is not a
+ Koblitz curve (Anomalous Binary Curve, ABC).
+
+
+ Partial modular reduction modulo
+ (τm - 1)/(τ - 1).
+ @param k The integer to be reduced.
+ @param m The bitlength of the underlying finite field.
+ @param a The parameter a of the elliptic curve.
+ @param s The auxiliary values s0 and
+ s1.
+ @param mu The parameter μ of the elliptic curve.
+ @param c The precision (number of bits of accuracy) of the partial
+ modular reduction.
+ @return ρ := k partmod (τm - 1)/(τ - 1)
+
+
+ Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint}
+ by a BigInteger using the reduced τ-adic
+ NAF (RTNAF) method.
+ @param p The F2mPoint to Multiply.
+ @param k The BigInteger by which to Multiply p.
+ @return k * p
+
+
+ Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint}
+ by an element λ of Z[τ]
+ using the τ-adic NAF (TNAF) method.
+ @param p The F2mPoint to Multiply.
+ @param lambda The element λ of
+ Z[τ].
+ @return λ * p
+
+
+ Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint}
+ by an element λ of Z[τ]
+ using the τ-adic NAF (TNAF) method, given the TNAF
+ of λ.
+ @param p The F2mPoint to Multiply.
+ @param u The the TNAF of λ..
+ @return λ * p
+
+
+ Computes the [τ]-adic window NAF of an element
+ λ of Z[τ].
+ @param mu The parameter μ of the elliptic curve.
+ @param lambda The element λ of
+ Z[τ] of which to compute the
+ [τ]-adic NAF.
+ @param width The window width of the resulting WNAF.
+ @param pow2w 2width.
+ @param tw The auxiliary value tw.
+ @param alpha The αu's for the window width.
+ @return The [τ]-adic window NAF of
+ λ.
+
+
+ Does the precomputation for WTNAF multiplication.
+ @param p The ECPoint for which to do the precomputation.
+ @param a The parameter a of the elliptic curve.
+ @return The precomputation array for p.
+
+
+ Class representing an element of Z[τ]. Let
+ λ be an element of Z[τ]. Then
+ λ is given as λ = u + vτ. The
+ components u and v may be used directly, there
+ are no accessor methods.
+ Immutable class.
+
+
+ The "real" part of λ.
+
+
+ The "τ-adic" part of λ.
+
+
+ Constructor for an element λ of
+ Z[τ].
+ @param u The "real" part of λ.
+ @param v The "τ-adic" part of
+ λ.
+
+
+ Base class for an elliptic curve.
+
+
+ Decode a point on this curve from its ASN.1 encoding. The different
+ encodings are taken account of, including point compression for
+ Fp (X9.62 s 4.2.1 pg 17).
+ @return The decoded point.
+
+
+ Elliptic curve over Fp
+
+
+ Elliptic curves over F2m. The Weierstrass equation is given by
+ y2 + xy = x3 + ax2 + b.
+
+
+ The exponent m of F2m.
+
+
+ TPB: The integer k where xm +
+ xk + 1 represents the reduction polynomial
+ f(z).
+ PPB: The integer k1 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+
+
+ TPB: Always set to 0
+ PPB: The integer k2 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+
+
+ TPB: Always set to 0
+ PPB: The integer k3 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+
+
+ The order of the base point of the curve.
+
+
+ The cofactor of the curve.
+
+
+ The point at infinity on this curve.
+
+
+ The parameter μ of the elliptic curve if this is
+ a Koblitz curve.
+
+
+ The auxiliary values s0 and
+ s1 used for partial modular reduction for
+ Koblitz curves.
+
+
+ Constructor for Trinomial Polynomial Basis (TPB).
+ @param m The exponent m of
+ F2m.
+ @param k The integer k where xm +
+ xk + 1 represents the reduction
+ polynomial f(z).
+ @param a The coefficient a in the Weierstrass equation
+ for non-supersingular elliptic curves over
+ F2m.
+ @param b The coefficient b in the Weierstrass equation
+ for non-supersingular elliptic curves over
+ F2m.
+
+
+ Constructor for Trinomial Polynomial Basis (TPB).
+ @param m The exponent m of
+ F2m.
+ @param k The integer k where xm +
+ xk + 1 represents the reduction
+ polynomial f(z).
+ @param a The coefficient a in the Weierstrass equation
+ for non-supersingular elliptic curves over
+ F2m.
+ @param b The coefficient b in the Weierstrass equation
+ for non-supersingular elliptic curves over
+ F2m.
+ @param n The order of the main subgroup of the elliptic curve.
+ @param h The cofactor of the elliptic curve, i.e.
+ #Ea(F2m) = h * n.
+
+
+ Constructor for Pentanomial Polynomial Basis (PPB).
+ @param m The exponent m of
+ F2m.
+ @param k1 The integer k1 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param k2 The integer k2 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param k3 The integer k3 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param a The coefficient a in the Weierstrass equation
+ for non-supersingular elliptic curves over
+ F2m.
+ @param b The coefficient b in the Weierstrass equation
+ for non-supersingular elliptic curves over
+ F2m.
+
+
+ Constructor for Pentanomial Polynomial Basis (PPB).
+ @param m The exponent m of
+ F2m.
+ @param k1 The integer k1 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param k2 The integer k2 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param k3 The integer k3 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param a The coefficient a in the Weierstrass equation
+ for non-supersingular elliptic curves over
+ F2m.
+ @param b The coefficient b in the Weierstrass equation
+ for non-supersingular elliptic curves over
+ F2m.
+ @param n The order of the main subgroup of the elliptic curve.
+ @param h The cofactor of the elliptic curve, i.e.
+ #Ea(F2m) = h * n.
+
+
+ Returns the parameter μ of the elliptic curve.
+ @return μ of the elliptic curve.
+ @throws ArgumentException if the given ECCurve is not a
+ Koblitz curve.
+
+
+ @return the auxiliary values s0 and
+ s1 used for partial modular reduction for
+ Koblitz curves.
+
+
+ Solves a quadratic equation z2 + z = beta(X9.62
+ D.1.6) The other solution is z + 1.
+
+ @param beta
+ The value to solve the qradratic equation for.
+ @return the solution for z2 + z = beta or
+ null if no solution exists.
+
+
+ Return true if curve uses a Trinomial basis.
+
+ @return true if curve Trinomial, false otherwise.
+
+
+ Returns true if this is a Koblitz curve (ABC curve).
+ @return true if this is a Koblitz curve (ABC curve), false otherwise
+
+
+ return a sqrt root - the routine verifies that the calculation
+ returns the right value - if none exists it returns null.
+
+
+ return the field name for this field.
+
+ @return the string "Fp".
+
+
+ Class representing the Elements of the finite field
+ F2m in polynomial basis (PB)
+ representation. Both trinomial (Tpb) and pentanomial (Ppb) polynomial
+ basis representations are supported. Gaussian normal basis (GNB)
+ representation is not supported.
+
+
+ Indicates gaussian normal basis representation (GNB). Number chosen
+ according to X9.62. GNB is not implemented at present.
+
+
+ Indicates trinomial basis representation (Tpb). Number chosen
+ according to X9.62.
+
+
+ Indicates pentanomial basis representation (Ppb). Number chosen
+ according to X9.62.
+
+
+ Tpb or Ppb.
+
+
+ The exponent m of F2m.
+
+
+ Tpb: The integer k where xm +
+ xk + 1 represents the reduction polynomial
+ f(z).
+ Ppb: The integer k1 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+
+
+ Tpb: Always set to 0
+ Ppb: The integer k2 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+
+
+ Tpb: Always set to 0
+ Ppb: The integer k3 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+
+
+ The IntArray holding the bits.
+
+
+ The number of ints required to hold m bits.
+
+
+ Constructor for Ppb.
+ @param m The exponent m of
+ F2m.
+ @param k1 The integer k1 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param k2 The integer k2 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param k3 The integer k3 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param x The BigInteger representing the value of the field element.
+
+
+ Constructor for Tpb.
+ @param m The exponent m of
+ F2m.
+ @param k The integer k where xm +
+ xk + 1 represents the reduction
+ polynomial f(z).
+ @param x The BigInteger representing the value of the field element.
+
+
+ Checks, if the ECFieldElements a and b
+ are elements of the same field F2m
+ (having the same representation).
+ @param a field element.
+ @param b field element to be compared.
+ @throws ArgumentException if a and b
+ are not elements of the same field
+ F2m (having the same
+ representation).
+
+
+ @return the representation of the field
+ F2m, either of
+ {@link F2mFieldElement.Tpb} (trinomial
+ basis representation) or
+ {@link F2mFieldElement.Ppb} (pentanomial
+ basis representation).
+
+
+ @return the degree m of the reduction polynomial
+ f(z).
+
+
+ @return Tpb: The integer k where xm +
+ xk + 1 represents the reduction polynomial
+ f(z).
+ Ppb: The integer k1 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+
+
+ @return Tpb: Always returns 0
+ Ppb: The integer k2 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+
+
+ @return Tpb: Always set to 0
+ Ppb: The integer k3 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+
+
+ base class for points on elliptic curves.
+
+
+ Sets the PreCompInfo. Used by ECMultipliers
+ to save the precomputation for this ECPoint to store the
+ precomputation result for use by subsequent multiplication.
+ @param preCompInfo The values precomputed by the
+ ECMultiplier.
+
+
+ Sets the appropriate ECMultiplier, unless already set.
+
+
+ return the field element encoded with point compression. (S 4.3.6)
+
+
+ Multiplies this ECPoint by the given number.
+ @param k The multiplicator.
+ @return k * this.
+
+
+ Elliptic curve points over Fp
+
+
+ Create a point which encodes with point compression.
+
+ @param curve the curve to use
+ @param x affine x co-ordinate
+ @param y affine y co-ordinate
+
+
+ Create a point that encodes with or without point compresion.
+
+ @param curve the curve to use
+ @param x affine x co-ordinate
+ @param y affine y co-ordinate
+ @param withCompression if true encode with point compression
+
+
+ Sets the default ECMultiplier, unless already set.
+
+
+ Elliptic curve points over F2m
+
+
+ @param curve base curve
+ @param x x point
+ @param y y point
+
+
+ @param curve base curve
+ @param x x point
+ @param y y point
+ @param withCompression true if encode with point compression.
+
+
+ Constructor for point at infinity
+
+
+ Check, if two ECPoints can be added or subtracted.
+ @param a The first ECPoint to check.
+ @param b The second ECPoint to check.
+ @throws IllegalArgumentException if a and b
+ cannot be added.
+
+
+ Adds another ECPoints.F2m to this without
+ checking if both points are on the same curve. Used by multiplication
+ algorithms, because there all points are a multiple of the same point
+ and hence the checks can be omitted.
+ @param b The other ECPoints.F2m to add to
+ this.
+ @return this + b
+
+
+ Subtracts another ECPoints.F2m from this
+ without checking if both points are on the same curve. Used by
+ multiplication algorithms, because there all points are a multiple
+ of the same point and hence the checks can be omitted.
+ @param b The other ECPoints.F2m to subtract from
+ this.
+ @return this - b
+
+
+ Sets the appropriate ECMultiplier, unless already set.
+
+
+ Interface for classes encapsulating a point multiplication algorithm
+ for ECPoints.
+
+
+ Multiplies the ECPoint p by k, i.e.
+ p is added k times to itself.
+ @param p The ECPoint to be multiplied.
+ @param k The factor by which p i multiplied.
+ @return p multiplied by k.
+
+
+ Class implementing the NAF (Non-Adjacent Form) multiplication algorithm.
+
+
+ D.3.2 pg 101
+ @see org.bouncycastle.math.ec.multiplier.ECMultiplier#multiply(org.bouncycastle.math.ec.ECPoint, java.math.BigInteger)
+
+
+ Interface for classes storing precomputation data for multiplication
+ algorithms. Used as a Memento (see GOF patterns) for
+ WNafMultiplier.
+
+
+ Simple shift-and-add multiplication. Serves as reference implementation
+ to verify (possibly faster) implementations in
+ {@link org.bouncycastle.math.ec.ECPoint ECPoint}.
+
+ @param p The point to multiply.
+ @param k The factor by which to multiply.
+ @return The result of the point multiplication k * p.
+
+
+ Class implementing the WNAF (Window Non-Adjacent Form) multiplication
+ algorithm.
+
+
+ Computes the Window NAF (non-adjacent Form) of an integer.
+ @param width The width w of the Window NAF. The width is
+ defined as the minimal number w, such that for any
+ w consecutive digits in the resulting representation, at
+ most one is non-zero.
+ @param k The integer of which the Window NAF is computed.
+ @return The Window NAF of the given width, such that the following holds:
+ k = −i=0l-1 ki2i
+ , where the ki denote the elements of the
+ returned sbyte[].
+
+
+ Multiplies this by an integer k using the
+ Window NAF method.
+ @param k The integer by which this is multiplied.
+ @return A new ECPoint which equals this
+ multiplied by k.
+
+
+ Class holding precomputation data for the WNAF (Window Non-Adjacent Form)
+ algorithm.
+
+
+ Array holding the precomputed ECPoints used for the Window
+ NAF multiplication in
+ {@link org.bouncycastle.math.ec.multiplier.WNafMultiplier.multiply()
+ WNafMultiplier.multiply()}.
+
+
+ Holds an ECPoint representing twice(this). Used for the
+ Window NAF multiplication in
+ {@link org.bouncycastle.math.ec.multiplier.WNafMultiplier.multiply()
+ WNafMultiplier.multiply()}.
+
+
+ Class implementing the WTNAF (Window
+ τ-adic Non-Adjacent Form) algorithm.
+
+
+ Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint}
+ by k using the reduced τ-adic NAF (RTNAF)
+ method.
+ @param p The F2mPoint to multiply.
+ @param k The integer by which to multiply k.
+ @return p multiplied by k.
+
+
+ Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint}
+ by an element λ of Z[τ] using
+ the τ-adic NAF (TNAF) method.
+ @param p The F2mPoint to multiply.
+ @param lambda The element λ of
+ Z[τ] of which to compute the
+ [τ]-adic NAF.
+ @return p multiplied by λ.
+
+
+ Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint}
+ by an element λ of Z[τ]
+ using the window τ-adic NAF (TNAF) method, given the
+ WTNAF of λ.
+ @param p The F2mPoint to multiply.
+ @param u The the WTNAF of λ..
+ @return λ * p
+
+
+ Class holding precomputation data for the WTNAF (Window
+ τ-adic Non-Adjacent Form) algorithm.
+
+
+ Array holding the precomputed F2mPoints used for the
+ WTNAF multiplication in
+ {@link org.bouncycastle.math.ec.multiplier.WTauNafMultiplier.multiply()
+ WTauNafMultiplier.multiply()}.
+
+
+ Constructor for WTauNafPreCompInfo
+ @param preComp Array holding the precomputed F2mPoints
+ used for the WTNAF multiplication in
+ {@link org.bouncycastle.math.ec.multiplier.WTauNafMultiplier.multiply()
+ WTauNafMultiplier.multiply()}.
+
+
+ @return the array holding the precomputed F2mPoints
+ used for the WTNAF multiplication in
+ {@link org.bouncycastle.math.ec.multiplier.WTauNafMultiplier.multiply()
+ WTauNafMultiplier.multiply()}.
+
+
+
+
+ BasicOcspResponse ::= SEQUENCE {
+ tbsResponseData ResponseData,
+ signatureAlgorithm AlgorithmIdentifier,
+ signature BIT STRING,
+ certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL
+ }
+
+
+
+
+
+ Get all critical extension values, by oid
+
+ IDictionary with string (OID) keys and Asn1OctetString values
+
+
+
+ Get all non-critical extension values, by oid
+
+ IDictionary with string (OID) keys and Asn1OctetString values
+
+
+
+ Get non critical extensions.
+
+ A set of non critical extension oids.
+
+
+
+ Get any critical extensions.
+
+ A sorted list of critical entension.
+
+
+
+ Get the value of a given extension.
+
+ The object ID of the extension.
+ An Asn1OctetString object if that extension is found or null if not.
+
+
+ The DER encoding of the tbsResponseData field.
+ In the event of an encoding error.
+
+
+ The certificates, if any, associated with the response.
+ In the event of an encoding error.
+
+
+
+ Verify the signature against the tbsResponseData object we contain.
+
+
+
+ The ASN.1 encoded representation of this object.
+
+
+ Generator for basic OCSP response objects.
+
+
+ basic constructor
+
+
+ construct with the responderID to be the SHA-1 keyHash of the passed in public key.
+
+
+ Add a response for a particular Certificate ID.
+
+ @param certID certificate ID details
+ @param certStatus status of the certificate - null if okay
+
+
+ Add a response for a particular Certificate ID.
+
+ @param certID certificate ID details
+ @param certStatus status of the certificate - null if okay
+ @param singleExtensions optional extensions
+
+
+ Add a response for a particular Certificate ID.
+
+ @param certID certificate ID details
+ @param nextUpdate date when next update should be requested
+ @param certStatus status of the certificate - null if okay
+ @param singleExtensions optional extensions
+
+
+ Add a response for a particular Certificate ID.
+
+ @param certID certificate ID details
+ @param thisUpdate date this response was valid on
+ @param nextUpdate date when next update should be requested
+ @param certStatus status of the certificate - null if okay
+ @param singleExtensions optional extensions
+
+
+ Set the extensions for the response.
+
+ @param responseExtensions the extension object to carry.
+
+
+ Return an IEnumerable of the signature names supported by the generator.
+
+ @return an IEnumerable containing recognised names.
+
+
+ create from an issuer certificate and the serial number of the
+ certificate it signed.
+ @exception OcspException if any problems occur creating the id fields.
+
+
+ Create a new CertificateID for a new serial number derived from a previous one
+ calculated for the same CA certificate.
+
+ @param original the previously calculated CertificateID for the CA.
+ @param newSerialNumber the serial number for the new certificate of interest.
+
+ @return a new CertificateID for newSerialNumber
+
+
+ return the serial number for the certificate associated
+ with this request.
+
+
+
+
+
+ Return the DER encoding of the tbsRequest field.
+ @return DER encoding of tbsRequest
+ @throws OcspException in the event of an encoding error.
+
+
+ If the request is signed return a possibly empty CertStore containing the certificates in the
+ request. If the request is not signed the method returns null.
+
+ @return null if not signed, a CertStore otherwise
+ @throws OcspException
+
+
+ Verify the signature against the TBSRequest object we contain.
+
+
+ return the ASN.1 encoded representation of this object.
+
+
+ return the object identifier representing the signature algorithm
+
+
+ Return whether or not this request is signed.
+
+ @return true if signed false otherwise.
+
+
+ Add a request for the given CertificateID.
+
+ @param certId certificate ID of interest
+
+
+ Add a request with extensions
+
+ @param certId certificate ID of interest
+ @param singleRequestExtensions the extensions to attach to the request
+
+
+ Set the requestor name to the passed in X509Principal
+
+ @param requestorName a X509Principal representing the requestor name.
+
+
+ Generate an unsigned request
+
+ @return the OcspReq
+ @throws OcspException
+
+
+ Return an IEnumerable of the signature names supported by the generator.
+
+ @return an IEnumerable containing recognised names.
+
+
+ return the ASN.1 encoded representation of this object.
+
+
+ base generator for an OCSP response - at the moment this only supports the
+ generation of responses containing BasicOCSP responses.
+
+
+ note 4 is not used.
+
+
+ Carrier for a ResponderID.
+
+
+ wrapper for the RevokedInfo object
+
+
+ return the revocation reason. Note: this field is optional, test for it
+ with hasRevocationReason() first.
+ @exception InvalidOperationException if a reason is asked for and none is avaliable
+
+
+ Return the status object for the response - null indicates good.
+
+ @return the status object for the response, null if it is good.
+
+
+ return the NextUpdate value - note: this is an optional field so may
+ be returned as null.
+
+ @return nextUpdate, or null if not present.
+
+
+ wrapper for the UnknownInfo object
+
+
+ Compressed data objects
+
+
+ Get the raw input stream contained in the object.
+
+
+ Return an uncompressed input stream which allows reading of the compressed data.
+
+
+ The algorithm used for compression
+
+
+ Class for producing compressed data packets.
+
+
+
+
+ Return an output stream which will save the data being written to
+ the compressed object.
+
+
+ The stream created can be closed off by either calling Close()
+ on the stream or Close() on the generator. Closing the returned
+ stream does not close off the Stream parameter outStr.
+
+
+ Stream to be used for output.
+ A Stream for output of the compressed data.
+
+
+
+
+
+
+
+ Return an output stream which will compress the data as it is written to it.
+ The stream will be written out in chunks according to the size of the passed in buffer.
+
+
+ The stream created can be closed off by either calling Close()
+ on the stream or Close() on the generator. Closing the returned
+ stream does not close off the Stream parameter outStr.
+
+
+ Note: if the buffer is not a power of 2 in length only the largest power of 2
+ bytes worth of the buffer will be used.
+
+
+ Note: using this may break compatibility with RFC 1991 compliant tools.
+ Only recent OpenPGP implementations are capable of accepting these streams.
+
+
+ Stream to be used for output.
+ The buffer to use.
+ A Stream for output of the compressed data.
+
+
+
+
+
+
+ Close the compressed object.summary>
+
+
+
+ Thrown if the IV at the start of a data stream indicates the wrong key is being used.
+
+
+
+ Generic exception class for PGP encoding/decoding problems.
+
+
+ Return the raw input stream for the data stream.
+
+
+ Return true if the message is integrity protected.
+ True, if there is a modification detection code namespace associated
+ with this stream.
+
+
+ Note: This can only be called after the message has been read.
+ True, if the message verifies, false otherwise
+
+
+ Generator for encrypted objects.
+
+
+ Existing SecureRandom constructor.
+ The symmetric algorithm to use.
+ Source of randomness.
+
+
+ Creates a cipher stream which will have an integrity packet associated with it.
+
+
+ Base constructor.
+ The symmetric algorithm to use.
+ Source of randomness.
+ PGP 2.6.x compatibility required.
+
+
+
+ Add a PBE encryption method to the encrypted object using the default algorithm (S2K_SHA1).
+
+
+
+ Add a PBE encryption method to the encrypted object.
+
+
+ Add a public key encrypted session key to the encrypted object.
+
+
+
+
+ If buffer is non null stream assumed to be partial, otherwise the length will be used
+ to output a fixed length packet.
+
+
+ The stream created can be closed off by either calling Close()
+ on the stream or Close() on the generator. Closing the returned
+ stream does not close off the Stream parameter outStr.
+
+
+
+
+
+
+ Return an output stream which will encrypt the data as it is written to it.
+
+
+ The stream created can be closed off by either calling Close()
+ on the stream or Close() on the generator. Closing the returned
+ stream does not close off the Stream parameter outStr.
+
+
+
+
+
+
+ Return an output stream which will encrypt the data as it is written to it.
+ The stream will be written out in chunks according to the size of the passed in buffer.
+
+
+ The stream created can be closed off by either calling Close()
+ on the stream or Close() on the generator. Closing the returned
+ stream does not close off the Stream parameter outStr.
+
+
+ Note: if the buffer is not a power of 2 in length only the largest power of 2
+ bytes worth of the buffer will be used.
+
+
+
+
+
+
+ Close off the encrypted object - this is equivalent to calling Close() on the stream
+ returned by the Open() method.
+
+
+ Note: This does not close the underlying output stream, only the stream on top of
+ it created by the Open() method.
+
+
+
+
+ A holder for a list of PGP encryption method packets.
+
+
+ Key flag values for the KeyFlags subpacket.
+
+
+
+ General class to handle JCA key pairs and convert them into OpenPGP ones.
+
+ A word for the unwary, the KeyId for an OpenPGP public key is calculated from
+ a hash that includes the time of creation, if you pass a different date to the
+ constructor below with the same public private key pair the KeyIs will not be the
+ same as for previous generations of the key, so ideally you only want to do
+ this once.
+
+
+
+
+ Create a key pair from a PgpPrivateKey and a PgpPublicKey.
+ The public key.
+ The private key.
+
+
+ The keyId associated with this key pair.
+
+
+
+ Generator for a PGP master and subkey ring.
+ This class will generate both the secret and public key rings
+
+
+
+
+ Create a new key ring generator using old style checksumming. It is recommended to use
+ SHA1 checksumming where possible.
+
+ The certification level for keys on this ring.
+ The master key pair.
+ The id to be associated with the ring.
+ The algorithm to be used to protect secret keys.
+ The passPhrase to be used to protect secret keys.
+ Packets to be included in the certification hash.
+ Packets to be attached unhashed to the certification.
+ input secured random.
+
+
+
+ Create a new key ring generator.
+
+ The certification level for keys on this ring.
+ The master key pair.
+ The id to be associated with the ring.
+ The algorithm to be used to protect secret keys.
+ The passPhrase to be used to protect secret keys.
+ Checksum the secret keys with SHA1 rather than the older 16 bit checksum.
+ Packets to be included in the certification hash.
+ Packets to be attached unhashed to the certification.
+ input secured random.
+
+
+ Add a subkey to the key ring to be generated with default certification.
+
+
+
+ Add a subkey with specific hashed and unhashed packets associated with it and
+ default certification.
+
+ Public/private key pair.
+ Hashed packet values to be included in certification.
+ Unhashed packets values to be included in certification.
+
+
+
+ Return the secret key ring.
+
+
+ Return the public key ring that corresponds to the secret key ring.
+
+
+
+ Thrown if the key checksum is invalid.
+
+
+
+ Class for processing literal data objects.
+
+
+ The special name indicating a "for your eyes only" packet.
+
+
+ Return the file name as an unintrepreted byte array.
+
+
+ The raw input stream for the data stream.
+
+
+ The input stream representing the data stream.
+
+
+ The format of the data stream - Binary or Text
+
+
+ The file name that's associated with the data stream.
+
+
+ The modification time for the file.
+
+
+ Class for producing literal data packets.
+
+
+ The special name indicating a "for your eyes only" packet.
+
+
+
+ Generates literal data objects in the old format.
+ This is important if you need compatibility with PGP 2.6.x.
+
+ If true, uses old format.
+
+
+
+
+ Open a literal data packet, returning a stream to store the data inside the packet.
+
+
+ The stream created can be closed off by either calling Close()
+ on the stream or Close() on the generator. Closing the returned
+ stream does not close off the Stream parameter outStr.
+
+
+ The stream we want the packet in.
+ The format we are using.
+ The name of the 'file'.
+ The length of the data we will write.
+ The time of last modification we want stored.
+
+
+
+
+ Open a literal data packet, returning a stream to store the data inside the packet,
+ as an indefinite length stream. The stream is written out as a series of partial
+ packets with a chunk size determined by the size of the passed in buffer.
+
+
+ The stream created can be closed off by either calling Close()
+ on the stream or Close() on the generator. Closing the returned
+ stream does not close off the Stream parameter outStr.
+
+
+ Note: if the buffer is not a power of 2 in length only the largest power of 2
+ bytes worth of the buffer will be used.
+
+ The stream we want the packet in.
+ The format we are using.
+ The name of the 'file'.
+ The time of last modification we want stored.
+ The buffer to use for collecting data to put into chunks.
+
+
+
+ Close the literal data packet - this is equivalent to calling Close()
+ on the stream returned by the Open() method.
+
+
+
+
+ A PGP marker packet - in general these should be ignored other than where
+ the idea is to preserve the original input stream.
+
+
+
+
+ General class for reading a PGP object stream.
+
+ Note: if this class finds a PgpPublicKey or a PgpSecretKey it
+ will create a PgpPublicKeyRing, or a PgpSecretKeyRing for each
+ key found. If all you are trying to do is read a key ring file use
+ either PgpPublicKeyRingBundle or PgpSecretKeyRingBundle.
+
+
+
+ Return the next object in the stream, or null if the end is reached.
+ On a parse error
+
+
+
+ Return all available objects in a list.
+
+ An IList containing all objects from this factory, in order.
+
+
+ A one pass signature object.
+
+
+ Initialise the signature object for verification.
+
+
+ Verify the calculated signature against the passed in PgpSignature.
+
+
+ Holder for a list of PgpOnePassSignature objects.
+
+
+ A password based encryption object.
+
+
+ Return the raw input stream for the data stream.
+
+
+ Return the decrypted input stream, using the passed in passphrase.
+
+
+ General class to contain a private key for use with other OpenPGP objects.
+
+
+
+ Create a PgpPrivateKey from a regular private key and the ID of its
+ associated public key.
+
+ Private key to use.
+ ID of the corresponding public key.
+
+
+ The keyId associated with the contained private key.
+
+
+ The contained private key.
+
+
+ General class to handle a PGP public key object.
+
+
+
+ Create a PgpPublicKey from the passed in lightweight one.
+
+
+ Note: the time passed in affects the value of the key's keyId, so you probably only want
+ to do this once for a lightweight key, or make sure you keep track of the time you used.
+
+ Asymmetric algorithm type representing the public key.
+ Actual public key to associate.
+ Date of creation.
+ If pubKey is not public.
+ On key creation problem.
+
+
+ Constructor for a sub-key.
+
+
+ Copy constructor.
+ The public key to copy.
+
+
+ Return the trust data associated with the public key, if present.
+ A byte array with trust data, null otherwise.
+
+
+ The number of valid seconds from creation time - zero means no expiry.
+
+
+ The fingerprint of the key
+
+
+ The public key contained in the object.
+ A lightweight public key.
+ If the key algorithm is not recognised.
+
+
+ Allows enumeration of any user IDs associated with the key.
+ An IEnumerable of string objects.
+
+
+ Allows enumeration of any user attribute vectors associated with the key.
+ An IEnumerable of PgpUserAttributeSubpacketVector objects.
+
+
+ Allows enumeration of any signatures associated with the passed in id.
+ The ID to be matched.
+ An IEnumerable of PgpSignature objects.
+
+
+ Allows enumeration of signatures associated with the passed in user attributes.
+ The vector of user attributes to be matched.
+ An IEnumerable of PgpSignature objects.
+
+
+ Allows enumeration of signatures of the passed in type that are on this key.
+ The type of the signature to be returned.
+ An IEnumerable of PgpSignature objects.
+
+
+ Allows enumeration of all signatures/certifications associated with this key.
+ An IEnumerable with all signatures/certifications.
+
+
+ Check whether this (sub)key has a revocation signature on it.
+ True, if this (sub)key has been revoked.
+
+
+ Add a certification for an id to the given public key.
+ The key the certification is to be added to.
+ The ID the certification is associated with.
+ The new certification.
+ The re-certified key.
+
+
+ Add a certification for the given UserAttributeSubpackets to the given public key.
+ The key the certification is to be added to.
+ The attributes the certification is associated with.
+ The new certification.
+ The re-certified key.
+
+
+
+ Remove any certifications associated with a user attribute subpacket on a key.
+
+ The key the certifications are to be removed from.
+ The attributes to be removed.
+
+ The re-certified key, or null if the user attribute subpacket was not found on the key.
+
+
+
+ Remove any certifications associated with a given ID on a key.
+ The key the certifications are to be removed from.
+ The ID that is to be removed.
+ The re-certified key, or null if the ID was not found on the key.
+
+
+ Remove a certification associated with a given ID on a key.
+ The key the certifications are to be removed from.
+ The ID that the certfication is to be removed from.
+ The certfication to be removed.
+ The re-certified key, or null if the certification was not found.
+
+
+ Remove a certification associated with a given user attributes on a key.
+ The key the certifications are to be removed from.
+ The user attributes that the certfication is to be removed from.
+ The certification to be removed.
+ The re-certified key, or null if the certification was not found.
+
+
+ Add a revocation or some other key certification to a key.
+ The key the revocation is to be added to.
+ The key signature to be added.
+ The new changed public key object.
+
+
+ Remove a certification from the key.
+ The key the certifications are to be removed from.
+ The certfication to be removed.
+ The modified key, null if the certification was not found.
+
+
+ The version of this key.
+
+
+ The creation time of this key.
+
+
+ The number of valid days from creation time - zero means no expiry.
+
+
+ The keyId associated with the public key.
+
+
+
+ Check if this key has an algorithm type that makes it suitable to use for encryption.
+
+
+ Note: with version 4 keys KeyFlags subpackets should also be considered when present for
+ determining the preferred use of the key.
+
+
+ true if this key algorithm is suitable for encryption.
+
+
+
+ True, if this is a master key.
+
+
+ The algorithm code associated with the public key.
+
+
+ The strength of the key in bits.
+
+
+ A public key encrypted data object.
+
+
+
+ Return the algorithm code for the symmetric algorithm used to encrypt the data.
+
+
+
+ Return the decrypted data stream for the packet.
+
+
+ The key ID for the key used to encrypt the data.
+
+
+
+ Class to hold a single master public key and its subkeys.
+
+ Often PGP keyring files consist of multiple master keys, if you are trying to process
+ or construct one of these you should use the PgpPublicKeyRingBundle class.
+
+
+
+
+ Return the first public key in the ring.
+
+
+ Return the public key referred to by the passed in key ID if it is present.
+
+
+ Allows enumeration of all the public keys.
+ An IEnumerable of PgpPublicKey objects.
+
+
+
+ Returns a new key ring with the public key passed in either added or
+ replacing an existing one.
+
+ The public key ring to be modified.
+ The public key to be inserted.
+ A new PgpPublicKeyRing
+
+
+ Returns a new key ring with the public key passed in removed from the key ring.
+ The public key ring to be modified.
+ The public key to be removed.
+ A new PgpPublicKeyRing, or null if pubKey is not found.
+
+
+
+ Often a PGP key ring file is made up of a succession of master/sub-key key rings.
+ If you want to read an entire public key file in one hit this is the class for you.
+
+
+
+ Build a PgpPublicKeyRingBundle from the passed in input stream.
+ Input stream containing data.
+ If a problem parsing the stream occurs.
+ If an object is encountered which isn't a PgpPublicKeyRing.
+
+
+ Allow enumeration of the public key rings making up this collection.
+
+
+ Allow enumeration of the key rings associated with the passed in userId.
+ The user ID to be matched.
+ An IEnumerable of key rings which matched (possibly none).
+
+
+ Allow enumeration of the key rings associated with the passed in userId.
+ The user ID to be matched.
+ If true, userId need only be a substring of an actual ID string to match.
+ An IEnumerable of key rings which matched (possibly none).
+
+
+ Allow enumeration of the key rings associated with the passed in userId.
+ The user ID to be matched.
+ If true, userId need only be a substring of an actual ID string to match.
+ If true, case is ignored in user ID comparisons.
+ An IEnumerable of key rings which matched (possibly none).
+
+
+ Return the PGP public key associated with the given key id.
+ The ID of the public key to return.
+
+
+ Return the public key ring which contains the key referred to by keyId
+ key ID to match against
+
+
+
+ Return true if a key matching the passed in key ID is present, false otherwise.
+
+ key ID to look for.
+
+
+
+ Return a new bundle containing the contents of the passed in bundle and
+ the passed in public key ring.
+
+ The PgpPublicKeyRingBundle the key ring is to be added to.
+ The key ring to be added.
+ A new PgpPublicKeyRingBundle merging the current one with the passed in key ring.
+ If the keyId for the passed in key ring is already present.
+
+
+
+ Return a new bundle containing the contents of the passed in bundle with
+ the passed in public key ring removed.
+
+ The PgpPublicKeyRingBundle the key ring is to be removed from.
+ The key ring to be removed.
+ A new PgpPublicKeyRingBundle not containing the passed in key ring.
+ If the keyId for the passed in key ring is not present.
+
+
+ Return the number of key rings in this collection.
+
+
+ General class to handle a PGP secret key object.
+
+
+ Extract a PgpPrivateKey from this secret key's encrypted contents.
+
+
+
+ Return a copy of the passed in secret key, encrypted using a new password
+ and the passed in algorithm.
+
+ The PgpSecretKey to be copied.
+ The current password for the key.
+ The new password for the key.
+ The algorithm to be used for the encryption.
+ Source of randomness.
+
+
+ Replace the passed the public key on the passed in secret key.
+ Secret key to change.
+ New public key.
+ A new secret key.
+ If KeyId's do not match.
+
+
+
+ Check if this key has an algorithm type that makes it suitable to use for signing.
+
+
+ Note: with version 4 keys KeyFlags subpackets should also be considered when present for
+ determining the preferred use of the key.
+
+
+ true if this key algorithm is suitable for use with signing.
+
+
+
+ True, if this is a master key.
+
+
+ The algorithm the key is encrypted with.
+
+
+ The key ID of the public key associated with this key.
+
+
+ The public key associated with this key.
+
+
+ Allows enumeration of any user IDs associated with the key.
+ An IEnumerable of string objects.
+
+
+ Allows enumeration of any user attribute vectors associated with the key.
+ An IEnumerable of string objects.
+
+
+
+ Class to hold a single master secret key and its subkeys.
+
+ Often PGP keyring files consist of multiple master keys, if you are trying to process
+ or construct one of these you should use the PgpSecretKeyRingBundle class.
+
+
+
+
+ Return the public key for the master key.
+
+
+ Return the master private key.
+
+
+ Allows enumeration of the secret keys.
+ An IEnumerable of PgpSecretKey objects.
+
+
+
+ Return an iterator of the public keys in the secret key ring that
+ have no matching private key. At the moment only personal certificate data
+ appears in this fashion.
+
+ An IEnumerable of unattached, or extra, public keys.
+
+
+
+ Replace the public key set on the secret ring with the corresponding key off the public ring.
+
+ Secret ring to be changed.
+ Public ring containing the new public key set.
+
+
+
+ Return a copy of the passed in secret key ring, with the master key and sub keys encrypted
+ using a new password and the passed in algorithm.
+
+ The PgpSecretKeyRing to be copied.
+ The current password for key.
+ The new password for the key.
+ The algorithm to be used for the encryption.
+ Source of randomness.
+
+
+
+ Returns a new key ring with the secret key passed in either added or
+ replacing an existing one with the same key ID.
+
+ The secret key ring to be modified.
+ The secret key to be inserted.
+ A new PgpSecretKeyRing
+
+
+ Returns a new key ring with the secret key passed in removed from the key ring.
+ The secret key ring to be modified.
+ The secret key to be removed.
+ A new PgpSecretKeyRing, or null if secKey is not found.
+
+
+
+ Often a PGP key ring file is made up of a succession of master/sub-key key rings.
+ If you want to read an entire secret key file in one hit this is the class for you.
+
+
+
+ Build a PgpSecretKeyRingBundle from the passed in input stream.
+ Input stream containing data.
+ If a problem parsing the stream occurs.
+ If an object is encountered which isn't a PgpSecretKeyRing.
+
+
+ Allow enumeration of the secret key rings making up this collection.
+
+
+ Allow enumeration of the key rings associated with the passed in userId.
+ The user ID to be matched.
+ An IEnumerable of key rings which matched (possibly none).
+
+
+ Allow enumeration of the key rings associated with the passed in userId.
+ The user ID to be matched.
+ If true, userId need only be a substring of an actual ID string to match.
+ An IEnumerable of key rings which matched (possibly none).
+
+
+ Allow enumeration of the key rings associated with the passed in userId.
+ The user ID to be matched.
+ If true, userId need only be a substring of an actual ID string to match.
+ If true, case is ignored in user ID comparisons.
+ An IEnumerable of key rings which matched (possibly none).
+
+
+ Return the PGP secret key associated with the given key id.
+ The ID of the secret key to return.
+
+
+ Return the secret key ring which contains the key referred to by keyId
+ The ID of the secret key
+
+
+
+ Return true if a key matching the passed in key ID is present, false otherwise.
+
+ key ID to look for.
+
+
+
+ Return a new bundle containing the contents of the passed in bundle and
+ the passed in secret key ring.
+
+ The PgpSecretKeyRingBundle the key ring is to be added to.
+ The key ring to be added.
+ A new PgpSecretKeyRingBundle merging the current one with the passed in key ring.
+ If the keyId for the passed in key ring is already present.
+
+
+
+ Return a new bundle containing the contents of the passed in bundle with
+ the passed in secret key ring removed.
+
+ The PgpSecretKeyRingBundle the key ring is to be removed from.
+ The key ring to be removed.
+ A new PgpSecretKeyRingBundle not containing the passed in key ring.
+ If the keyId for the passed in key ring is not present.
+
+
+ Return the number of rings in this collection.
+
+
+ A PGP signature object.
+
+
+
+ Verify the signature as certifying the passed in public key as associated
+ with the passed in user attributes.
+
+ User attributes the key was stored under.
+ The key to be verified.
+ True, if the signature matches, false otherwise.
+
+
+
+ Verify the signature as certifying the passed in public key as associated
+ with the passed in ID.
+
+ ID the key was stored under.
+ The key to be verified.
+ True, if the signature matches, false otherwise.
+
+
+ Verify a certification for the passed in key against the passed in master key.
+ The key we are verifying against.
+ The key we are verifying.
+ True, if the certification is valid, false otherwise.
+
+
+ Verify a key certification, such as revocation, for the passed in key.
+ The key we are checking.
+ True, if the certification is valid, false otherwise.
+
+
+ The OpenPGP version number for this signature.
+
+
+ The key algorithm associated with this signature.
+
+
+ The hash algorithm associated with this signature.
+
+
+ The ID of the key that created the signature.
+
+
+ The creation time of this signature.
+
+
+
+ Return true if the signature has either hashed or unhashed subpackets.
+
+
+
+ Generator for PGP signatures.
+
+
+ Create a generator for the passed in keyAlgorithm and hashAlgorithm codes.
+
+
+ Initialise the generator for signing.
+
+
+ Initialise the generator for signing.
+
+
+ Return the one pass header associated with the current signature.
+
+
+ Return a signature object containing the current signature state.
+
+
+ Generate a certification for the passed in ID and key.
+ The ID we are certifying against the public key.
+ The key we are certifying against the ID.
+ The certification.
+
+
+ Generate a certification for the passed in userAttributes.
+ The ID we are certifying against the public key.
+ The key we are certifying against the ID.
+ The certification.
+
+
+ Generate a certification for the passed in key against the passed in master key.
+ The key we are certifying against.
+ The key we are certifying.
+ The certification.
+
+
+ Generate a certification, such as a revocation, for the passed in key.
+ The key we are certifying.
+ The certification.
+
+
+ A list of PGP signatures - normally in the signature block after literal data.
+
+
+ Generator for signature subpackets.
+
+
+
+ Add a TrustSignature packet to the signature. The values for depth and trust are largely
+ installation dependent but there are some guidelines in RFC 4880 - 5.2.3.13.
+
+ true if the packet is critical.
+ depth level.
+ trust amount.
+
+
+
+ Set the number of seconds a key is valid for after the time of its creation.
+ A value of zero means the key never expires.
+
+ True, if should be treated as critical, false otherwise.
+ The number of seconds the key is valid, or zero if no expiry.
+
+
+
+ Set the number of seconds a signature is valid for after the time of its creation.
+ A value of zero means the signature never expires.
+
+ True, if should be treated as critical, false otherwise.
+ The number of seconds the signature is valid, or zero if no expiry.
+
+
+
+ Set the creation time for the signature.
+
+ Note: this overrides the generation of a creation time when the signature
+ is generated.
+
+
+
+
+ Sets revocation reason sub packet
+
+
+
+
+ Sets revocation key sub packet
+
+
+
+
+ Sets issuer key sub packet
+
+
+
+ Container for a list of signature subpackets.
+
+
+ Return true if a particular subpacket type exists.
+
+ @param type type to look for.
+ @return true if present, false otherwise.
+
+
+ Return all signature subpackets of the passed in type.
+ @param type subpacket type code
+ @return an array of zero or more matching subpackets.
+
+
+
+ Return the number of seconds a signature is valid for after its creation date.
+ A value of zero means the signature never expires.
+
+ Seconds a signature is valid for.
+
+
+
+ Return the number of seconds a key is valid for after its creation date.
+ A value of zero means the key never expires.
+
+ Seconds a signature is valid for.
+
+
+ Return the number of packets this vector contains.
+
+
+ Container for a list of user attribute subpackets.
+
+
+ Basic utility class.
+
+
+
+ Return either an ArmoredInputStream or a BcpgInputStream based on whether
+ the initial characters of the stream are binary PGP encodings or not.
+
+
+
+ Generator for old style PGP V3 Signatures.
+
+
+ Create a generator for the passed in keyAlgorithm and hashAlgorithm codes.
+
+
+ Initialise the generator for signing.
+
+
+ Initialise the generator for signing.
+
+
+ Return the one pass header associated with the current signature.
+
+
+ Return a V3 signature object containing the current signature state.
+
+
+ PEM generator for the original set of PEM objects used in Open SSL.
+
+
+
+ A
+
+
+
+
+ Class for reading OpenSSL PEM encoded streams containing
+ X509 certificates, PKCS8 encoded keys and PKCS7 objects.
+
+ In the case of PKCS7 objects the reader will return a CMS ContentInfo object. Keys and
+ Certificates will be returned using the appropriate java.security type.
+
+
+
+ A
+
+
+
+
+ Create a new PemReader
+
+ @param reader the Reader
+
+
+ Create a new PemReader with a password finder
+
+ @param reader the Reader
+ @param pFinder the password finder
+
+
+ Reads in a X509Certificate.
+
+ @return the X509Certificate
+ @throws IOException if an I/O error occured
+
+
+ Reads in a X509CRL.
+
+ @return the X509Certificate
+ @throws IOException if an I/O error occured
+
+
+ Reads in a PKCS10 certification request.
+
+ @return the certificate request.
+ @throws IOException if an I/O error occured
+
+
+ Reads in a X509 Attribute Certificate.
+
+ @return the X509 Attribute Certificate
+ @throws IOException if an I/O error occured
+
+
+ Reads in a PKCS7 object. This returns a ContentInfo object suitable for use with the CMS
+ API.
+
+ @return the X509Certificate
+ @throws IOException if an I/O error occured
+
+
+ Read a Key Pair
+
+
+ General purpose writer for OpenSSL PEM objects.
+
+
+ A generic PEM writer, based on RFC 1421
+
+
+ Base constructor.
+
+ @param out output stream to use.
+
+
+ Return the number of bytes or characters required to contain the
+ passed in object if it is PEM encoded.
+
+ @param obj pem object to be output
+ @return an estimate of the number of bytes
+
+
+ The TextWriter object to write the output to.
+
+
+ Constructor for an unencrypted private key PEM object.
+
+ @param key private key to be encoded.
+
+
+ Constructor for an encrypted private key PEM object.
+
+ @param key private key to be encoded
+ @param algorithm encryption algorithm to use
+ @param provider provider to use
+ @throws NoSuchAlgorithmException if algorithm/mode cannot be found
+
+
+
+ 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 Attr{{ IOSet }}
+
+ Attr { ATTRIBUTE:IOSet } ::= Sequence {
+ type ATTRIBUTE.&id({IOSet}),
+ values Set SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type})
+ }
+
+ see
+
+
+
+ Instantiate a Pkcs10CertificationRequest object with the necessary credentials.
+
+ Name of Sig Alg.
+ X509Name of subject eg OU="My unit." O="My Organisatioin" C="au"
+ Public Key to be included in cert reqest.
+ ASN1Set of Attributes.
+ Matching Private key for nominated (above) public key to be used to sign the request.
+
+
+
+ Get the public key.
+
+ The public key.
+
+
+
+ Verify Pkcs10 Cert Request is valid.
+
+ true = valid.
+
+
+
+ A class for creating and verifying Pkcs10 Certification requests (this is an extension on ).
+ The requests are made using delay signing. This is useful for situations where
+ the private key is in another environment and not directly accessible (e.g. HSM)
+ So the first step creates the request, then the signing is done outside this
+ object and the signature is then used to complete the request.
+
+
+ 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 Attr{{ IOSet }}
+
+ Attr { ATTRIBUTE:IOSet } ::= Sequence {
+ type ATTRIBUTE.&id({IOSet}),
+ values Set SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type})
+ }
+
+ see
+
+
+
+ Instantiate a Pkcs10CertificationRequest object with the necessary credentials.
+
+ Name of Sig Alg.
+ X509Name of subject eg OU="My unit." O="My Organisatioin" C="au"
+ Public Key to be included in cert reqest.
+ ASN1Set of Attributes.
+
+ After the object is constructed use the and finally the
+ SignRequest methods to finalize the request.
+
+
+
+ simply return the cert entry for the private key
+
+
+ Utility class for reencoding PKCS#12 files to definite length.
+
+
+ Just re-encode the outer layer of the PKCS#12 file to definite length encoding.
+
+ @param berPKCS12File - original PKCS#12 file
+ @return a byte array representing the DER encoding of the PFX structure
+ @throws IOException
+
+
+ Re-encode the PKCS#12 structure to definite length encoding at the inner layer
+ as well, recomputing the MAC accordingly.
+
+ @param berPKCS12File - original PKCS12 file.
+ @param provider - provider to use for MAC calculation.
+ @return a byte array representing the DER encoding of the PFX structure.
+ @throws IOException on parsing, encoding errors.
+
+
+
+ Returns the revocationDate.
+
+
+
+
+ Returns the certStatus.
+
+
+
+ Returns an immutable Set of X.509 attribute certificate
+ extensions that this PkixAttrCertChecker supports 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.
+
+
+ All X.509 attribute certificate extensions that a
+ PkixAttrCertChecker 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
+ PkixAttrCertChecker, or null if no
+ extensions are supported
+
+
+ Performs checks on the specified attribute certificate. Every handled
+ extension is rmeoved from the unresolvedCritExts
+ collection.
+
+ @param attrCert The attribute certificate to be checked.
+ @param certPath The certificate path which belongs to the attribute
+ certificate issuer public key certificate.
+ @param holderCertPath The certificate path which belongs to the holder
+ certificate.
+ @param unresolvedCritExts a Collection of OID strings
+ representing the current set of unresolved critical extensions
+ @throws CertPathValidatorException if the specified attribute certificate
+ does not pass the check.
+
+
+ Returns a clone of this object.
+
+ @return a copy of this PkixAttrCertChecker
+
+
+ Build and validate a CertPath using the given parameter.
+
+ @param params PKIXBuilderParameters object containing all information to
+ build the CertPath
+
+
+ CertPathValidatorSpi implementation for X.509 Attribute Certificates la RFC 3281.
+
+ @see org.bouncycastle.x509.ExtendedPkixParameters
+
+
+ Validates an attribute certificate with the given certificate path.
+
+
+ params must be an instance of
+ ExtendedPkixParameters.
+
+ The target constraints in the params must be an
+ X509AttrCertStoreSelector with at least the attribute
+ certificate criterion set. Obey that also target informations may be
+ necessary to correctly validate this attribute certificate.
+
+ The attribute certificate issuer must be added to the trusted attribute
+ issuers with {@link ExtendedPkixParameters#setTrustedACIssuers(Set)}.
+
+ @param certPath The certificate path which belongs to the attribute
+ certificate issuer public key certificate.
+ @param params The PKIX parameters.
+ @return A PKIXCertPathValidatorResult of the result of
+ validating the certPath.
+ @throws InvalidAlgorithmParameterException if params is
+ inappropriate for this validator.
+ @throws CertPathValidatorException if the verification fails.
+
+
+
+ Summary description for PkixBuilderParameters.
+
+
+
+
+ Summary description for PkixParameters.
+
+
+
+ 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.
+
+
+ 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.
+
+
+ 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
+
+
+ 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)
+
+
+ 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()
+
+
+ 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)
+
+
+ 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()
+
+
+ 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()
+
+
+ Returns the List of certification path checkers. Each PKIXCertPathChecker
+ in the returned IList is cloned to protect against subsequent modifications.
+
+ @return an immutable List of PKIXCertPathCheckers (may be empty, but not
+ null)
+
+ @see #setCertPathCheckers(java.util.List)
+
+
+ Adds a PKIXCertPathChecker to the list of certification
+ path checkers. See the {@link #setCertPathCheckers 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).
+
+
+ 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.
+
+
+ Sets the Bouncy Castle Stores for finding CRLs, certificates, attribute
+ certificates or cross certificates.
+
+ The IList is cloned.
+
+
+ @param stores A list of stores to use.
+ @see #getStores
+ @throws ClassCastException if an element of stores is not
+ a {@link Store}.
+
+
+ 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
+
+
+ Adds an 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()
+
+
+ Returns an IList of additional Bouncy Castle
+ Stores used for finding CRLs, certificates, attribute
+ certificates or cross certificates.
+
+ @return an immutable IList of additional Bouncy Castle
+ Stores. Never null.
+
+ @see #addAddionalStore(Store)
+
+
+ Returns an IList of Bouncy Castle
+ Stores used for finding CRLs, certificates, attribute
+ certificates or cross certificates.
+
+ @return an immutable IList of Bouncy Castle
+ Stores. Never null.
+
+ @see #setStores(IList)
+
+
+ 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.
+
+
+ Returns the required constraints on the target certificate or attribute
+ certificate. The constraints are returned as an instance of
+ IX509Selector. If null, no constraints are
+ defined.
+
+
+ The target certificate in a PKIX path may be a certificate or an
+ attribute certificate.
+
+ Note that the IX509Selector returned is cloned to protect
+ against subsequent modifications.
+
+ @return a IX509Selector specifying the constraints on the
+ target certificate or attribute certificate (or null)
+ @see #setTargetConstraints
+ @see X509CertStoreSelector
+ @see X509AttributeCertStoreSelector
+
+
+ Sets the required constraints on the target certificate or attribute
+ certificate. The constraints are specified as an instance of
+ IX509Selector. If null, no constraints are
+ defined.
+
+ The target certificate in a PKIX path may be a certificate or an
+ attribute certificate.
+
+ Note that the IX509Selector specified is cloned to protect
+ against subsequent modifications.
+
+
+ @param selector a IX509Selector specifying the constraints on
+ the target certificate or attribute certificate (or
+ null)
+ @see #getTargetConstraints
+ @see X509CertStoreSelector
+ @see X509AttributeCertStoreSelector
+
+
+ Returns the trusted attribute certificate issuers. If attribute
+ certificates is verified the trusted AC issuers must be set.
+
+ The returned ISet consists of TrustAnchors.
+
+ The returned ISet is immutable. Never null
+
+
+ @return Returns an immutable set of the trusted AC issuers.
+
+
+ Sets the trusted attribute certificate issuers. If attribute certificates
+ is verified the trusted AC issuers must be set.
+
+ The trustedACIssuers must be a ISet 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.
+
+
+ Returns the neccessary attributes which must be contained in an attribute
+ certificate.
+
+ The returned ISet is immutable and contains
+ Strings with the OIDs.
+
+
+ @return Returns the necessary AC attributes.
+
+
+ Sets the neccessary which must be contained in an attribute certificate.
+
+ The ISet 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.
+
+
+ Returns the attribute certificates which are not allowed.
+
+ The returned ISet is immutable and contains
+ Strings with the OIDs.
+
+
+ @return Returns the prohibited AC attributes. Is never null.
+
+
+ Sets the attribute certificates which are not allowed.
+
+ The ISet 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.
+
+
+ Returns the attribute certificate checker. The returned set contains
+ {@link PKIXAttrCertChecker}s and is immutable.
+
+ @return Returns the attribute certificate checker. Is never
+ null.
+
+
+ Sets the attribute certificate checkers.
+
+ All elements in the ISet 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.
+
+
+ Whether delta CRLs should be used for checking the revocation status.
+ Defaults to false.
+
+
+ The validity model.
+ @see #CHAIN_VALIDITY_MODEL
+ @see #PKIX_VALIDITY_MODEL
+
+
+ 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.
+
+
+ Returns an instance of PkixBuilderParameters.
+
+ 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 PkixBuilderParameters instance.
+
+
+
+ Excluded certificates are not used for building a certification path.
+
+ the excluded certificates.
+
+
+
+ Sets the excluded certificates which are not used for building a
+ certification path. If the ISet is null an
+ empty set is assumed.
+
+
+ The given set is cloned to protect it against subsequent modifications.
+
+ The excluded certificates to set.
+
+
+ Can alse handle ExtendedPKIXBuilderParameters and
+ PKIXBuilderParameters.
+
+ @param params Parameters to set.
+ @see org.bouncycastle.x509.ExtendedPKIXParameters#setParams(java.security.cert.PKIXParameters)
+
+
+ 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
+
+
+ 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
+
+ CertPath implementation for X.509 certificates.
+
+
+
+ @param certs
+
+
+ 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
+
+
+
+ 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
+
+
+
+ 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()
+
+
+ Returns the encoded form of this certification path, using
+ the default encoding.
+
+ @return the encoded bytes
+ @exception CertificateEncodingException if an encoding error occurs
+
+
+
+ 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
+
+
+
+ Return a DERObject containing the encoded certificate.
+
+ @param cert the X509Certificate object to be encoded
+
+ @return the DERObject
+
+
+
+ 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)
+
+
+
+
+ Returns the list of certificates in this certification
+ path.
+
+
+
+ Implements the PKIX CertPathBuilding algorithm for BouncyCastle.
+
+ @see CertPathBuilderSpi
+
+
+ Build and validate a CertPath using the given parameter.
+
+ @param params PKIXBuilderParameters object containing all information to
+ build the CertPath
+
+
+
+ Summary description for PkixCertPathBuilderException.
+
+
+
+
+ Summary description for PkixCertPathBuilderResult.
+
+
+
+
+ Summary description for PkixCertPathValidatorResult.
+
+
+
+ * 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
+ * PKIXCertPathCheckermust 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
+
+
+ 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
+
+
+ * 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
+
+
+ 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
+
+
+ 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
+
+
+ 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.
+
+ CertPathValidatorSpi implementation for X.509 Certificate validation a la RFC
+ 3280.
+
+
+
+ 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
+
+
+
+
+ Creates a PkixCertPathValidatorException with the given detail
+ message. A detail message is a String that describes this
+ particular exception.
+
+ the detail message
+
+
+
+ Creates a PkixCertPathValidatorException with the specified
+ detail message and cause.
+
+ the detail message
+ 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.)
+
+
+
+ Creates a PkixCertPathValidatorException with the specified
+ detail message, cause, certification path, and index.
+
+ the detail message (or null if none)
+ the cause (or null if none)
+ the certification path that was in the process of being
+ validated when the error was encountered
+ the index of the certificate in the certification path that *
+
+
+
+ Returns the detail message for this CertPathValidatorException.
+
+ the detail message, or null if neither the message nor cause were specified
+
+
+ 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)
+
+
+ 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
+
+
+
+ Summary description for PkixCertPathValidatorUtilities.
+
+
+
+
+ key usage bits
+
+
+
+
+ Search the given Set of TrustAnchor's for one that is the
+ issuer of the given X509 certificate.
+
+ the X509 certificate
+ a Set of TrustAnchor's
+ the TrustAnchor object if found or
+ null if not.
+
+ @exception
+
+
+
+ Returns the issuer of an attribute certificate or certificate.
+
+ The attribute certificate or certificate.
+ The issuer as X500Principal.
+
+
+ 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 Exception if DSA parameters cannot be inherited.
+
+
+
+ Return a Collection of all certificates or attribute certificates found
+ in the X509Store's that are matching the certSelect criteriums.
+
+ a {@link Selector} object that will be used to select
+ the certificates
+ a List containing only X509Store objects. These
+ are used to search for certificates.
+ a Collection of all found or
+ org.bouncycastle.x509.X509AttributeCertificate objects.
+ May be empty but never null.
+
+
+
+ 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 Exception if an exception occurs while processing.
+ @throws ClassCastException if issuerPrincipals does not
+ contain only X500Principals.
+
+
+ Fetches complete CRLs according to RFC 3280.
+
+ @param dp The distribution point for which the complete CRL
+ @param cert The X509Certificate or
+ {@link org.bouncycastle.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 Exception if an exception occurs while picking the CRLs
+ or no CRLs are found.
+
+
+ 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 Exception if an exception occurs while picking the delta
+ CRLs.
+
+
+ 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.
+
+ @exception Exception
+ if an error occurs.
+
+
+
+ Extract the value of the given extension, if it exists.
+
+ The extension object.
+ The object identifier to obtain.
+ Asn1Object
+ if the extension cannot be read.
+
+
+
+ crl checking
+ Return a Collection of all CRLs found in the X509Store's that are
+ matching the crlSelect criteriums.
+
+ a {@link X509CRLStoreSelector} object that will be used
+ to select the CRLs
+ a List containing only {@link org.bouncycastle.x509.X509Store
+ X509Store} objects. These are used to search for CRLs
+ a Collection of all found {@link X509CRL X509CRL} objects. May be
+ empty but never null.
+
+
+
+ Returns the intersection of the permitted IP ranges in
+ permitted with ip.
+
+ @param permitted A Set of permitted IP addresses with
+ their subnet mask as byte arrays.
+ @param ips The IP address with its subnet mask.
+ @return The Set of permitted IP ranges intersected with
+ ip.
+
+
+ Returns the union of the excluded IP ranges in excluded
+ with ip.
+
+ @param excluded A Set of excluded IP addresses with their
+ subnet mask as byte arrays.
+ @param ip The IP address with its subnet mask.
+ @return The Set of excluded IP ranges unified with
+ ip as byte arrays.
+
+
+ Calculates the union if two IP ranges.
+
+ @param ipWithSubmask1 The first IP address with its subnet mask.
+ @param ipWithSubmask2 The second IP address with its subnet mask.
+ @return A Set with the union of both addresses.
+
+
+ Calculates the interesction if two IP ranges.
+
+ @param ipWithSubmask1 The first IP address with its subnet mask.
+ @param ipWithSubmask2 The second IP address with its subnet mask.
+ @return A Set with the single IP address with its subnet
+ mask as a byte array or an empty Set.
+
+
+ Concatenates the IP address with its subnet mask.
+
+ @param ip The IP address.
+ @param subnetMask Its subnet mask.
+ @return The concatenated IP address with its subnet mask.
+
+
+ Splits the IP addresses and their subnet mask.
+
+ @param ipWithSubmask1 The first IP address with the subnet mask.
+ @param ipWithSubmask2 The second IP address with the subnet mask.
+ @return An array with two elements. Each element contains the IP address
+ and the subnet mask in this order.
+
+
+ Based on the two IP addresses and their subnet masks the IP range is
+ computed for each IP address - subnet mask pair and returned as the
+ minimum IP address and the maximum address of the range.
+
+ @param ip1 The first IP address.
+ @param subnetmask1 The subnet mask of the first IP address.
+ @param ip2 The second IP address.
+ @param subnetmask2 The subnet mask of the second IP address.
+ @return A array with two elements. The first/second element contains the
+ min and max IP address of the first/second IP address and its
+ subnet mask.
+
+
+ Checks if the IP ip is included in the permitted ISet
+ permitted.
+
+ @param permitted A Set of permitted IP addresses with
+ their subnet mask as byte arrays.
+ @param ip The IP address.
+ @throws PkixNameConstraintValidatorException
+ if the IP is not permitted.
+
+
+ Checks if the IP ip is included in the excluded ISet
+ excluded.
+
+ @param excluded A Set of excluded IP addresses with their
+ subnet mask as byte arrays.
+ @param ip The IP address.
+ @throws PkixNameConstraintValidatorException
+ if the IP is excluded.
+
+
+ Checks if the IP address ip is constrained by
+ constraint.
+
+ @param ip The IP address.
+ @param constraint The constraint. This is an IP address concatenated with
+ its subnetmask.
+ @return true if constrained, false
+ otherwise.
+
+
+ The common part of email1 and email2 is
+ added to the union union. If email1 and
+ email2 have nothing in common they are added both.
+
+ @param email1 Email address constraint 1.
+ @param email2 Email address constraint 2.
+ @param union The union.
+
+
+ The most restricting part from email1 and
+ email2 is added to the intersection intersect.
+
+ @param email1 Email address constraint 1.
+ @param email2 Email address constraint 2.
+ @param intersect The intersection.
+
+
+ Checks if the given GeneralName is in the permitted ISet.
+
+ @param name The GeneralName
+ @throws PkixNameConstraintValidatorException
+ If the name
+
+
+ Check if the given GeneralName is contained in the excluded ISet.
+
+ @param name The GeneralName.
+ @throws PkixNameConstraintValidatorException
+ If the name is
+ excluded.
+
+
+ Updates the permitted ISet of these name constraints with the intersection
+ with the given subtree.
+
+ @param permitted The permitted subtrees
+
+
+ Adds a subtree to the excluded ISet of these name constraints.
+
+ @param subtree A subtree with an excluded GeneralName.
+
+
+ Returns the maximum IP address.
+
+ @param ip1 The first IP address.
+ @param ip2 The second IP address.
+ @return The maximum IP address.
+
+
+ Returns the minimum IP address.
+
+ @param ip1 The first IP address.
+ @param ip2 The second IP address.
+ @return The minimum IP address.
+
+
+ Compares IP address ip1 with ip2. If ip1
+ is equal to ip2 0 is returned. If ip1 is bigger 1 is returned, -1
+ otherwise.
+
+ @param ip1 The first IP address.
+ @param ip2 The second IP address.
+ @return 0 if ip1 is equal to ip2, 1 if ip1 is bigger, -1 otherwise.
+
+
+ Returns the logical OR of the IP addresses ip1 and
+ ip2.
+
+ @param ip1 The first IP address.
+ @param ip2 The second IP address.
+ @return The OR of ip1 and ip2.
+
+
+ Stringifies an IPv4 or v6 address with subnet mask.
+
+ @param ip The IP with subnet mask.
+ @return The stringified IP address.
+
+
+
+ Summary description for PkixPolicyNode.
+
+
+
+ Constructors
+
+
+
+ This class helps to handle CRL revocation reasons mask. Each CRL handles a
+ certain set of revocation reasons.
+
+
+
+
+ Constructs are reason mask with the reasons.
+
+ The reasons.
+
+
+
+ A reason mask with no reason.
+
+
+
+
+ A mask with all revocation reasons.
+
+
+
+ Adds all reasons from the reasons mask to this mask.
+
+ @param mask The reasons mask to add.
+
+
+
+ Intersects this mask with the given reasons mask.
+
+ mask The mask to intersect with.
+ The intersection of this and teh given mask.
+
+
+
+ Returns true if the passed reasons mask has new reasons.
+
+ The reasons mask which should be tested for new reasons.
+ true if the passed reasons mask has new reasons.
+
+
+
+ Returns true if this reasons mask contains all possible
+ reasons.
+
+ true if this reasons mask contains all possible reasons.
+
+
+
+
+ Returns the reasons in this mask.
+
+
+
+ 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.
+
+
+ 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
+ g 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.
+
+
+ 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.
+
+
+ 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.
+
+
+ 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.
+
+
+ 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.
+
+
+ Checks if an attribute certificate is revoked.
+
+ @param attrCert Attribute certificate to check if it is revoked.
+ @param paramsPKIX PKIX parameters.
+ @param issuerCert The issuer certificate of the attribute certificate
+ attrCert.
+ @param validDate The date when the certificate revocation status should
+ be checked.
+ @param certPathCerts The certificates of the certification path to be
+ checked.
+
+ @throws CertPathValidatorException if the certificate is revoked or the
+ status cannot be checked or some error occurs.
+
+
+ Searches for a holder public key certificate and verifies its
+ certification path.
+
+ @param attrCert the attribute certificate.
+ @param pkixParams The PKIX parameters.
+ @return The certificate path of the holder certificate.
+ @throws Exception if
+
+
no public key certificate can be found although holder
+ information is given by an entity name or a base certificate
+ ID
+
support classes cannot be created
+
no certification path for the public key certificate can
+ be built
+
+
+
+
+ Checks a distribution point for revocation information for the
+ certificate attrCert.
+
+ @param dp The distribution point to consider.
+ @param attrCert The attribute certificate which should be checked.
+ @param paramsPKIX PKIX parameters.
+ @param validDate The date when the certificate revocation status should
+ be checked.
+ @param issuerCert Certificate to check if it is revoked.
+ @param reasonMask The reasons mask which is already checked.
+ @param certPathCerts The certificates of the certification path to be
+ checked.
+ @throws Exception if the certificate is revoked or the status
+ cannot be checked or some error occurs.
+
+
+
+ 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.
+
+
+
+
+ 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.
+
+
+
+ Note that the name constraints byte array supplied is cloned to protect
+ against subsequent modifications.
+
+ a trusted X509Certificate
+ 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.
+ if the specified X509Certificate is null
+
+
+
+ Creates an instance of TrustAnchor where the
+ most-trusted CA is specified as an X500Principal 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 the other constructors.
+
+ Note that the name constraints byte array supplied here is cloned to
+ protect against subsequent modifications.
+
+
+ the name of the most-trusted CA as X509Name
+ the public key of the most-trusted CA
+
+ 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.
+
+
+ if caPrincipal or pubKey is null
+
+
+
+
+ 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 X.500 distinguished name of the most-trusted CA in RFC
+ 2253 string format
+ the public key of the most-trusted CA
+ 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.
+ throws NullPointerException, IllegalArgumentException
+
+
+
+ Decode the name constraints and clone them if not null.
+
+
+
+
+ Returns a formatted string describing the TrustAnchor.
+
+ a formatted string describing the TrustAnchor
+
+
+
+ Returns the most-trusted CA certificate.
+
+
+
+
+ Returns the name of the most-trusted CA as an X509Name.
+
+
+
+
+ Returns the name of the most-trusted CA in RFC 2253 string format.
+
+
+
+
+ Returns the public key of the most-trusted CA.
+
+
+
+
+ Utility class for creating IBasicAgreement objects from their names/Oids
+
+
+
+
+ Cipher Utility class contains methods that can not be specifically grouped into other classes.
+
+
+
+
+ Returns a ObjectIdentifier for a give encoding.
+
+ A string representation of the encoding.
+ A DerObjectIdentifier, null if the Oid is not available.
+
+
+
+ Utility class for creating IDigest objects from their names/Oids
+
+
+
+
+ Returns a ObjectIdentifier for a given digest mechanism.
+
+ A string representation of the digest meanism.
+ A DerObjectIdentifier, null if the Oid is not available.
+
+
+
+ Utility class for creating HMac object from their names/Oids
+
+
+
+
+
+
+
+
+
+ Returns a ObjectIdentifier for a give encoding.
+
+ A string representation of the encoding.
+ A DerObjectIdentifier, null if the Oid is not available.
+
+
+ Use the specified instance of IRandomGenerator as random source.
+
+ This constructor performs no seeding of either the IRandomGenerator or the
+ constructed SecureRandom. It is the responsibility of the client to provide
+ proper seed material as necessary/appropriate for the given IRandomGenerator
+ implementation.
+
+ The source to generate all random bytes from.
+
+
+ base constructor.
+
+
+ create a SecurityUtilityException with the given message.
+
+ @param message the message to be carried with the exception.
+
+
+
+ Signer Utility class contains methods that can not be specifically grouped into other classes.
+
+
+
+
+ Returns a ObjectIdentifier for a give encoding.
+
+ A string representation of the encoding.
+ A DerObjectIdentifier, null if the Oid is not available.
+
+
+
+ Utility class for creating IWrapper objects from their names/Oids
+
+
+
+ Base class for an RFC 3161 Time Stamp Request.
+
+
+ Create a TimeStampRequest from the past in byte array.
+
+ @param req byte array containing the request.
+ @throws IOException if the request is malformed.
+
+
+ Create a TimeStampRequest from the past in input stream.
+
+ @param in input stream containing the request.
+ @throws IOException if the request is malformed.
+
+
+ Validate the timestamp request, checking the digest to see if it is of an
+ accepted type and whether it is of the correct length for the algorithm specified.
+
+ @param algorithms a set of string OIDS giving accepted algorithms.
+ @param policies if non-null a set of policies we are willing to sign under.
+ @param extensions if non-null a set of extensions we are willing to accept.
+ @throws TspException if the request is invalid, or processing fails.
+
+
+ return the ASN.1 encoded representation of this object.
+
+
+ Generator for RFC 3161 Time Stamp Request objects.
+
+
+ add a given extension field for the standard extensions tag (tag 3)
+ @throws IOException
+
+
+ add a given extension field for the standard extensions tag
+ The value parameter becomes the contents of the octet string associated
+ with the extension.
+
+
+ add a given extension field for the standard extensions tag (tag 3)
+ @throws IOException
+
+
+ add a given extension field for the standard extensions tag
+ The value parameter becomes the contents of the octet string associated
+ with the extension.
+
+
+ Base class for an RFC 3161 Time Stamp Response object.
+
+
+ Create a TimeStampResponse from a byte array containing an ASN.1 encoding.
+
+ @param resp the byte array containing the encoded response.
+ @throws TspException if the response is malformed.
+ @throws IOException if the byte array doesn't represent an ASN.1 encoding.
+
+
+ Create a TimeStampResponse from an input stream containing an ASN.1 encoding.
+
+ @param input the input stream containing the encoded response.
+ @throws TspException if the response is malformed.
+ @throws IOException if the stream doesn't represent an ASN.1 encoding.
+
+
+ Check this response against to see if it a well formed response for
+ the passed in request. Validation will include checking the time stamp
+ token if the response status is GRANTED or GRANTED_WITH_MODS.
+
+ @param request the request to be checked against
+ @throws TspException if the request can not match this response.
+
+
+ return the ASN.1 encoded representation of this object.
+
+
+ Generator for RFC 3161 Time Stamp Responses.
+
+
+ Return an appropriate TimeStampResponse.
+
+ If genTime is null a timeNotAvailable error response will be returned.
+
+ @param request the request this response is for.
+ @param serialNumber serial number for the response token.
+ @param genTime generation time for the response token.
+ @param provider provider to use for signature calculation.
+ @return
+ @throws NoSuchAlgorithmException
+ @throws NoSuchProviderException
+ @throws TSPException
+
+
+
+ Generate a TimeStampResponse with chosen status and FailInfoField.
+
+ @param status the PKIStatus to set.
+ @param failInfoField the FailInfoField to set.
+ @param statusString an optional string describing the failure.
+ @return a TimeStampResponse with a failInfoField and optional statusString
+ @throws TSPException in case the response could not be created
+
+
+ Validate the time stamp token.
+
+ To be valid the token must be signed by the passed in certificate and
+ the certificate must be the one referred to by the SigningCertificate
+ attribute included in the hashed attributes of the token. The
+ certificate must also have the ExtendedKeyUsageExtension with only
+ KeyPurposeID.IdKPTimeStamping and have been valid at the time the
+ timestamp was created.
+
+
+ A successful call to validate means all the above are true.
+
+
+
+ Return the underlying CmsSignedData object.
+
+ @return the underlying CMS structure.
+
+
+ Return a ASN.1 encoded byte stream representing the encoded object.
+
+ @throws IOException if encoding fails.
+
+
+ basic creation - only the default attributes will be included here.
+
+
+ create with a signer with extra signed/unsigned attributes.
+
+
+ @return the nonce value, null if there isn't one.
+
+
+ Recognised hash algorithms for the time stamp protocol.
+
+
+ Fetches the signature time-stamp attributes from a SignerInformation object.
+ Checks that the MessageImprint for each time-stamp matches the signature field.
+ (see RFC 3161 Appendix A).
+
+ @param signerInfo a SignerInformation to search for time-stamps
+ @return a collection of TimeStampToken objects
+ @throws TSPValidationException
+
+
+ Validate the passed in certificate as being of the correct type to be used
+ for time stamping. To be valid it must have an ExtendedKeyUsage extension
+ which has a key purpose identifier of id-kp-timeStamping.
+
+ @param cert the certificate of interest.
+ @throws TspValidationException if the certicate fails on one of the check points.
+
+
+
+ Return the digest algorithm using one of the standard JCA string
+ representations rather than the algorithm identifier (if possible).
+
+
+
+ Exception thrown if a TSP request or response fails to validate.
+
+ If a failure code is associated with the exception it can be retrieved using
+ the getFailureCode() method.
+
+
+ Return the failure code associated with this exception - if one is set.
+
+ @return the failure code if set, -1 otherwise.
+
+
+ General array utilities.
+
+
+
+ Are two arrays equal.
+
+ Left side.
+ Right side.
+ True if equal.
+
+
+
+ A constant time equals comparison - does not terminate early if
+ test will fail.
+
+ first array
+ second array
+ true if arrays equal, false otherwise.
+
+
+ BigInteger utilities.
+
+
+ Return the passed in value as an unsigned byte array.
+
+ @param value value to be converted.
+ @return a byte array without a leading zero byte if present in the signed encoding.
+
+
+ Return a random BigInteger not less than 'min' and not greater than 'max'
+
+ @param min the least value that may be generated
+ @param max the greatest value that may be generated
+ @param random the source of randomness
+ @return a random BigInteger value in the range [min,max]
+
+
+
+ Return the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC) for a given DateTime value.
+
+ A UTC DateTime value not before epoch.
+ Number of whole milliseconds after epoch.
+ 'dateTime' is before epoch.
+
+
+
+ Create a DateTime value from the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC).
+
+ Number of milliseconds since the epoch.
+ A UTC DateTime value
+
+
+
+ Return the current number of milliseconds since the Unix epoch (1 Jan., 1970 UTC).
+
+
+
+ encode the input data producing a base 64 encoded byte array.
+
+ @return a byte array containing the base 64 encoded data.
+
+
+ Encode the byte data to base 64 writing it to the given output stream.
+
+ @return the number of bytes produced.
+
+
+ Encode the byte data to base 64 writing it to the given output stream.
+
+ @return the number of bytes produced.
+
+
+ decode the base 64 encoded input data. It is assumed the input data is valid.
+
+ @return a byte array representing the decoded data.
+
+
+ decode the base 64 encoded string data - whitespace will be ignored.
+
+ @return a byte array representing the decoded data.
+
+
+ decode the base 64 encoded string data writing it to the given output stream,
+ whitespace characters will be ignored.
+
+ @return the number of bytes produced.
+
+
+ Encode and decode byte arrays (typically from binary to 7-bit ASCII
+ encodings).
+
+
+ encode the input data producing a base 64 output stream.
+
+ @return the number of bytes produced.
+
+
+ decode the base 64 encoded byte data writing it to the given output stream,
+ whitespace characters will be ignored.
+
+ @return the number of bytes produced.
+
+
+ decode the base 64 encoded string data writing it to the given output stream,
+ whitespace characters will be ignored.
+
+ @return the number of bytes produced.
+
+
+
+ A buffering class to allow translation from one format to another to
+ be done in discrete chunks.
+
+
+
+
+ Create a buffered Decoder.
+
+ The translater to use.
+ The size of the buffer.
+
+
+
+ Process one byte of data.
+
+ Data in.
+ Byte array for the output.
+ The offset in the output byte array to start writing from.
+ The amount of output bytes.
+
+
+
+ Process data from a byte array.
+
+ The input data.
+ Start position within input data array.
+ Amount of data to process from input data array.
+ Array to store output.
+ Position in output array to start writing from.
+ The amount of output bytes.
+
+
+
+ A class that allows encoding of data using a specific encoder to be processed in chunks.
+
+
+
+
+ Create.
+
+ The translator to use.
+ Size of the chunks.
+
+
+
+ Process one byte of data.
+
+ The byte.
+ An array to store output in.
+ Offset within output array to start writing from.
+
+
+
+
+ Process data from a byte array.
+
+ Input data Byte array containing data to be processed.
+ Start position within input data array.
+ Amount of input data to be processed.
+ Output data array.
+ Offset within output data array to start writing to.
+ The amount of data written.
+
+
+
+ Class to decode and encode Hex.
+
+
+
+ encode the input data producing a Hex encoded byte array.
+
+ @return a byte array containing the Hex encoded data.
+
+
+ encode the input data producing a Hex encoded byte array.
+
+ @return a byte array containing the Hex encoded data.
+
+
+ Hex encode the byte data writing it to the given output stream.
+
+ @return the number of bytes produced.
+
+
+ Hex encode the byte data writing it to the given output stream.
+
+ @return the number of bytes produced.
+
+
+ decode the Hex encoded input data. It is assumed the input data is valid.
+
+ @return a byte array representing the decoded data.
+
+
+ decode the Hex encoded string data - whitespace will be ignored.
+
+ @return a byte array representing the decoded data.
+
+
+ decode the Hex encoded string data writing it to the given output stream,
+ whitespace characters will be ignored.
+
+ @return the number of bytes produced.
+
+
+ encode the input data producing a Hex output stream.
+
+ @return the number of bytes produced.
+
+
+ decode the Hex encoded byte data writing it to the given output stream,
+ whitespace characters will be ignored.
+
+ @return the number of bytes produced.
+
+
+ decode the Hex encoded string data writing it to the given output stream,
+ whitespace characters will be ignored.
+
+ @return the number of bytes produced.
+
+
+
+ A hex translator.
+
+
+
+
+ Translator interface.
+
+
+
+
+ Return encoded block size.
+
+ 2
+
+
+
+ Encode some data.
+
+ Input data array.
+ Start position within input data array.
+ The amount of data to process.
+ The output data array.
+ The offset within the output data array to start writing from.
+ Amount of data encoded.
+
+
+
+ Returns the decoded block size.
+
+ 1
+
+
+
+ Decode data from a byte array.
+
+ The input data array.
+ Start position within input data array.
+ The amounty of data to process.
+ The output data array.
+ The position within the output data array to start writing from.
+ The amount of data written.
+
+
+ Convert binary data to and from UrlBase64 encoding. This is identical to
+ Base64 encoding, except that the padding character is "." and the other
+ non-alphanumeric characters are "-" and "_" instead of "+" and "/".
+
+ The purpose of UrlBase64 encoding is to provide a compact encoding of binary
+ data that is safe for use as an URL parameter. Base64 encoding does not
+ produce encoded values that are safe for use in URLs, since "/" can be
+ interpreted as a path delimiter; "+" is the encoded form of a space; and
+ "=" is used to separate a name from the corresponding value in an URL
+ parameter.
+
+
+
+ Encode the input data producing a URL safe base 64 encoded byte array.
+
+ @return a byte array containing the URL safe base 64 encoded data.
+
+
+ Encode the byte data writing it to the given output stream.
+
+ @return the number of bytes produced.
+
+
+ Decode the URL safe base 64 encoded input data - white space will be ignored.
+
+ @return a byte array representing the decoded data.
+
+
+ decode the URL safe base 64 encoded byte data writing it to the given output stream,
+ whitespace characters will be ignored.
+
+ @return the number of bytes produced.
+
+
+ decode the URL safe base 64 encoded string data - whitespace will be ignored.
+
+ @return a byte array representing the decoded data.
+
+
+ Decode the URL safe base 64 encoded string data writing it to the given output stream,
+ whitespace characters will be ignored.
+
+ @return the number of bytes produced.
+
+
+ Convert binary data to and from UrlBase64 encoding. This is identical to
+ Base64 encoding, except that the padding character is "." and the other
+ non-alphanumeric characters are "-" and "_" instead of "+" and "/".
+
+ The purpose of UrlBase64 encoding is to provide a compact encoding of binary
+ data that is safe for use as an URL parameter. Base64 encoding does not
+ produce encoded values that are safe for use in URLs, since "/" can be
+ interpreted as a path delimiter; "+" is the encoded form of a space; and
+ "=" is used to separate a name from the corresponding value in an URL
+ parameter.
+
+
+
+
+ A
+
+
+ A
+
+
+
+
+
+ Pipe all bytes from inStr to outStr, throwing StreamFlowException if greater
+ than limit bytes in inStr.
+
+
+ A
+
+
+ A
+
+
+ A
+
+ The number of bytes actually transferred, if not greater than limit
+
+
+
+ Validate the given IPv4 or IPv6 address.
+
+ @param address the IP address as a string.
+
+ @return true if a valid address, false otherwise
+
+
+ Validate the given IPv4 or IPv6 address and netmask.
+
+ @param address the IP address as a string.
+
+ @return true if a valid address with netmask, false otherwise
+
+
+ Validate the given IPv4 address.
+
+ @param address the IP address as a string.
+
+ @return true if a valid IPv4 address, false otherwise
+
+
+ Validate the given IPv6 address.
+
+ @param address the IP address as a string.
+
+ @return true if a valid IPv4 address, false otherwise
+
+
+ General string utilities.
+
+
+
+ Summary description for DeflaterOutputStream.
+
+
+
+
+ Summary description for DeflaterOutputStream.
+
+
+
+
+ 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
+ }
+
+
+
+
+ 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.
+
+
+ Returns the hash if an object digest info is used.
+
+ @return The hash or null if no object digest info is set.
+
+
+ Return any principal objects inside the attribute certificate holder entity names field.
+
+ @return an array of IPrincipal objects (usually X509Name), null if no entity names field is set.
+
+
+ Return the principals associated with the issuer attached to this holder
+
+ @return an array of principals, null if no BaseCertificateID is set.
+
+
+ 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.
+
+
+ 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.
+
+
+ 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.
+
+
+ Return the serial number associated with the issuer attached to this holder.
+
+ @return the certificate serial number, null if no BaseCertificateID is set.
+
+
+ Carrying class for an attribute certificate issuer.
+
+
+ Set the issuer directly with the ASN.1 structure.
+
+ @param issuer The issuer
+
+
+ Return any principal objects inside the attribute certificate issuer object.
+ An array of IPrincipal objects (usually X509Principal).
+
+
+ A high level authority key identifier.
+
+
+ Constructor which will take the byte[] returned from getExtensionValue()
+
+ @param encodedValue a DER octet encoded string with the extension structure in it.
+ @throws IOException on parsing errors.
+
+
+ Create an AuthorityKeyIdentifier using the passed in certificate's public
+ key, issuer and serial number.
+
+ @param certificate the certificate providing the information.
+ @throws CertificateParsingException if there is a problem processing the certificate
+
+
+ Create an AuthorityKeyIdentifier using just the hash of the
+ public key.
+
+ @param pubKey the key to generate the hash from.
+ @throws InvalidKeyException if there is a problem using the key.
+
+
+ A high level subject key identifier.
+
+
+ Constructor which will take the byte[] returned from getExtensionValue()
+
+ @param encodedValue a DER octet encoded string with the extension structure in it.
+ @throws IOException on parsing errors.
+
+
+ Interface for an X.509 Attribute Certificate.
+
+
+ Return the attributes contained in the attribute block in the certificate.
+ An array of attributes.
+
+
+ Return the attributes with the same type as the passed in oid.
+ The object identifier we wish to match.
+ An array of matched attributes, null if there is no match.
+
+
+ Return an ASN.1 encoded byte array representing the attribute certificate.
+ An ASN.1 encoded byte array.
+ If the certificate cannot be encoded.
+
+
+ The version number for the certificate.
+
+
+ The serial number for the certificate.
+
+
+ The UTC DateTime before which the certificate is not valid.
+
+
+ The UTC DateTime after which the certificate is not valid.
+
+
+ The holder of the certificate.
+
+
+ The issuer details for the certificate.
+
+
+
+ A utility class that will extract X509Principal objects from X.509 certificates.
+
+ Use this in preference to trying to recreate a principal from a string, not all
+ DNs are what they should be, so it's best to leave them encoded where they
+ can be.
+
+
+
+ Return the issuer of the given cert as an X509Principal.
+
+
+ Return the subject of the given cert as an X509Principal.
+
+
+ Return the issuer of the given CRL as an X509Principal.
+
+
+ This class is an Selector like implementation to select
+ attribute certificates from a given set of criteria.
+
+ @see org.bouncycastle.x509.X509AttributeCertificate
+ @see org.bouncycastle.x509.X509Store
+
+
+
+ Decides if the given attribute certificate should be selected.
+
+ The attribute certificate to be checked.
+ true if the object matches this selector.
+
+
+ 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)
+
+
+ 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.
+
+
+ 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)
+
+
+ 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)
+
+
+ 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)
+
+
+ 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.
+
+
+ Adds a collection with target groups criteria. If null is
+ given any will do.
+
+ The collection consists of GeneralName objects or byte[]
+ representing DER encoded GeneralNames.
+
+
+ @param names A collection of target groups.
+ @throws IOException if a parsing error occurs.
+ @see #AddTargetGroup(byte[])
+ @see #AddTargetGroup(GeneralName)
+
+
+ Gets the target groups. 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 groups.
+ @see #setTargetGroups(Collection)
+
+
+ The attribute certificate which must be matched.
+ If null is given, any will do.
+
+
+ The criteria for validity
+ If null is given any will do.
+
+
+ The holder.
+ If null is given any will do.
+
+
+ The issuer.
+ If null is given any will do.
+
+
+ The serial number.
+ If null is given any will do.
+
+
+
+ This class is an IX509Selector implementation to select
+ certificate pairs, which are e.g. used for cross certificates. The set of
+ criteria is given from two X509CertStoreSelector objects,
+ each of which, if present, must match the respective component of a pair.
+
+
+
+
+ Decides if the given certificate pair should be selected. If
+ obj is not a X509CertificatePair, this method
+ returns false.
+
+ The X509CertificatePair to be tested.
+ true if the object matches this selector.
+
+
+ The certificate pair which is used for testing on equality.
+
+
+ The certificate selector for the forward part.
+
+
+ The certificate selector for the reverse part.
+
+
+ A simple collection backed store.
+
+
+ Basic constructor.
+
+ @param collection - initial contents for the store, this is copied.
+
+
+ Return the matches in the collection for the passed in selector.
+
+ @param selector the selector to match against.
+ @return a possibly empty collection of matching objects.
+
+
+ This class contains a collection for collection based X509Stores.
+
+
+
+ Constructor.
+
+ The collection is copied.
+
+
+ The collection containing X.509 object types.
+ If collection is null.
+
+
+ Returns a copy of the ICollection.
+
+
+ Returns a formatted string describing the parameters.
+
+
+
+ An ICollection of X509Name objects
+
+
+
+ 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 IX509AttributeCertificate being checked (or
+ null)
+ @see #getAttrCertificateChecking()
+
+
+ If true only complete CRLs are returned. Defaults to
+ false.
+
+ @return true if only complete CRLs are returned.
+
+
+ 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.
+
+
+ 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(bool)}.
+
+ @param issuingDistributionPoint The issuing distribution point to set.
+ This is the DER encoded OCTET STRING extension value.
+ @see #getIssuingDistributionPoint()
+
+
+ Whether 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.
+
+
+ The maximum base CRL number. Defaults to null.
+
+ @return Returns the maximum base CRL number.
+ @see #setMaxBaseCRLNumber(BigInteger)
+
+
+
+ A factory to produce Public Key Info Objects.
+
+
+
+
+ Create a Subject Public Key Info object for a given public key.
+
+ One of ElGammalPublicKeyParameters, DSAPublicKeyParameter, DHPublicKeyParameters, RsaKeyParameters or ECPublicKeyParameters
+ A subject public key info object.
+ Throw exception if object provided is not one of the above.
+
+
+
+ Create loading data from byte array.
+
+
+
+
+
+ Create loading data from byte array.
+
+
+
+
+ Generates a certificate object and initializes it with the data
+ read from the input stream inStream.
+
+
+ Returns a (possibly empty) collection view of the certificates
+ read from the given input stream inStream.
+
+
+ Class for carrying the values in an X.509 Attribute.
+
+
+ @param at an object representing an attribute.
+
+
+ Create an X.509 Attribute with the type given by the passed in oid and
+ the value represented by an ASN.1 Set containing value.
+
+ @param oid type of the attribute
+ @param value value object to go into the atribute's value set.
+
+
+ Create an X.59 Attribute with the type given by the passed in oid and the
+ value represented by an ASN.1 Set containing the objects in value.
+
+ @param oid type of the attribute
+ @param value vector of values to go in the attribute's value set.
+
+
+
+ An Object representing an X509 Certificate.
+ Has static methods for loading Certificates encoded in many forms that return X509Certificate Objects.
+
+
+
+
+ Return true if the nominated time is within the start and end times nominated on the certificate.
+
+ The time to test validity against.
+ True if certificate is valid for nominated time.
+
+
+
+ Checks if the current date is within certificate's validity period.
+
+
+
+
+ Checks if the given date is within certificate's validity period.
+
+ if the certificate is expired by given date
+ if the certificate is not yet valid on given date
+
+
+
+ Return the Der encoded TbsCertificate data.
+ This is the certificate component less the signature.
+ To Get the whole certificate call the GetEncoded() member.
+
+ A byte array containing the Der encoded Certificate component.
+
+
+
+ The signature.
+
+ A byte array containg the signature of the certificate.
+
+
+
+ Get the signature algorithms parameters. (EG DSA Parameters)
+
+ A byte array containing the Der encoded version of the parameters or null if there are none.
+
+
+
+ Get a key usage guidlines.
+
+
+
+
+ Get the public key of the subject of the certificate.
+
+ The public key parameters.
+
+
+
+ Return a Der encoded version of this certificate.
+
+ A byte array.
+
+
+
+ Verify the certificate's signature using the nominated public key.
+
+ An appropriate public key parameter object, RsaPublicKeyParameters, DsaPublicKeyParameters or ECDsaPublicKeyParameters
+ True if the signature is valid.
+ If key submitted is not of the above nominated types.
+
+
+
+ Return true if the current time is within the start and end times nominated on the certificate.
+
+ true id certificate is valid for the current time.
+
+
+
+ Return the certificate's version.
+
+ An integer whose value Equals the version of the cerficate.
+
+
+
+ Return a BigInteger containing the serial number.
+
+ The Serial number.
+
+
+
+ Get the Issuer Distinguished Name. (Who signed the certificate.)
+
+ And X509Object containing name and value pairs.
+
+
+
+ Get the subject of this certificate.
+
+ An X509Name object containing name and value pairs.
+
+
+
+ The time that this certificate is valid from.
+
+ A DateTime object representing that time in the local time zone.
+
+
+
+ The time that this certificate is valid up to.
+
+ A DateTime object representing that time in the local time zone.
+
+
+
+ A meaningful version of the Signature Algorithm. (EG SHA1WITHRSA)
+
+ A sting representing the signature algorithm.
+
+
+
+ Get the Signature Algorithms Object ID.
+
+ A string containg a '.' separated object id.
+
+
+
+ Get the issuers UID.
+
+ A DerBitString.
+
+
+
+ Get the subjects UID.
+
+ A DerBitString.
+
+
+
+ This class contains a cross certificate pair. Cross certificates pairs may
+ contain two cross signed certificates from two CAs. A certificate from the
+ other CA to this CA is contained in the forward certificate, the certificate
+ from this CA to the other CA is contained in the reverse certificate.
+
+
+
+ Constructor
+ Certificate from the other CA to this CA.
+ Certificate from this CA to the other CA.
+
+
+ Constructor from a ASN.1 CertificatePair structure.
+ The CertificatePair ASN.1 object.
+
+
+ Returns the certificate from the other CA to this CA.
+
+
+ Returns the certificate from this CA to the other CA.
+
+
+ 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.
+
+
+
+ Create loading data from byte array.
+
+
+
+
+
+ Create loading data from byte array.
+
+
+
+
+ Generates a certificate object and initializes it with the data
+ read from the input stream inStream.
+
+
+ Returns a (possibly empty) collection view of the certificates
+ read from the given input stream inStream.
+
+
+
+ Create loading data from byte array.
+
+
+
+
+
+ Create loading data from byte array.
+
+
+
+
+ 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)
+
+
+ Returns a string representation of this CRL.
+
+ @return a string representation of this CRL.
+
+
+ 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.
+
+
+ The following extensions are listed in RFC 2459 as relevant to CRL Entries
+
+ ReasonCode Hode Instruction Code Invalidity Date Certificate Issuer
+ (critical)
+
+
+ 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
+ TbsCertificateList.CrlEntry object.
+ @param isIndirect
+ true if the corresponding CRL is a indirect
+ CRL.
+ @param previousCertificateIssuer
+ Certificate issuer of the previous CrlEntry.
+
+
+
+ Create loading data from byte array.
+
+
+
+
+
+ Create loading data from byte array.
+
+
+
+
+ Generates a certificate revocation list (CRL) object and initializes
+ it with the data read from the input stream inStream.
+
+
+ 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 significant field being crls. In particular the signature
+ and the contents are ignored.
+
+
+ A holding class for constructing an X509 Key Usage extension.
+
+
+
+
+ Basic constructor.
+
+ @param usage - the bitwise OR of the Key Usage flags giving the
+ allowed uses for the key.
+ e.g. (X509KeyUsage.keyEncipherment | X509KeyUsage.dataEncipherment)
+
+
+ Return the digest algorithm using one of the standard JCA string
+ representations rather than the algorithm identifier (if possible).
+
+
+
+ Class to Generate X509V1 Certificates.
+
+
+
+
+ Default Constructor.
+
+
+
+
+ Reset the generator.
+
+
+
+
+ Set the certificate's serial number.
+
+ Make serial numbers long, if you have no serial number policy make sure the number is at least 16 bytes of secure random data.
+ You will be surprised how ugly a serial number collision can get.
+ The serial number.
+
+
+
+ Set the issuer distinguished name.
+ The issuer is the entity whose private key is used to sign the certificate.
+
+ The issuers DN.
+
+
+
+ Set the date that this certificate is to be valid from.
+
+
+
+
+
+ Set the date after which this certificate will no longer be valid.
+
+
+
+
+
+ Set the subject distinguished name.
+ The subject describes the entity associated with the public key.
+
+
+
+
+
+ Set the public key that this certificate identifies.
+
+
+
+
+
+ Set the signature algorithm that will be used to sign this certificate.
+ This can be either a name or an OID, names are treated as case insensitive.
+
+ string representation of the algorithm name
+
+
+
+ Generate a new X509Certificate.
+
+ The private key of the issuer used to sign this certificate.
+ An X509Certificate.
+
+
+
+ Generate a new X509Certificate specifying a SecureRandom instance that you would like to use.
+
+ The private key of the issuer used to sign this certificate.
+ The Secure Random you want to use.
+ An X509Certificate.
+
+
+
+ Allows enumeration of the signature names supported by the generator.
+
+
+
+ An implementation of a version 2 X.509 Attribute Certificate.
+
+
+ Class to produce an X.509 Version 2 AttributeCertificate.
+
+
+ Reset the generator
+
+
+ Set the Holder of this Attribute Certificate.
+
+
+ Set the issuer.
+
+
+ Set the serial number for the certificate.
+
+
+
+ Set the signature algorithm. This can be either a name or an OID, names
+ are treated as case insensitive.
+
+ The algorithm name.
+
+
+ Add an attribute.
+
+
+ Add a given extension field for the standard extensions tag.
+
+
+
+ Add a given extension field for the standard extensions tag.
+ The value parameter becomes the contents of the octet string associated
+ with the extension.
+
+
+
+
+ Generate an X509 certificate, based on the current issuer and subject.
+
+
+
+
+ Generate an X509 certificate, based on the current issuer and subject,
+ using the supplied source of randomness, if required.
+
+
+
+
+ Allows enumeration of the signature names supported by the generator.
+
+
+
+ class to produce an X.509 Version 2 CRL.
+
+
+ reset the generator
+
+
+ Set the issuer distinguished name - the issuer is the entity whose private key is used to sign the
+ certificate.
+
+
+ Reason being as indicated by CrlReason, i.e. CrlReason.KeyCompromise
+ or 0 if CrlReason is not to be used
+
+
+
+ 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
+
+
+
+ Add a CRL entry with extensions.
+
+
+
+ Add the CRLEntry objects contained in a previous CRL.
+
+ @param other the X509Crl to source the other entries from.
+
+
+ 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.
+
+
+ add a given extension field for the standard extensions tag (tag 0)
+
+
+ add a given extension field for the standard extensions tag (tag 0)
+
+
+ add a given extension field for the standard extensions tag (tag 0)
+
+
+ add a given extension field for the standard extensions tag (tag 0)
+
+
+ Generate an X509 CRL, based on the current issuer and subject.
+ The key used for signing.
+
+
+ Generate an X509 CRL, based on the current issuer and subject.
+ The key used for signing.
+ A user-defined source of randomness.
+
+
+
+ Allows enumeration of the signature names supported by the generator.
+
+
+
+
+ A class to Generate Version 3 X509Certificates.
+
+
+
+
+ Reset the Generator.
+
+
+
+
+ Set the certificate's serial number.
+
+ Make serial numbers long, if you have no serial number policy make sure the number is at least 16 bytes of secure random data.
+ You will be surprised how ugly a serial number collision can Get.
+ The serial number.
+
+
+
+ Set the distinguished name of the issuer.
+ The issuer is the entity which is signing the certificate.
+
+ The issuer's DN.
+
+
+
+ Set the date that this certificate is to be valid from.
+
+
+
+
+
+ Set the date after which this certificate will no longer be valid.
+
+
+
+
+
+ Set the DN of the entity that this certificate is about.
+
+
+
+
+
+ Set the public key that this certificate identifies.
+
+
+
+
+
+ Set the signature algorithm that will be used to sign this certificate.
+
+
+
+
+
+ Set the subject unique ID - note: it is very rare that it is correct to do this.
+
+
+
+
+
+ Set the issuer unique ID - note: it is very rare that it is correct to do this.
+
+
+
+
+
+ Add a given extension field for the standard extensions tag (tag 3).
+
+ string containing a dotted decimal Object Identifier.
+ Is it critical.
+ The value.
+
+
+
+ Add an extension to this certificate.
+
+ Its Object Identifier.
+ Is it critical.
+ The value.
+
+
+
+ Add an extension using a string with a dotted decimal OID.
+
+ string containing a dotted decimal Object Identifier.
+ Is it critical.
+ byte[] containing the value of this extension.
+
+
+
+ Add an extension to this certificate.
+
+ Its Object Identifier.
+ Is it critical.
+ byte[] containing the value of this extension.
+
+
+
+ Add a given extension field for the standard extensions tag (tag 3),
+ copying the extension value from another certificate.
+
+
+
+ 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.
+
+
+
+ Generate an X509Certificate.
+
+ The private key of the issuer that is signing this certificate.
+ An X509Certificate.
+
+
+
+ Generate an X509Certificate using your own SecureRandom.
+
+ The private key of the issuer that is signing this certificate.
+ You Secure Random instance.
+ An X509Certificate.
+
+
+
+ Allows enumeration of the signature names supported by the generator.
+
+
+
+
diff --git a/Crypto/doc/wp7/crypto.xml b/Crypto/doc/wp7/crypto.xml
new file mode 100644
index 000000000..f1cf2f391
--- /dev/null
+++ b/Crypto/doc/wp7/crypto.xml
@@ -0,0 +1,19296 @@
+
+
+
+ crypto
+
+
+
+ Base class for both the compress and decompress classes.
+ Holds common arrays, and static data.
+
+ @author Keiron Liddle
+
+
+ An input stream that decompresses from the BZip2 format (with the file
+ header chars) to be read as any other stream.
+
+ @author Keiron Liddle
+
+ NB: note this class has been modified to read the leading BZ from the
+ start of the BZIP2 stream to make it compatible with other PGP programs.
+
+
+ An output stream that compresses into the BZip2 format (with the file
+ header chars) into another stream.
+
+ @author Keiron Liddle
+
+ TODO: Update to BZip2 1.0.1
+ NB: note this class has been modified to add a leading BZ to the
+ start of the BZIP2 stream to make it compatible with other PGP programs.
+
+
+
+ modified by Oliver Merkel, 010128
+
+
+
+ A simple class the hold and calculate the CRC for sanity checking
+ of the data.
+
+ @author Keiron Liddle
+
+
+ Return the DER encoding of the object, null if the DER encoding can not be made.
+
+ @return a DER byte array, null otherwise.
+
+
+ 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.
+
+
+ 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.
+
+
+ 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.
+
+
+ build an object given its tag and the number of bytes to construct it from.
+
+
+ A Null object.
+
+
+ Create a base ASN.1 object from a byte array.
+ The byte array to parse.
+ The base ASN.1 object represented by the byte array.
+ If there is a problem parsing the data.
+
+
+ Read a base ASN.1 object from a stream.
+ The stream to parse.
+ The base ASN.1 object represented by the byte array.
+ If there is a problem parsing the data.
+
+
+ return an Octet string from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ return an Octet string from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ @param string the octets making up the octet string.
+
+
+ return an Asn1Sequence from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Return an ASN1 sequence from a tagged object. There is a special
+ case here, if an object appears to have been explicitly tagged on
+ reading but we were expecting it to be implicitly tagged in the
+ normal course of events it indicates that we lost the surrounding
+ sequence - so we need to add it back (this will happen if the tagged
+ object is a sequence that contains other sequences). If you are
+ dealing with implicitly tagged sequences you really should
+ be using this method.
+
+ @param obj the tagged object.
+ @param explicitly true if the object is meant to be explicitly tagged,
+ false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ return the object at the sequence position indicated by index.
+
+ @param index the sequence number (starting at zero) of the object
+ @return the object at the sequence position indicated by index.
+
+
+ return an ASN1Set from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Return an ASN1 set from a tagged object. There is a special
+ case here, if an object appears to have been explicitly tagged on
+ reading but we were expecting it to be implicitly tagged in the
+ normal course of events it indicates that we lost the surrounding
+ set - so we need to add it back (this will happen if the tagged
+ object is a sequence that contains other sequences). If you are
+ dealing with implicitly tagged sets you really should
+ be using this method.
+
+ @param obj the tagged object.
+ @param explicitly true if the object is meant to be explicitly tagged
+ false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ return true if a <= b (arrays are assumed padded with zeros).
+
+
+ return the object at the set position indicated by index.
+
+ @param index the set number (starting at zero) of the object
+ @return the object at the set position indicated by index.
+
+
+ ASN.1 TaggedObject - in ASN.1 notation this is any object preceded by
+ a [n] where n is some number - these are assumed to follow the construction
+ rules (as with sequences).
+
+
+ @param tagNo the tag number for this object.
+ @param obj the tagged object.
+
+
+ @param explicitly true if the object is explicitly tagged.
+ @param tagNo the tag number for this object.
+ @param obj the tagged object.
+
+
+ return whether or not the object may be explicitly tagged.
+
+ Note: if the object has been read from an input stream, the only
+ time you can be sure if isExplicit is returning the true state of
+ affairs is if it returns false. An implicitly tagged object may appear
+ to be explicitly tagged, so you need to understand the context under
+ which the reading was done as well, see GetObject below.
+
+
+ return whatever was following the tag.
+
+ Note: tagged objects are generally context dependent if you're
+ trying to extract a tagged object you should be going via the
+ appropriate GetInstance method.
+
+
+ Return the object held in this tagged object as a parser assuming it has
+ the type of the passed in tag. If the object doesn't have a parser
+ associated with it, the base object is returned.
+
+
+ Base class for an application specific object
+
+
+ Return the enclosed object assuming explicit tagging.
+
+ @return the resulting object
+ @throws IOException if reconstruction fails.
+
+
+ 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.
+
+
+ A BER Null object.
+
+
+ A Null object.
+
+
+ The octets making up the octet string.
+
+
+ convert a vector of octet strings into a single byte string
+
+
+ The octets making up the octet string.
+
+
+ return the DER octets that make up this string.
+
+
+ create an empty sequence
+
+
+ create a sequence containing one object
+
+
+ create a sequence containing a vector of objects.
+
+
+ create an empty sequence
+
+
+ create a sequence containing one object
+
+
+ create a sequence containing a vector of objects.
+
+
+ A Der encoded set object
+
+
+ create an empty set
+
+
+ @param obj - a single object that makes up the set.
+
+
+ @param v - a vector of objects making up the set.
+
+
+ create an empty sequence
+
+
+ create a set containing one object
+
+
+ create a set containing a vector of objects.
+
+
+ BER TaggedObject - in ASN.1 notation this is any object preceded by
+ a [n] where n is some number - these are assumed to follow the construction
+ rules (as with sequences).
+
+
+ DER TaggedObject - in ASN.1 notation this is any object preceded by
+ a [n] where n is some number - these are assumed to follow the construction
+ rules (as with sequences).
+
+
+ @param tagNo the tag number for this object.
+ @param obj the tagged object.
+
+
+ @param explicitly true if an explicitly tagged object.
+ @param tagNo the tag number for this object.
+ @param obj the tagged object.
+
+
+ create an implicitly tagged object that contains a zero
+ length sequence.
+
+
+ @param tagNo the tag number for this object.
+ @param obj the tagged object.
+
+
+ @param explicitly true if an explicitly tagged object.
+ @param tagNo the tag number for this object.
+ @param obj the tagged object.
+
+
+ create an implicitly tagged object that contains a zero
+ length sequence.
+
+
+
+ CAKeyUpdAnnContent ::= SEQUENCE {
+ oldWithNew CmpCertificate, -- old pub signed with new priv
+ newWithOld CmpCertificate, -- new pub signed with old priv
+ newWithNew CmpCertificate -- new pub signed with new priv
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ CertConfirmContent ::= SEQUENCE OF CertStatus
+
+ @return a basic ASN.1 object representation.
+
+
+
+ CertifiedKeyPair ::= SEQUENCE {
+ certOrEncCert CertOrEncCert,
+ privateKey [0] EncryptedValue OPTIONAL,
+ -- see [CRMF] for comment on encoding
+ publicationInfo [1] PKIPublicationInfo OPTIONAL
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+ Marker interface for CHOICE objects - if you implement this in a roll-your-own
+ object, any attempt to tag the object implicitly will convert the tag to an
+ explicit one as the encoding rules require.
+
+ If you use this interface your class should also implement the getInstance
+ pattern which takes a tag object and the tagging mode used.
+
+ @return a basic ASN.1 object representation.
+
+
+
+ CertResponse ::= SEQUENCE {
+ certReqId INTEGER,
+ -- to match this response with corresponding request (a value
+ -- of -1 is to be used if certReqId is not specified in the
+ -- corresponding request)
+ status PKIStatusInfo,
+ certifiedKeyPair CertifiedKeyPair OPTIONAL,
+ rspInfo OCTET STRING OPTIONAL
+ -- analogous to the id-regInfo-utf8Pairs string defined
+ -- for regInfo in CertReqMsg [CRMF]
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ CertStatus ::= SEQUENCE {
+ certHash OCTET STRING,
+ -- the hash of the certificate, using the same hash algorithm
+ -- as is used to create and verify the certificate signature
+ certReqId INTEGER,
+ -- to match this confirmation with the corresponding req/rep
+ statusInfo PKIStatusInfo OPTIONAL
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ Challenge ::= SEQUENCE {
+ owf AlgorithmIdentifier OPTIONAL,
+
+ -- MUST be present in the first Challenge; MAY be omitted in
+ -- any subsequent Challenge in POPODecKeyChallContent (if
+ -- omitted, then the owf used in the immediately preceding
+ -- Challenge is to be used).
+
+ witness OCTET STRING,
+ -- the result of applying the one-way function (owf) to a
+ -- randomly-generated INTEGER, A. [Note that a different
+ -- INTEGER MUST be used for each Challenge.]
+ challenge OCTET STRING
+ -- the encryption (under the public key for which the cert.
+ -- request is being made) of Rand, where Rand is specified as
+ -- Rand ::= SEQUENCE {
+ -- int INTEGER,
+ -- - the randomly-generated INTEGER A (above)
+ -- sender GeneralName
+ -- - the sender's name (as included in PKIHeader)
+ -- }
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+ Note: the addition of attribute certificates is a BC extension.
+
+
+
+ @return a basic ASN.1 object representation.
+
+
+
+ GenMsgContent ::= SEQUENCE OF InfoTypeAndValue
+
+ @return a basic ASN.1 object representation.
+
+
+
+ GenRepContent ::= SEQUENCE OF InfoTypeAndValue
+
+ @return a basic ASN.1 object representation.
+
+
+ Example InfoTypeAndValue contents include, but are not limited
+ to, the following (un-comment in this ASN.1 module and use as
+ appropriate for a given environment):
+
+ @return a basic ASN.1 object representation.
+
+
+
+ OobCertHash ::= SEQUENCE {
+ hashAlg [0] AlgorithmIdentifier OPTIONAL,
+ certId [1] CertId OPTIONAL,
+ hashVal BIT STRING
+ -- hashVal is calculated over the Der encoding of the
+ -- self-signed certificate with the identifier certID.
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ PbmParameter ::= SEQUENCE {
+ salt OCTET STRING,
+ -- note: implementations MAY wish to limit acceptable sizes
+ -- of this string to values appropriate for their environment
+ -- in order to reduce the risk of denial-of-service attacks
+ owf AlgorithmIdentifier,
+ -- AlgId for a One-Way Function (SHA-1 recommended)
+ iterationCount INTEGER,
+ -- number of times the OWF is applied
+ -- note: implementations MAY wish to limit acceptable sizes
+ -- of this integer to values appropriate for their environment
+ -- in order to reduce the risk of denial-of-service attacks
+ mac AlgorithmIdentifier
+ -- the MAC AlgId (e.g., DES-MAC, Triple-DES-MAC [PKCS11],
+ } -- or HMAC [RFC2104, RFC2202])
+
+ @return a basic ASN.1 object representation.
+
+
+ Creates a new PkiBody.
+ @param type one of the TYPE_* constants
+ @param content message content
+
+
+
+ @return a basic ASN.1 object representation.
+
+
+
+ PkiConfirmContent ::= NULL
+
+ @return a basic ASN.1 object representation.
+
+
+
+ PKIFailureInfo ::= BIT STRING {
+ badAlg (0),
+ -- unrecognized or unsupported Algorithm Identifier
+ badMessageCheck (1), -- integrity check failed (e.g., signature did not verify)
+ badRequest (2),
+ -- transaction not permitted or supported
+ badTime (3), -- messageTime was not sufficiently close to the system time, as defined by local policy
+ badCertId (4), -- no certificate could be found matching the provided criteria
+ badDataFormat (5),
+ -- the data submitted has the wrong format
+ wrongAuthority (6), -- the authority indicated in the request is different from the one creating the response token
+ incorrectData (7), -- the requester's data is incorrect (for notary services)
+ missingTimeStamp (8), -- when the timestamp is missing but should be there (by policy)
+ badPOP (9) -- the proof-of-possession failed
+ timeNotAvailable (14),
+ -- the TSA's time source is not available
+ unacceptedPolicy (15),
+ -- the requested TSA policy is not supported by the TSA
+ unacceptedExtension (16),
+ -- the requested extension is not supported by the TSA
+ addInfoNotAvailable (17)
+ -- the additional information requested could not be understood
+ -- or is not available
+ systemFailure (25)
+ -- the request cannot be handled due to system failure
+
+
+
+ basic interface for Der string objects.
+
+
+ return the correct number of pad bits for a bit string defined in
+ a 32 bit constant
+
+
+ return the correct number of bytes for a bit string defined in
+ a 32 bit constant
+
+
+ return a Bit string from the passed in object
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return a Bit string from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ @param data the octets making up the bit string.
+ @param padBits the number of extra bits at the end of the string.
+
+
+ @return the value of the bit string as an int (truncating if necessary)
+
+
+ Basic constructor.
+
+
+
+ PkiFreeText ::= SEQUENCE SIZE (1..MAX) OF UTF8String
+
+
+
+ Return the number of string elements present.
+
+ @return number of elements present.
+
+
+ Return the UTF8STRING at index.
+
+ @param index index of the string of interest
+ @return the string at index.
+
+
+ Value for a "null" recipient or sender.
+
+
+
+ PkiHeader ::= SEQUENCE {
+ pvno INTEGER { cmp1999(1), cmp2000(2) },
+ sender GeneralName,
+ -- identifies the sender
+ recipient GeneralName,
+ -- identifies the intended recipient
+ messageTime [0] GeneralizedTime OPTIONAL,
+ -- time of production of this message (used when sender
+ -- believes that the transport will be "suitable"; i.e.,
+ -- that the time will still be meaningful upon receipt)
+ protectionAlg [1] AlgorithmIdentifier OPTIONAL,
+ -- algorithm used for calculation of protection bits
+ senderKID [2] KeyIdentifier OPTIONAL,
+ recipKID [3] KeyIdentifier OPTIONAL,
+ -- to identify specific keys used for protection
+ transactionID [4] OCTET STRING OPTIONAL,
+ -- identifies the transaction; i.e., this will be the same in
+ -- corresponding request, response, certConf, and PKIConf
+ -- messages
+ senderNonce [5] OCTET STRING OPTIONAL,
+ recipNonce [6] OCTET STRING OPTIONAL,
+ -- nonces used to provide replay protection, senderNonce
+ -- is inserted by the creator of this message; recipNonce
+ -- is a nonce previously inserted in a related message by
+ -- the intended recipient of this message
+ freeText [7] PKIFreeText OPTIONAL,
+ -- this may be used to indicate context-specific instructions
+ -- (this field is intended for human consumption)
+ generalInfo [8] SEQUENCE SIZE (1..MAX) OF
+ InfoTypeAndValue OPTIONAL
+ -- this may be used to convey context-specific information
+ -- (this field not primarily intended for human consumption)
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ PKIHeader ::= SEQUENCE {
+ pvno INTEGER { cmp1999(1), cmp2000(2) },
+ sender GeneralName,
+ -- identifies the sender
+ recipient GeneralName,
+ -- identifies the intended recipient
+ messageTime [0] GeneralizedTime OPTIONAL,
+ -- time of production of this message (used when sender
+ -- believes that the transport will be "suitable"; i.e.,
+ -- that the time will still be meaningful upon receipt)
+ protectionAlg [1] AlgorithmIdentifier OPTIONAL,
+ -- algorithm used for calculation of protection bits
+ senderKID [2] KeyIdentifier OPTIONAL,
+ recipKID [3] KeyIdentifier OPTIONAL,
+ -- to identify specific keys used for protection
+ transactionID [4] OCTET STRING OPTIONAL,
+ -- identifies the transaction; i.e., this will be the same in
+ -- corresponding request, response, certConf, and PKIConf
+ -- messages
+ senderNonce [5] OCTET STRING OPTIONAL,
+ recipNonce [6] OCTET STRING OPTIONAL,
+ -- nonces used to provide replay protection, senderNonce
+ -- is inserted by the creator of this message; recipNonce
+ -- is a nonce previously inserted in a related message by
+ -- the intended recipient of this message
+ freeText [7] PKIFreeText OPTIONAL,
+ -- this may be used to indicate context-specific instructions
+ -- (this field is intended for human consumption)
+ generalInfo [8] SEQUENCE SIZE (1..MAX) OF
+ InfoTypeAndValue OPTIONAL
+ -- this may be used to convey context-specific information
+ -- (this field not primarily intended for human consumption)
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+ Creates a new PkiMessage.
+
+ @param header message header
+ @param body message body
+ @param protection message protection (may be null)
+ @param extraCerts extra certificates (may be null)
+
+
+
+ @return a basic ASN.1 object representation.
+
+
+
+ PkiMessages ::= SEQUENCE SIZE (1..MAX) OF PkiMessage
+
+ @return a basic ASN.1 object representation.
+
+
+ @param status
+
+
+ @param status
+ @param statusString
+
+
+
+ PkiStatusInfo ::= SEQUENCE {
+ status PKIStatus, (INTEGER)
+ statusString PkiFreeText OPTIONAL,
+ failInfo PkiFailureInfo OPTIONAL (BIT STRING)
+ }
+
+ PKIStatus:
+ granted (0), -- you got exactly what you asked for
+ grantedWithMods (1), -- you got something like what you asked for
+ rejection (2), -- you don't get it, more information elsewhere in the message
+ waiting (3), -- the request body part has not yet been processed, expect to hear more later
+ revocationWarning (4), -- this message contains a warning that a revocation is imminent
+ revocationNotification (5), -- notification that a revocation has occurred
+ keyUpdateWarning (6) -- update already done for the oldCertId specified in CertReqMsg
+
+ PkiFailureInfo:
+ badAlg (0), -- unrecognized or unsupported Algorithm Identifier
+ badMessageCheck (1), -- integrity check failed (e.g., signature did not verify)
+ badRequest (2), -- transaction not permitted or supported
+ badTime (3), -- messageTime was not sufficiently close to the system time, as defined by local policy
+ badCertId (4), -- no certificate could be found matching the provided criteria
+ badDataFormat (5), -- the data submitted has the wrong format
+ wrongAuthority (6), -- the authority indicated in the request is different from the one creating the response token
+ incorrectData (7), -- the requester's data is incorrect (for notary services)
+ missingTimeStamp (8), -- when the timestamp is missing but should be there (by policy)
+ badPOP (9) -- the proof-of-possession failed
+
+
+
+
+
+ PollRepContent ::= SEQUENCE OF SEQUENCE {
+ certReqId INTEGER,
+ checkAfter INTEGER, -- time in seconds
+ reason PKIFreeText OPTIONAL
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ @return a basic ASN.1 object representation.
+
+
+
+ RevDetails ::= SEQUENCE {
+ certDetails CertTemplate,
+ -- allows requester to specify as much as they can about
+ -- the cert. for which revocation is requested
+ -- (e.g., for cases in which serialNumber is not available)
+ crlEntryDetails Extensions OPTIONAL
+ -- requested crlEntryExtensions
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ RevRepContent ::= SEQUENCE {
+ status SEQUENCE SIZE (1..MAX) OF PKIStatusInfo,
+ -- in same order as was sent in RevReqContent
+ revCerts [0] SEQUENCE SIZE (1..MAX) OF CertId OPTIONAL,
+ -- IDs for which revocation was requested
+ -- (same order as status)
+ crls [1] SEQUENCE SIZE (1..MAX) OF CertificateList OPTIONAL
+ -- the resulting CRLs (there may be more than one)
+ }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ RevReqContent ::= SEQUENCE OF RevDetails
+
+ @return a basic ASN.1 object representation.
+
+
+ return an Attribute object from the given object.
+
+ @param o the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Attribute ::= SEQUENCE {
+ attrType OBJECT IDENTIFIER,
+ attrValues SET OF AttributeValue
+ }
+
+
+
+
+ Attributes ::=
+ SET SIZE(1..MAX) OF Attribute -- according to RFC 5652
+
+ @return
+
+
+ Return all the attributes matching the OBJECT IDENTIFIER oid. The vector will be
+ empty if there are no attributes of the required type present.
+
+ @param oid type of attribute required.
+ @return a vector of all the attributes found of type oid.
+
+
+ Return a new table with the passed in attribute added.
+
+ @param attrType
+ @param attrValue
+ @return
+
+
+ Return the first attribute matching the given OBJECT IDENTIFIER
+
+
+ return an AuthenticatedData object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param isExplicit true if the object is meant to be explicitly
+ tagged false otherwise.
+ @throws ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return an AuthenticatedData object from the given object.
+
+ @param obj the object we want converted.
+ @throws ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return an AuthEnvelopedData object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param isExplicit true if the object is meant to be explicitly
+ tagged false otherwise.
+ @throws ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return an AuthEnvelopedData object from the given object.
+
+ @param obj the object we want converted.
+ @throws ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return a CompressedData object from a tagged object.
+
+ @param ato the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return a CompressedData object from the given object.
+
+ @param _obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ RFC 3274 - CMS Compressed Data.
+
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ ContentInfo ::= Sequence {
+ contentType ContentType,
+ content
+ [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }
+
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ ContentInfo ::= SEQUENCE {
+ contentType ContentType,
+ content
+ [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }
+
+
+
+ return an AuthEnvelopedData object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param isExplicit true if the object is meant to be explicitly
+ tagged false otherwise.
+ @throws ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return an AuthEnvelopedData object from the given object.
+
+ @param obj the object we want converted.
+ @throws ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return an EncryptedContentInfo object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ @return a basic ASN.1 object representation.
+
+
+ return an EnvelopedData object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return an EnvelopedData object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return a KekIdentifier object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return a KekIdentifier object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ KekIdentifier ::= Sequence {
+ keyIdentifier OCTET STRING,
+ date GeneralizedTime OPTIONAL,
+ other OtherKeyAttribute OPTIONAL
+ }
+
+
+
+ return a KekRecipientInfo object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return a KekRecipientInfo object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ KekRecipientInfo ::= Sequence {
+ version CMSVersion, -- always set to 4
+ kekID KekIdentifier,
+ keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
+ encryptedKey EncryptedKey
+ }
+
+
+
+ return an KeyAgreeRecipientIdentifier object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param isExplicit true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return an KeyAgreeRecipientIdentifier object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return a KeyAgreeRecipientInfo object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return a KeyAgreeRecipientInfo object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ * Produce an object suitable for an Asn1OutputStream.
+ *
+
+
+ return a KeyTransRecipientInfo object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ KeyTransRecipientInfo ::= Sequence {
+ version CMSVersion, -- always set to 0 or 2
+ rid RecipientIdentifier,
+ keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
+ encryptedKey EncryptedKey
+ }
+
+ @return
+
+
+ return an OriginatorIdentifierOrKey object from a tagged object.
+
+ @param o the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return an OriginatorIdentifierOrKey object from the given object.
+
+ @param o the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return an OriginatorInfo object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return an OriginatorInfo object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return an OriginatorPublicKey object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return an OriginatorPublicKey object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return an OtherKeyAttribute object from the given object.
+
+ @param o the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ OtherKeyAttribute ::= Sequence {
+ keyAttrId OBJECT IDENTIFIER,
+ keyAttr ANY DEFINED BY keyAttrId OPTIONAL
+ }
+
+
+
+ return a OtherRecipientInfo object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return a OtherRecipientInfo object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ OtherRecipientInfo ::= Sequence {
+ oriType OBJECT IDENTIFIER,
+ oriValue ANY DEFINED BY oriType }
+
+
+
+ return a PasswordRecipientInfo object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return a PasswordRecipientInfo object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ PasswordRecipientInfo ::= Sequence {
+ version CMSVersion, -- Always set to 0
+ keyDerivationAlgorithm [0] KeyDerivationAlgorithmIdentifier
+ OPTIONAL,
+ keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
+ encryptedKey EncryptedKey }
+
+
+
+ return an RecipientEncryptedKey object from a tagged object.
+
+ @param obj the tagged object holding the object we want.
+ @param isExplicit true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return a RecipientEncryptedKey object from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return a RecipientIdentifier object from the given object.
+
+ @param o the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return a RecipientKeyIdentifier object from a tagged object.
+
+ @param _ato the tagged object holding the object we want.
+ @param _explicit true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the object held by the
+ tagged object cannot be converted.
+
+
+ return a RecipientKeyIdentifier object from the given object.
+
+ @param _obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ return a SignerIdentifier object from the given object.
+
+ @param o the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ creates a time object from a given date - if the date is between 1950
+ and 2049 a UTCTime object is Generated, otherwise a GeneralizedTime
+ is used.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ @return a basic ASN.1 object representation.
+
+
+
+ CertReqMessages ::= SEQUENCE SIZE (1..MAX) OF CertReqMsg
+
+ @return a basic ASN.1 object representation.
+
+
+ Creates a new CertReqMsg.
+ @param certReq CertRequest
+ @param popo may be null
+ @param regInfo may be null
+
+
+
+ CertReqMsg ::= SEQUENCE {
+ certReq CertRequest,
+ pop ProofOfPossession OPTIONAL,
+ -- content depends upon key type
+ regInfo SEQUENCE SIZE(1..MAX) OF AttributeTypeAndValue OPTIONAL }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ CertRequest ::= SEQUENCE {
+ certReqId INTEGER, -- ID for matching request and reply
+ certTemplate CertTemplate, -- Selected fields of cert to be issued
+ controls Controls OPTIONAL } -- Attributes affecting issuance
+
+ @return a basic ASN.1 object representation.
+
+
+
+ @return a basic ASN.1 object representation.
+
+
+ Sets the X.509 version. Note: for X509v3, use 2 here.
+
+
+ Sets the issuer unique ID (deprecated in X.509v3)
+
+
+ Sets the subject unique ID (deprecated in X.509v3)
+
+
+
+ EncryptedKey ::= CHOICE {
+ encryptedValue EncryptedValue, -- deprecated
+ envelopedData [0] EnvelopedData }
+ -- The encrypted private key MUST be placed in the envelopedData
+ -- encryptedContentInfo encryptedContent OCTET STRING.
+
+
+
+
+ EncryptedValue ::= SEQUENCE {
+ intendedAlg [0] AlgorithmIdentifier OPTIONAL,
+ -- the intended algorithm for which the value will be used
+ symmAlg [1] AlgorithmIdentifier OPTIONAL,
+ -- the symmetric algorithm used to encrypt the value
+ encSymmKey [2] BIT STRING OPTIONAL,
+ -- the (encrypted) symmetric key used to encrypt the value
+ keyAlg [3] AlgorithmIdentifier OPTIONAL,
+ -- algorithm used to encrypt the symmetric key
+ valueHint [4] OCTET STRING OPTIONAL,
+ -- a brief description or identifier of the encValue content
+ -- (may be meaningful only to the sending entity, and used only
+ -- if EncryptedValue might be re-examined by the sending entity
+ -- in the future)
+ encValue BIT STRING }
+ -- the encrypted value itself
+
+ @return a basic ASN.1 object representation.
+
+
+
+ OptionalValidity ::= SEQUENCE {
+ notBefore [0] Time OPTIONAL,
+ notAfter [1] Time OPTIONAL } --at least one MUST be present
+
+ @return a basic ASN.1 object representation.
+
+
+
+ PkiArchiveOptions ::= CHOICE {
+ encryptedPrivKey [0] EncryptedKey,
+ -- the actual value of the private key
+ keyGenParameters [1] KeyGenParameters,
+ -- parameters which allow the private key to be re-generated
+ archiveRemGenPrivKey [2] BOOLEAN }
+ -- set to TRUE if sender wishes receiver to archive the private
+ -- key of a key pair that the receiver generates in response to
+ -- this request; set to FALSE if no archival is desired.
+
+
+
+
+ PkiPublicationInfo ::= SEQUENCE {
+ action INTEGER {
+ dontPublish (0),
+ pleasePublish (1) },
+ pubInfos SEQUENCE SIZE (1..MAX) OF SinglePubInfo OPTIONAL }
+ -- pubInfos MUST NOT be present if action is "dontPublish"
+ -- (if action is "pleasePublish" and pubInfos is omitted,
+ -- "dontCare" is assumed)
+
+ @return a basic ASN.1 object representation.
+
+
+ Password-based MAC value for use with POPOSigningKeyInput.
+
+
+ Creates a new PKMACValue.
+ @param params parameters for password-based MAC
+ @param value MAC of the DER-encoded SubjectPublicKeyInfo
+
+
+ Creates a new PKMACValue.
+ @param aid CMPObjectIdentifiers.passwordBasedMAC, with PBMParameter
+ @param value MAC of the DER-encoded SubjectPublicKeyInfo
+
+
+
+ PKMACValue ::= SEQUENCE {
+ algId AlgorithmIdentifier,
+ -- algorithm value shall be PasswordBasedMac 1.2.840.113533.7.66.13
+ -- parameter value is PBMParameter
+ value BIT STRING }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ PopoPrivKey ::= CHOICE {
+ thisMessage [0] BIT STRING, -- Deprecated
+ -- possession is proven in this message (which contains the private
+ -- key itself (encrypted for the CA))
+ subsequentMessage [1] SubsequentMessage,
+ -- possession will be proven in a subsequent message
+ dhMAC [2] BIT STRING, -- Deprecated
+ agreeMAC [3] PKMACValue,
+ encryptedKey [4] EnvelopedData }
+
+
+
+ Creates a new Proof of Possession object for a signing key.
+ @param poposkIn the PopoSigningKeyInput structure, or null if the
+ CertTemplate includes both subject and publicKey values.
+ @param aid the AlgorithmIdentifier used to sign the proof of possession.
+ @param signature a signature over the DER-encoded value of poposkIn,
+ or the DER-encoded value of certReq if poposkIn is null.
+
+
+
+ PopoSigningKey ::= SEQUENCE {
+ poposkInput [0] PopoSigningKeyInput OPTIONAL,
+ algorithmIdentifier AlgorithmIdentifier,
+ signature BIT STRING }
+ -- The signature (using "algorithmIdentifier") is on the
+ -- DER-encoded value of poposkInput. NOTE: If the CertReqMsg
+ -- certReq CertTemplate contains the subject and publicKey values,
+ -- then poposkInput MUST be omitted and the signature MUST be
+ -- computed on the DER-encoded value of CertReqMsg certReq. If
+ -- the CertReqMsg certReq CertTemplate does not contain the public
+ -- key and subject values, then poposkInput MUST be present and
+ -- MUST be signed. This strategy ensures that the public key is
+ -- not present in both the poposkInput and CertReqMsg certReq
+ -- CertTemplate fields.
+
+ @return a basic ASN.1 object representation.
+
+
+ Creates a new PopoSigningKeyInput with sender name as authInfo.
+
+
+ Creates a new PopoSigningKeyInput using password-based MAC.
+
+
+
+ PopoSigningKeyInput ::= SEQUENCE {
+ authInfo CHOICE {
+ sender [0] GeneralName,
+ -- used only if an authenticated identity has been
+ -- established for the sender (e.g., a DN from a
+ -- previously-issued and currently-valid certificate
+ publicKeyMac PKMacValue },
+ -- used if no authenticated GeneralName currently exists for
+ -- the sender; publicKeyMac contains a password-based MAC
+ -- on the DER-encoded value of publicKey
+ publicKey SubjectPublicKeyInfo } -- from CertTemplate
+
+ @return a basic ASN.1 object representation.
+
+
+ Returns the sender field, or null if authInfo is publicKeyMac
+
+
+ Returns the publicKeyMac field, or null if authInfo is sender
+
+
+ Creates a ProofOfPossession with type raVerified.
+
+
+ Creates a ProofOfPossession for a signing key.
+
+
+ Creates a ProofOfPossession for key encipherment or agreement.
+ @param type one of TYPE_KEY_ENCIPHERMENT or TYPE_KEY_AGREEMENT
+
+
+
+ ProofOfPossession ::= CHOICE {
+ raVerified [0] NULL,
+ -- used if the RA has already verified that the requester is in
+ -- possession of the private key
+ signature [1] PopoSigningKey,
+ keyEncipherment [2] PopoPrivKey,
+ keyAgreement [3] PopoPrivKey }
+
+ @return a basic ASN.1 object representation.
+
+
+
+ @return a basic ASN.1 object representation.
+
+
+ return an integer from the passed in object
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return an Integer from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param isExplicit true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ in some cases positive values Get crammed into a space,
+ that's not quite big enough...
+
+
+ table of the available named parameters for GOST 3410-2001.
+
+
+ return the ECDomainParameters object for the given OID, null if it
+ isn't present.
+
+ @param oid an object identifier representing a named parameters, if present.
+
+
+ return the named curve name represented by the given object identifier.
+
+
+ returns an enumeration containing the name strings for curves
+ contained in this structure.
+
+
+
+
+
+ table of the available named parameters for GOST 3410-94.
+
+
+ return the GOST3410ParamSetParameters object for the given OID, null if it
+ isn't present.
+
+ @param oid an object identifier representing a named parameters, if present.
+
+
+ returns an enumeration containing the name strings for parameters
+ contained in this structure.
+
+
+ Der BMPString object.
+
+
+ return a BMP string from the given object.
+
+ @param obj the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return a BMP string from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ basic constructor - byte encoded string.
+
+
+ basic constructor
+
+
+ return a bool from the passed in object.
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return a DerBoolean from the passed in bool.
+
+
+ return a Boolean from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ return an integer from the passed in object
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return an Enumerated from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ Class representing the DER-type External
+
+
+ Creates a new instance of DerExternal
+ See X.690 for more informations about the meaning of these parameters
+ @param directReference The direct reference or null if not set.
+ @param indirectReference The indirect reference or null if not set.
+ @param dataValueDescriptor The data value descriptor or null if not set.
+ @param externalData The external data in its encoded form.
+
+
+ Creates a new instance of DerExternal.
+ See X.690 for more informations about the meaning of these parameters
+ @param directReference The direct reference or null if not set.
+ @param indirectReference The indirect reference or null if not set.
+ @param dataValueDescriptor The data value descriptor or null if not set.
+ @param encoding The encoding to be used for the external data
+ @param externalData The external data
+
+
+ The encoding of the content. Valid values are
+
+
0 single-ASN1-type
+
1 OCTET STRING
+
2 BIT STRING
+
+
+
+ Generalized time object.
+
+
+ return a generalized time from the passed in object
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return a Generalized Time object from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ The correct format for this is YYYYMMDDHHMMSS[.f]Z, or without the Z
+ for local time, or Z+-HHMM on the end, for difference between local
+ time and UTC time. The fractional second amount f must consist of at
+ least one number with trailing zeroes removed.
+
+ @param time the time string.
+ @exception ArgumentException if string is an illegal format.
+
+
+ base constructor from a local time object
+
+
+ return the time - always in the form of
+ YYYYMMDDhhmmssGMT(+hh:mm|-hh:mm).
+
+ Normally in a certificate we would expect "Z" rather than "GMT",
+ however adding the "GMT" means we can just use:
+
+ dateF = new SimpleDateFormat("yyyyMMddHHmmssz");
+
+ To read in the time and Get a date which is compatible with our local
+ time zone.
+
+
+ Return the time.
+ @return The time string as it appeared in the encoded object.
+
+
+ Der IA5String object - this is an ascii string.
+
+
+ return a IA5 string from the passed in object
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return an IA5 string from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ basic constructor - with bytes.
+
+
+ basic constructor - without validation.
+
+
+ Constructor with optional validation.
+
+ @param string the base string to wrap.
+ @param validate whether or not to check the string.
+ @throws ArgumentException if validate is true and the string
+ contains characters that should not be in an IA5String.
+
+
+ return true if the passed in String can be represented without
+ loss as an IA5String, false otherwise.
+
+ @return true if in printable set, false otherwise.
+
+
+ Der NumericString object - this is an ascii string of characters {0,1,2,3,4,5,6,7,8,9, }.
+
+
+ return a Numeric string from the passed in object
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return an Numeric string from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ basic constructor - with bytes.
+
+
+ basic constructor - without validation..
+
+
+ Constructor with optional validation.
+
+ @param string the base string to wrap.
+ @param validate whether or not to check the string.
+ @throws ArgumentException if validate is true and the string
+ contains characters that should not be in a NumericString.
+
+
+ Return true if the string can be represented as a NumericString ('0'..'9', ' ')
+
+ @param str string to validate.
+ @return true if numeric, fale otherwise.
+
+
+ return an Oid from the passed in object
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return an object Identifier from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ Return true if this oid is an extension of the passed in branch, stem.
+ @param stem the arc or branch that is a possible parent.
+ @return true if the branch is on the passed in stem, false otherwise.
+
+
+ Der PrintableString object.
+
+
+ return a printable string from the passed in object.
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return a Printable string from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ basic constructor - byte encoded string.
+
+
+ basic constructor - this does not validate the string
+
+
+ Constructor with optional validation.
+
+ @param string the base string to wrap.
+ @param validate whether or not to check the string.
+ @throws ArgumentException if validate is true and the string
+ contains characters that should not be in a PrintableString.
+
+
+ return true if the passed in String can be represented without
+ loss as a PrintableString, false otherwise.
+
+ @return true if in printable set, false otherwise.
+
+
+ Der T61String (also the teletex string) - 8-bit characters
+
+
+ return a T61 string from the passed in object.
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return an T61 string from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ basic constructor - with bytes.
+
+
+ basic constructor - with string.
+
+
+ Der UniversalString object.
+
+
+ return a Universal string from the passed in object.
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return a Universal string from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ basic constructor - byte encoded string.
+
+
+ We insert one of these when we find a tag we don't recognise.
+
+
+ @param tag the tag value.
+ @param data the contents octets.
+
+
+ UTC time object.
+
+
+ return an UTC Time from the passed in object.
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return an UTC Time from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ The correct format for this is YYMMDDHHMMSSZ (it used to be that seconds were
+ never encoded. When you're creating one of these objects from scratch, that's
+ what you want to use, otherwise we'll try to deal with whatever Gets read from
+ the input stream... (this is why the input format is different from the GetTime()
+ method output).
+
+ @param time the time string.
+
+
+ base constructor from a DateTime object
+
+
+ return the time as a date based on whatever a 2 digit year will return. For
+ standardised processing use ToAdjustedDateTime().
+
+ @return the resulting date
+ @exception ParseException if the date string cannot be parsed.
+
+
+ return the time as an adjusted date
+ in the range of 1950 - 2049.
+
+ @return a date in the range of 1950 to 2049.
+ @exception ParseException if the date string cannot be parsed.
+
+
+ return the time - always in the form of
+ YYMMDDhhmmssGMT(+hh:mm|-hh:mm).
+
+ Normally in a certificate we would expect "Z" rather than "GMT",
+ however adding the "GMT" means we can just use:
+
+ dateF = new SimpleDateFormat("yyMMddHHmmssz");
+
+ To read in the time and Get a date which is compatible with our local
+ time zone.
+
+ Note: In some cases, due to the local date processing, this
+ may lead to unexpected results. If you want to stick the normal
+ convention of 1950 to 2049 use the GetAdjustedTime() method.
+
+
+
+ Return a time string as an adjusted date with a 4 digit year.
+ This goes in the range of 1950 - 2049.
+
+
+
+ Der UTF8String object.
+
+
+ return an UTF8 string from the passed in object.
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return an UTF8 string from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ basic constructor - byte encoded string.
+
+
+ basic constructor
+
+
+ Der VisibleString object.
+
+
+ return a Visible string from the passed in object.
+
+ @exception ArgumentException if the object cannot be converted.
+
+
+ return a Visible string from a tagged object.
+
+ @param obj the tagged object holding the object we want
+ @param explicitly true if the object is meant to be explicitly
+ tagged false otherwise.
+ @exception ArgumentException if the tagged object cannot
+ be converted.
+
+
+ basic constructor - byte encoded string.
+
+
+ basic constructor
+
+
+
+ RFC 3126: 4.3.1 Certificate Values Attribute Definition
+
+ CertificateValues ::= SEQUENCE OF Certificate
+
+
+
+
+
+
+
+ Create from OCTET STRING whose octets represent the identifier.
+
+
+ Create from byte array representing the identifier.
+
+
+ The definition of ContentIdentifier is
+
+ SigningCertificate ::= SEQUENCE {
+ certs SEQUENCE OF EssCertID,
+ policies SEQUENCE OF PolicyInformation OPTIONAL
+ }
+
+ id-aa-signingCertificate OBJECT IDENTIFIER ::= { iso(1)
+ member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
+ smime(16) id-aa(2) 12 }
+
+
+ The definition of SigningCertificateV2 is
+
+ SigningCertificateV2 ::= SEQUENCE {
+ certs SEQUENCE OF EssCertIDv2,
+ policies SEQUENCE OF PolicyInformation OPTIONAL
+ }
+
+ id-aa-signingCertificateV2 OBJECT IDENTIFIER ::= { iso(1)
+ member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
+ smime(16) id-aa(2) 47 }
+
+
+ The CscaMasterList object. This object can be wrapped in a
+ CMSSignedData to be published in LDAP.
+
+
+ CscaMasterList ::= SEQUENCE {
+ version CscaMasterListVersion,
+ certList SET OF Certificate }
+
+ CscaMasterListVersion :: INTEGER {v0(0)}
+
+ @return
+
+
+ The id-isismtt-cp-accredited OID indicates that the certificate is a
+ qualified certificate according to Directive 1999/93/EC of the European
+ Parliament and of the Council of 13 December 1999 on a Community
+ Framework for Electronic Signatures, which additionally conforms the
+ special requirements of the SigG and has been issued by an accredited CA.
+
+
+ Certificate extensionDate of certificate generation
+
+
+ DateOfCertGenSyntax ::= GeneralizedTime
+
+
+
+ Attribute to indicate that the certificate holder may sign in the name of
+ a third person. May also be used as extension in a certificate.
+
+
+ Attribute to indicate admissions to certain professions. May be used as
+ attribute in attribute certificate or as extension in a certificate
+
+
+ Monetary limit for transactions. The QcEuMonetaryLimit QC statement MUST
+ be used in new certificates in place of the extension/attribute
+ MonetaryLimit since January 1, 2004. For the sake of backward
+ compatibility with certificates already in use, SigG conforming
+ components MUST support MonetaryLimit (as well as QcEuLimitValue).
+
+
+ A declaration of majority. May be used as attribute in attribute
+ certificate or as extension in a certificate
+
+
+
+ Serial number of the smart card containing the corresponding private key
+
+
+ ICCSNSyntax ::= OCTET STRING (SIZE(8..20))
+
+
+
+
+ Reference for a file of a smartcard that stores the public key of this
+ certificate and that is used as �security anchor�.
+
+
+ PKReferenceSyntax ::= OCTET STRING (SIZE(20))
+
+
+
+ Some other restriction regarding the usage of this certificate. May be
+ used as attribute in attribute certificate or as extension in a
+ certificate.
+
+
+
+ @see Org.BouncyCastle.Asn1.IsisMtt.X509.Restriction
+
+
+
+ (Single)Request extension: Clients may include this extension in a
+ (single) Request to request the responder to send the certificate in the
+ response message along with the status information. Besides the LDAP
+ service, this extension provides another mechanism for the distribution
+ of certificates, which MAY optionally be provided by certificate
+ repositories.
+
+
+ RetrieveIfAllowed ::= BOOLEAN
+
+
+
+ SingleOCSPResponse extension: The certificate requested by the client by
+ inserting the RetrieveIfAllowed extension in the request, will be
+ returned in this extension.
+
+ @see Org.BouncyCastle.Asn1.IsisMtt.Ocsp.RequestedCertificate
+
+
+ Base ObjectIdentifier for naming authorities
+
+
+ SingleOCSPResponse extension: Date, when certificate has been published
+ in the directory and status information has become available. Currently,
+ accrediting authorities enforce that SigG-conforming OCSP servers include
+ this extension in the responses.
+
+
+ CertInDirSince ::= GeneralizedTime
+
+
+
+ Hash of a certificate in OCSP.
+
+ @see Org.BouncyCastle.Asn1.IsisMtt.Ocsp.CertHash
+
+
+
+ NameAtBirth ::= DirectoryString(SIZE(1..64)
+
+
+ Used in
+ {@link Org.BouncyCastle.Asn1.X509.SubjectDirectoryAttributes SubjectDirectoryAttributes}
+
+
+ Some other information of non-restrictive nature regarding the usage of
+ this certificate. May be used as attribute in atribute certificate or as
+ extension in a certificate.
+
+
+
+ @see Org.BouncyCastle.Asn1.IsisMtt.X509.AdditionalInformationSyntax
+
+
+ Indicates that an attribute certificate exists, which limits the
+ usability of this public key certificate. Whenever verifying a signature
+ with the help of this certificate, the content of the corresponding
+ attribute certificate should be concerned. This extension MUST be
+ included in a PKC, if a corresponding attribute certificate (having the
+ PKC as base certificate) contains some attribute that restricts the
+ usability of the PKC too. Attribute certificates with restricting content
+ MUST always be included in the signed document.
+
+
+ LiabilityLimitationFlagSyntax ::= BOOLEAN
+
+
+
+ ISIS-MTT PROFILE: The responder may include this extension in a response to
+ send the hash of the requested certificate to the responder. This hash is
+ cryptographically bound to the certificate and serves as evidence that the
+ certificate is known to the responder (i.e. it has been issued and is present
+ in the directory). Hence, this extension is a means to provide a positive
+ statement of availability as described in T8.[8]. As explained in T13.[1],
+ clients may rely on this information to be able to validate signatures after
+ the expiry of the corresponding certificate. Hence, clients MUST support this
+ extension. If a positive statement of availability is to be delivered, this
+ extension syntax and OID MUST be used.
+
+
+
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructor from a given details.
+
+ @param hashAlgorithm The hash algorithm identifier.
+ @param certificateHash The hash of the whole DER encoding of the certificate.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @return an Asn1Object
+
+
+ ISIS-MTT-Optional: The certificate requested by the client by inserting the
+ RetrieveIfAllowed extension in the request, will be returned in this
+ extension.
+
+ ISIS-MTT-SigG: The signature act allows publishing certificates only then,
+ when the certificate owner gives his isExplicit permission. Accordingly, there
+ may be �nondownloadable� certificates, about which the responder must provide
+ status information, but MUST NOT include them in the response. Clients may
+ get therefore the following three kind of answers on a single request
+ including the RetrieveIfAllowed extension:
+
+
a) the responder supports the extension and is allowed to publish the
+ certificate: RequestedCertificate returned including the requested
+ certificate
+
b) the responder supports the extension but is NOT allowed to publish
+ the certificate: RequestedCertificate returned including an empty OCTET
+ STRING
+
c) the responder does not support the extension: RequestedCertificate is
+ not included in the response
+
+ Clients requesting RetrieveIfAllowed MUST be able to handle these cases. If
+ any of the OCTET STRING options is used, it MUST contain the DER encoding of
+ the requested certificate.
+
+
+
+
+ Constructor from a given details.
+
+ Only one parameter can be given. All other must be null.
+
+ @param certificate Given as Certificate
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+
+ Constructor from a given details.
+
+ @param information The describtion of the information.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructor from a given details.
+
+ Parameter professionInfos is mandatory.
+
+ @param admissionAuthority The admission authority.
+ @param namingAuthority The naming authority.
+ @param professionInfos The profession infos.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+
+ ISIS-MTT PROFILE: The relatively complex structure of AdmissionSyntax
+ supports the following concepts and requirements:
+
+
External institutions (e.g. professional associations, chambers, unions,
+ administrative bodies, companies, etc.), which are responsible for granting
+ and verifying professional admissions, are indicated by means of the data
+ field admissionAuthority. An admission authority is indicated by a
+ GeneralName object. Here an X.501 directory name (distinguished name) can be
+ indicated in the field directoryName, a URL address can be indicated in the
+ field uniformResourceIdentifier, and an object identifier can be indicated in
+ the field registeredId.
+
The names of authorities which are responsible for the administration of
+ title registers are indicated in the data field namingAuthority. The name of
+ the authority can be identified by an object identifier in the field
+ namingAuthorityId, by means of a text string in the field
+ namingAuthorityText, by means of a URL address in the field
+ namingAuthorityUrl, or by a combination of them. For example, the text string
+ can contain the name of the authority, the country and the name of the title
+ register. The URL-option refers to a web page which contains lists with
+ �officially� registered professions (text and possibly OID) as well as
+ further information on these professions. Object identifiers for the
+ component namingAuthorityId are grouped under the OID-branch
+ id-isis-at-namingAuthorities and must be applied for.
+
See http://www.teletrust.de/anwend.asp?Id=30200&Sprache=E_&HomePG=0
+ for an application form and http://www.teletrust.de/links.asp?id=30220,11
+ for an overview of registered naming authorities.
+
By means of the data type ProfessionInfo certain professions,
+ specializations, disciplines, fields of activity, etc. are identified. A
+ profession is represented by one or more text strings, resp. profession OIDs
+ in the fields professionItems and professionOIDs and by a registration number
+ in the field registrationNumber. An indication in text form must always be
+ present, whereas the other indications are optional. The component
+ addProfessionInfo may contain additional applicationspecific information in
+ DER-encoded form.
+
+
+ By means of different namingAuthority-OIDs or profession OIDs hierarchies of
+ professions, specializations, disciplines, fields of activity, etc. can be
+ expressed. The issuing admission authority should always be indicated (field
+ admissionAuthority), whenever a registration number is presented. Still,
+ information on admissions can be given without indicating an admission or a
+ naming authority by the exclusive use of the component professionItems. In
+ this case the certification authority is responsible for the verification of
+ the admission information.
+
+
+
+ This attribute is single-valued. Still, several admissions can be captured in
+ the sequence structure of the component contentsOfAdmissions of
+ AdmissionSyntax or in the component professionInfos of Admissions. The
+ component admissionAuthority of AdmissionSyntax serves as default value for
+ the component admissionAuthority of Admissions. Within the latter component
+ the default value can be overwritten, in case that another authority is
+ responsible. The component namingAuthority of Admissions serves as a default
+ value for the component namingAuthority of ProfessionInfo. Within the latter
+ component the default value can be overwritten, in case that another naming
+ authority needs to be recorded.
+
+ The length of the string objects is limited to 128 characters. It is
+ recommended to indicate a namingAuthorityURL in all issued attribute
+ certificates. If a namingAuthorityURL is indicated, the field professionItems
+ of ProfessionInfo should contain only registered titles. If the field
+ professionOIDs exists, it has to contain the OIDs of the professions listed
+ in professionItems in the same order. In general, the field professionInfos
+ should contain only one entry, unless the admissions that are to be listed
+ are logically connected (e.g. they have been issued under the same admission
+ number).
+
+ @see Org.BouncyCastle.Asn1.IsisMtt.X509.Admissions
+ @see Org.BouncyCastle.Asn1.IsisMtt.X509.ProfessionInfo
+ @see Org.BouncyCastle.Asn1.IsisMtt.X509.NamingAuthority
+
+
+ Constructor from Asn1Sequence.
+
+ The sequence is of type ProcurationSyntax:
+
+
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructor from given details.
+
+ @param admissionAuthority The admission authority.
+ @param contentsOfAdmissions The admissions.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ fullAgeAtCountry indicates the majority of the owner with respect to the laws
+ of a specific country.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @return an Asn1Object
+
+
+ @return notYoungerThan if that's what we are, -1 otherwise
+
+
+ Monetary limit for transactions. The QcEuMonetaryLimit QC statement MUST be
+ used in new certificates in place of the extension/attribute MonetaryLimit
+ since January 1, 2004. For the sake of backward compatibility with
+ certificates already in use, components SHOULD support MonetaryLimit (as well
+ as QcEuLimitValue).
+
+ Indicates a monetary limit within which the certificate holder is authorized
+ to act. (This value DOES NOT express a limit on the liability of the
+ certification authority).
+
+
+
+ currency must be the ISO code.
+
+ value = amount�10*exponent
+
+
+ Constructor from a given details.
+
+
+ value = amount�10^exponent
+
+ @param currency The currency. Must be the ISO code.
+ @param amount The amount
+ @param exponent The exponent
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+ @see Org.BouncyCastle.Asn1.IsisMtt.X509.AdmissionSyntax
+
+
+
+ Profession OIDs should always be defined under the OID branch of the
+ responsible naming authority. At the time of this writing, the work group
+ �Recht, Wirtschaft, Steuern� (�Law, Economy, Taxes�) is registered as the
+ first naming authority under the OID id-isismtt-at-namingAuthorities.
+
+
+ Constructor from Asn1Sequence.
+
+
+
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructor from given details.
+
+ All parameters can be combined.
+
+ @param namingAuthorityID ObjectIdentifier for naming authority.
+ @param namingAuthorityUrl URL for naming authority.
+ @param namingAuthorityText Textual representation of naming authority.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @return an Asn1Object
+
+
+ @return Returns the namingAuthorityID.
+
+
+ @return Returns the namingAuthorityText.
+
+
+ @return Returns the namingAuthorityUrl.
+
+
+ Attribute to indicate that the certificate holder may sign in the name of a
+ third person.
+
+ ISIS-MTT PROFILE: The corresponding ProcurationSyntax contains either the
+ name of the person who is represented (subcomponent thirdPerson) or a
+ reference to his/her base certificate (in the component signingFor,
+ subcomponent certRef), furthermore the optional components country and
+ typeSubstitution to indicate the country whose laws apply, and respectively
+ the type of procuration (e.g. manager, procuration, custody).
+
+
+ ISIS-MTT PROFILE: The GeneralName MUST be of type directoryName and MAY only
+ contain: - RFC3039 attributes, except pseudonym (countryName, commonName,
+ surname, givenName, serialNumber, organizationName, organizationalUnitName,
+ stateOrProvincename, localityName, postalAddress) and - SubjectDirectoryName
+ attributes (title, dateOfBirth, placeOfBirth, gender, countryOfCitizenship,
+ countryOfResidence and NameAtBirth).
+
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructor from a given details.
+
+
+ Either generalName or certRef MUST be
+ null.
+
+ @param country The country code whose laws apply.
+ @param typeOfSubstitution The type of procuration.
+ @param certRef Reference to certificate of the person who is represented.
+
+
+ Constructor from a given details.
+
+
+ Either generalName or certRef MUST be
+ null.
+
+ @param country The country code whose laws apply.
+ @param typeOfSubstitution The type of procuration.
+ @param thirdPerson The GeneralName of the person who is represented.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructor from given details.
+
+ professionItems is mandatory, all other parameters are
+ optional.
+
+ @param namingAuthority The naming authority.
+ @param professionItems Directory strings of the profession.
+ @param professionOids DERObjectIdentfier objects for the
+ profession.
+ @param registrationNumber Registration number.
+ @param addProfessionInfo Additional infos in encoded form.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @return an Asn1Object
+
+
+ @return Returns the professionItems.
+
+
+ @return Returns the professionOids.
+
+
+ @return Returns the addProfessionInfo.
+
+
+ @return Returns the namingAuthority.
+
+
+ @return Returns the registrationNumber.
+
+
+ Some other restriction regarding the usage of this certificate.
+
+
+
+ @param restriction A IAsn1String.
+
+
+ Constructor from a given details.
+
+ @param restriction The description of the restriction.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+ NetscapeCertType ::= BIT STRING {
+ SSLClient (0),
+ SSLServer (1),
+ S/MIME (2),
+ Object Signing (3),
+ Reserved (4),
+ SSL CA (5),
+ S/MIME CA (6),
+ Object Signing CA (7) }
+
+
+
+ Basic constructor.
+
+ @param usage - the bitwise OR of the Key Usage flags giving the
+ allowed uses for the key.
+ e.g. (X509NetscapeCertType.sslCA | X509NetscapeCertType.smimeCA)
+
+
+ This is designed to parse
+ the PublicKeyAndChallenge created by the KEYGEN tag included by
+ Mozilla based browsers.
+
+
+
+ Utility class for fetching curves using their NIST names as published in FIPS-PUB 186-2
+
+
+ return the X9ECParameters object for the named curve represented by
+ the passed in object identifier. Null if the curve isn't present.
+
+ @param oid an object identifier representing a named curve, if present.
+
+
+ return the object identifier signified by the passed in name. Null
+ if there is no object identifier associated with name.
+
+ @return the object identifier associated with name, if present.
+
+
+ return the named curve name represented by the given object identifier.
+
+
+ returns an enumeration containing the name strings for curves
+ contained in this structure.
+
+
+ From RFC 3657
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ class for breaking up an Oid into it's component tokens, ala
+ java.util.StringTokenizer. We need this class as some of the
+ lightweight Java environment don't support classes like
+ StringTokenizer.
+
+
+ return an Attribute object from the given object.
+
+ @param o the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Attr ::= Sequence {
+ attrType OBJECT IDENTIFIER,
+ attrValues Set OF AttributeValue
+ }
+
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ AlgorithmIdentifier ::= Sequence {
+ algorithm OBJECT IDENTIFIER,
+ parameters ANY DEFINED BY algorithm OPTIONAL }
+
+
+
+
+ MacData ::= SEQUENCE {
+ mac DigestInfo,
+ macSalt OCTET STRING,
+ iterations INTEGER DEFAULT 1
+ -- Note: The default is for historic reasons and its use is deprecated. A
+ -- higher value, like 1024 is recommended.
+
+ @return the basic DERObject construction.
+
+
+ the infamous Pfx from Pkcs12
+
+
+ write out an RSA private key with its associated information
+ as described in Pkcs8.
+
+ @return the asn1 primitive representing the parameters.
+
+
+ This outputs the key in Pkcs1v2 format.
+
+ RsaPrivateKey ::= Sequence {
+ version Version,
+ modulus Integer, -- n
+ publicExponent Integer, -- e
+ privateExponent Integer, -- d
+ prime1 Integer, -- p
+ prime2 Integer, -- q
+ exponent1 Integer, -- d mod (p-1)
+ exponent2 Integer, -- d mod (q-1)
+ coefficient Integer -- (inverse of q) mod p
+ }
+
+ Version ::= Integer
+
+
This routine is written to output Pkcs1 version 0, private keys.
+ @return the asn1 primitive representing the parameters.
+
+
+ a Pkcs#7 signed data object.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ the elliptic curve private key object from SEC 1
+
+
+ ECPrivateKey ::= SEQUENCE {
+ version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
+ privateKey OCTET STRING,
+ parameters [0] Parameters OPTIONAL,
+ publicKey [1] BIT STRING OPTIONAL }
+
+
+ return the X9ECParameters object for the named curve represented by
+ the passed in object identifier. Null if the curve isn't present.
+
+ @param oid an object identifier representing a named curve, if present.
+
+
+ return the object identifier signified by the passed in name. Null
+ if there is no object identifier associated with name.
+
+ @return the object identifier associated with name, if present.
+
+
+ return the named curve name represented by the given object identifier.
+
+
+ returns an enumeration containing the name strings for curves
+ contained in this structure.
+
+
+ EllipticCurve OBJECT IDENTIFIER ::= {
+ iso(1) identified-organization(3) certicom(132) curve(0)
+ }
+
+
+ Handler class for dealing with S/MIME Capabilities
+
+
+ general preferences
+
+
+ encryption algorithms preferences
+
+
+ return an Attr object from the given object.
+
+ @param o the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ returns an ArrayList with 0 or more objects of all the capabilities
+ matching the passed in capability Oid. If the Oid passed is null the
+ entire set is returned.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ SMIMECapabilities ::= Sequence OF SMIMECapability
+
+
+
+ return an Attr object from the given object.
+
+ @param o the object we want converted.
+ @exception ArgumentException if the object cannot be converted.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Attr ::= Sequence {
+ attrType OBJECT IDENTIFIER,
+ attrValues Set OF AttributeValue
+ }
+
+
+
+ general preferences
+
+
+ encryption algorithms preferences
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ SMIMECapability ::= Sequence {
+ capabilityID OBJECT IDENTIFIER,
+ parameters ANY DEFINED BY capabilityID OPTIONAL
+ }
+
+
+
+ Handler for creating a vector S/MIME Capabilities
+
+
+ The SmimeEncryptionKeyPreference object.
+
+
+
+ @param sKeyId the subjectKeyIdentifier value (normally the X.509 one)
+
+
+ elliptic curves defined in "ECC Brainpool Standard Curves and Curve Generation"
+ http://www.ecc-brainpool.org/download/draft_pkix_additional_ecc_dp.txt
+
+
+ return the X9ECParameters object for the named curve represented by
+ the passed in object identifier. Null if the curve isn't present.
+
+ @param oid an object identifier representing a named curve, if present.
+
+
+ return the object identifier signified by the passed in name. Null
+ if there is no object identifier associated with name.
+
+ @return the object identifier associated with name, if present.
+
+
+ return the named curve name represented by the given object identifier.
+
+
+ returns an enumeration containing the name strings for curves
+ contained in this structure.
+
+
+
+
+ TstInfo ::= SEQUENCE {
+ version INTEGER { v1(1) },
+ policy TSAPolicyId,
+ messageImprint MessageImprint,
+ -- MUST have the same value as the similar field in
+ -- TimeStampReq
+ serialNumber INTEGER,
+ -- Time-Stamping users MUST be ready to accommodate integers
+ -- up to 160 bits.
+ genTime GeneralizedTime,
+ accuracy Accuracy OPTIONAL,
+ ordering BOOLEAN DEFAULT FALSE,
+ nonce INTEGER OPTIONAL,
+ -- MUST be present if the similar field was present
+ -- in TimeStampReq. In that case it MUST have the same value.
+ tsa [0] GeneralName OPTIONAL,
+ extensions [1] IMPLICIT Extensions OPTIONAL }
+
+
+
+
+ dump a Der object as a formatted string with indentation
+
+ @param obj the Asn1Object to be dumped out.
+
+
+ dump out a DER object as a formatted string, in non-verbose mode
+
+ @param obj the Asn1Encodable to be dumped out.
+ @return the resulting string.
+
+
+ Dump out the object as a string
+
+ @param obj the Asn1Encodable to be dumped out.
+ @param verbose if true, dump out the contents of octet and bit strings.
+ @return the resulting string.
+
+
+
+
+
+ create an AccessDescription with the oid and location provided.
+
+
+
+ @return the access method.
+
+
+
+ @return the access location
+
+
+
+ Don't use this one if you are trying to be RFC 3281 compliant.
+ Use it for v1 attribute certificates only.
+
+ Our GeneralNames structure
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ AttCertIssuer ::= CHOICE {
+ v1Form GeneralNames, -- MUST NOT be used in this
+ -- profile
+ v2Form [0] V2Form -- v2 only
+ }
+
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+
+ *
+ * Calulates the keyidentifier using a SHA1 hash over the BIT STRING
+ * from SubjectPublicKeyInfo as defined in RFC2459.
+ *
+ * Example of making a AuthorityKeyIdentifier:
+ *
+ * SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence)new ASN1InputStream(
+ * publicKey.getEncoded()).readObject());
+ * AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
+ *
+ *
+ *
+
+
+ create an AuthorityKeyIdentifier with the GeneralNames tag and
+ the serial number provided as well.
+
+
+ create an AuthorityKeyIdentifier with the GeneralNames tag and
+ the serial number provided.
+
+
+ create an AuthorityKeyIdentifier with a precomputed key identifier
+
+
+ create an AuthorityKeyIdentifier with a precomupted key identifier
+ and the GeneralNames tag and the serial number provided as well.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+ create a cA=true object for the given path length constraint.
+
+ @param pathLenConstraint
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ This class helps to support crossCerfificatePairs in a LDAP directory
+ according RFC 2587
+
+
+ crossCertificatePairATTRIBUTE::={
+ WITH SYNTAX CertificatePair
+ EQUALITY MATCHING RULE certificatePairExactMatch
+ ID joint-iso-ccitt(2) ds(5) attributeType(4) crossCertificatePair(40)}
+
+
+
The forward elements of the crossCertificatePair attribute of a
+ CA's directory entry shall be used to store all, except self-issued
+ certificates issued to this CA. Optionally, the reverse elements of the
+ crossCertificatePair attribute, of a CA's directory entry may contain a
+ subset of certificates issued by this CA to other CAs. When both the forward
+ and the reverse elements are present in a single attribute value, issuer name
+ in one certificate shall match the subject name in the other and vice versa,
+ and the subject public key in one certificate shall be capable of verifying
+ the digital signature on the other certificate and vice versa.
+
+ When a reverse element is present, the forward element value and the reverse
+ element value need not be stored in the same attribute value; in other words,
+ they can be stored in either a single attribute value or two attribute
+ values.
+
+
+ CertificatePair ::= SEQUENCE {
+ forward [0] Certificate OPTIONAL,
+ reverse [1] Certificate OPTIONAL,
+ -- at least one of the pair shall be present -- }
+
+
+
+ Constructor from Asn1Sequence.
+
+ The sequence is of type CertificatePair:
+
+
+ CertificatePair ::= SEQUENCE {
+ forward [0] Certificate OPTIONAL,
+ reverse [1] Certificate OPTIONAL,
+ -- at least one of the pair shall be present -- }
+
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructor from a given details.
+
+ @param forward Certificates issued to this CA.
+ @param reverse Certificates issued by this CA to other CAs.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+ CertificatePair ::= SEQUENCE {
+ forward [0] Certificate OPTIONAL,
+ reverse [1] Certificate OPTIONAL,
+ -- at least one of the pair shall be present -- }
+
+
+ @return a DERObject
+
+
+ @return Returns the forward.
+
+
+ @return Returns the reverse.
+
+
+ CertPolicyId, used in the CertificatePolicies and PolicyMappings
+ X509V3 Extensions.
+
+
+ CertPolicyId ::= OBJECT IDENTIFIER
+
+
+
+ Return the distribution points making up the sequence.
+
+ @return DistributionPoint[]
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ CrlDistPoint ::= Sequence SIZE {1..MAX} OF DistributionPoint
+
+ @see PolicyQualifierInfo
+ @see PolicyInformation
+
+
+ Constant corresponding to ia5String encoding.
+
+
+
+ Constant corresponding to bmpString encoding.
+
+
+
+ Constant corresponding to utf8String encoding.
+
+
+
+ Constant corresponding to visibleString encoding.
+
+
+
+ Describe constant DisplayTextMaximumSize here.
+
+
+
+ Creates a new DisplayText instance.
+
+ @param type the desired encoding type for the text.
+ @param text the text to store. Strings longer than 200
+ characters are truncated.
+
+
+ Creates a new DisplayText instance.
+
+ @param text the text to encapsulate. Strings longer than 200
+ characters are truncated.
+
+
+ Creates a new DisplayText instance.
+
Useful when reading back a DisplayText class
+ from it's Asn1Encodable form.
+
+ @param contents an Asn1Encodable instance.
+
+
+ Returns the stored string object.
+
+ @return the stored text as a string.
+
+
+ The DistributionPoint object.
+
+ extendedKeyUsage ::= Sequence SIZE (1..MAX) OF KeyPurposeId
+
+
+
+ Returns all extended key usages.
+ The returned ArrayList contains DerObjectIdentifier instances.
+ @return An ArrayList with all key purposes.
+
+
+ The GeneralName object.
+
+
+
+ When the subjectAltName extension contains an Internet mail address,
+ the address MUST be included as an rfc822Name. The format of an
+ rfc822Name is an "addr-spec" as defined in RFC 822 [RFC 822].
+
+ When the subjectAltName extension contains a domain name service
+ label, the domain name MUST be stored in the dNSName (an IA5String).
+ The name MUST be in the "preferred name syntax," as specified by RFC
+ 1034 [RFC 1034].
+
+ When the subjectAltName extension contains a URI, the name MUST be
+ stored in the uniformResourceIdentifier (an IA5String). The name MUST
+ be a non-relative URL, and MUST follow the URL syntax and encoding
+ rules specified in [RFC 1738]. The name must include both a scheme
+ (e.g., "http" or "ftp") and a scheme-specific-part. The scheme-
+ specific-part must include a fully qualified domain name or IP
+ address as the host.
+
+ When the subjectAltName extension contains a iPAddress, the address
+ MUST be stored in the octet string in "network byte order," as
+ specified in RFC 791 [RFC 791]. The least significant bit (LSB) of
+ each octet is the LSB of the corresponding byte in the network
+ address. For IP Version 4, as specified in RFC 791, the octet string
+ MUST contain exactly four octets. For IP Version 6, as specified in
+ RFC 1883, the octet string MUST contain exactly sixteen octets [RFC
+ 1883].
+
+
+ Create a GeneralName for the given tag from the passed in string.
+
+ This constructor can handle:
+
+
rfc822Name
+
iPAddress
+
directoryName
+
dNSName
+
uniformResourceIdentifier
+
registeredID
+
+ For x400Address, otherName and ediPartyName there is no common string
+ format defined.
+
+ Note: A directory name can be encoded in different ways into a byte
+ representation. Be aware of this if the byte representation is used for
+ comparing results.
+
+
+ @param tag tag number
+ @param name string representation of name
+ @throws ArgumentException if the string encoding is not correct or
+ not supported.
+
+
+ Construct a GeneralNames object containing one GeneralName.
+ The name to be contained.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ GeneralNames ::= Sequence SIZE {1..MAX} OF GeneralName
+
+
+
+ Class for containing a restriction object subtrees in NameConstraints. See
+ RFC 3280.
+
+
+
+ @see org.bouncycastle.asn1.x509.NameConstraints
+
+
+
+ Constructor from a given details.
+
+ According RFC 3280, the minimum and maximum fields are not used with any
+ name forms, thus minimum MUST be zero, and maximum MUST be absent.
+
+ If minimum is null, zero is assumed, if
+ maximum is null, maximum is absent.
+
+ @param baseName
+ A restriction.
+ @param minimum
+ Minimum
+
+ @param maximum
+ Maximum
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @return a DERObject
+
+
+ The Holder object.
+
+ For an v2 attribute certificate this is:
+
+
+ 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
+ }
+
+
+
+ For an v1 attribute certificate this is:
+
+
+ subject CHOICE {
+ baseCertificateID [0] IssuerSerial,
+ -- associated with a Public Key Certificate
+ subjectName [1] GeneralNames },
+ -- associated with a name
+
+
+
+
+ Constructor for a holder for an v1 attribute certificate.
+
+ @param tagObj The ASN.1 tagged holder object.
+
+
+ Constructor for a holder for an v2 attribute certificate. *
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructs a holder from a IssuerSerial.
+ @param baseCertificateID The IssuerSerial.
+ @param version The version of the attribute certificate.
+
+
+ Constructs a holder with an entityName for v2 attribute certificates or
+ with a subjectName for v1 attribute certificates.
+
+ @param entityName The entity or subject name.
+
+
+ Constructs a holder with an entityName for v2 attribute certificates or
+ with a subjectName for v1 attribute certificates.
+
+ @param entityName The entity or subject name.
+ @param version The version of the attribute certificate.
+
+
+ Constructs a holder from an object digest info.
+
+ @param objectDigestInfo The object digest info object.
+
+
+ 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
+ }
+
+
+
+ Returns 1 for v2 attribute certificates or 0 for v1 attribute
+ certificates.
+ @return The version of the attribute certificate.
+
+
+ Returns the entityName for an v2 attribute certificate or the subjectName
+ for an v1 attribute certificate.
+
+ @return The entityname or subjectname.
+
+
+ Implementation of IetfAttrSyntax as specified by RFC3281.
+
+
+
+
+
+
+
+
+
+ Constructor from given details.
+
+ @param distributionPoint
+ May contain an URI as pointer to most current CRL.
+ @param onlyContainsUserCerts Covers revocation information for end certificates.
+ @param onlyContainsCACerts Covers revocation information for CA certificates.
+
+ @param onlySomeReasons
+ Which revocation reasons does this point cover.
+ @param indirectCRL
+ If true then the CRL contains revocation
+ information about certificates ssued by other CAs.
+ @param onlyContainsAttributeCerts Covers revocation information for attribute certificates.
+
+
+ Constructor from Asn1Sequence
+
+
+ @return Returns the distributionPoint.
+
+
+ @return Returns the onlySomeReasons.
+
+
+ The KeyPurposeID object.
+
+
+
+ Basic constructor.
+
+ @param usage - the bitwise OR of the Key Usage flags giving the
+ allowed uses for the key.
+ e.g. (KeyUsage.keyEncipherment | KeyUsage.dataEncipherment)
+
+
+ Constructor from a given details.
+
+
permitted and excluded are Vectors of GeneralSubtree objects.
+
+ @param permitted Permitted subtrees
+ @param excluded Excluded subtrees
+
+
+ NoticeReference class, used in
+ CertificatePolicies X509 V3 extensions
+ (in policy qualifiers).
+
+
+
+ @see PolicyQualifierInfo
+ @see PolicyInformation
+
+
+ Creates a new NoticeReference instance.
+
+ @param orgName a string value
+ @param numbers a ArrayList value
+
+
+ Creates a new NoticeReference instance.
+
+ @param orgName a string value
+ @param numbers an Asn1Sequence value
+
+
+ Creates a new NoticeReference instance.
+
+ @param displayTextType an int value
+ @param orgName a string value
+ @param numbers an Asn1Sequence value
+
+
+ Creates a new NoticeReference instance.
+
Useful for reconstructing a NoticeReference
+ instance from its encodable/encoded form.
+
+ @param as an Asn1Sequence value obtained from either
+ calling @{link ToAsn1Object()} for a NoticeReference
+ instance or from parsing it from a Der-encoded stream.
+
+
+ Describe ToAsn1Object method here.
+
+ @return a Asn1Object value
+
+
+ ObjectDigestInfo ASN.1 structure used in v2 attribute certificates.
+
+
+
+ ObjectDigestInfo ::= SEQUENCE {
+ digestedObjectType ENUMERATED {
+ publicKey (0),
+ publicKeyCert (1),
+ otherObjectTypes (2) },
+ -- otherObjectTypes MUST NOT
+ -- be used in this profile
+ otherObjectTypeID OBJECT IDENTIFIER OPTIONAL,
+ digestAlgorithm AlgorithmIdentifier,
+ objectDigest BIT STRING
+ }
+
+
+
+
+
+ The public key is hashed.
+
+
+ The public key certificate is hashed.
+
+
+ An other object is hashed.
+
+
+ Constructor from given details.
+
+ If digestedObjectType is not {@link #publicKeyCert} or
+ {@link #publicKey} otherObjectTypeID must be given,
+ otherwise it is ignored.
+
+ @param digestedObjectType The digest object type.
+ @param otherObjectTypeID The object type ID for
+ otherObjectDigest.
+ @param digestAlgorithm The algorithm identifier for the hash.
+ @param objectDigest The hash value.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ ObjectDigestInfo ::= SEQUENCE {
+ digestedObjectType ENUMERATED {
+ publicKey (0),
+ publicKeyCert (1),
+ otherObjectTypes (2) },
+ -- otherObjectTypes MUST NOT
+ -- be used in this profile
+ otherObjectTypeID OBJECT IDENTIFIER OPTIONAL,
+ digestAlgorithm AlgorithmIdentifier,
+ objectDigest BIT STRING
+ }
+
+
+
+
+ PolicyMappings V3 extension, described in RFC3280.
+
+
+ @see RFC 3280, section 4.2.1.6
+
+
+ Creates a new PolicyMappings instance.
+
+ @param seq an Asn1Sequence constructed as specified
+ in RFC 3280
+
+
+ Creates a new PolicyMappings instance.
+
+ @param mappings a HashMap value that maps
+ string oids
+ to other string oids.
+
+
+ PolicyQualifierId, used in the CertificatePolicies
+ X509V3 extension.
+
+
+
+
+ Policy qualifiers, used in the X509V3 CertificatePolicies
+ extension.
+
+
+ PolicyQualifierInfo ::= Sequence {
+ policyQualifierId PolicyQualifierId,
+ qualifier ANY DEFINED BY policyQualifierId }
+
+
+
+ Creates a new PolicyQualifierInfo instance.
+
+ @param policyQualifierId a PolicyQualifierId value
+ @param qualifier the qualifier, defined by the above field.
+
+
+ Creates a new PolicyQualifierInfo containing a
+ cPSuri qualifier.
+
+ @param cps the CPS (certification practice statement) uri as a
+ string.
+
+
+ Creates a new PolicyQualifierInfo instance.
+
+ @param as PolicyQualifierInfo X509 structure
+ encoded as an Asn1Sequence.
+
+
+ Returns a Der-encodable representation of this instance.
+
+ @return a Asn1Object value
+
+
+
+
+ Iso4217CurrencyCode ::= CHOICE {
+ alphabetic PrintableString (SIZE 3), --Recommended
+ numeric INTEGER (1..999) }
+ -- Alphabetic or numeric currency code as defined in ISO 4217
+ -- It is recommended that the Alphabetic form is used
+
+
+
+ @param reasons - the bitwise OR of the Key Reason flags giving the
+ allowed uses for the key.
+
+
+ Implementation of the RoleSyntax object as specified by the RFC3281.
+
+
+
+
+ RoleSyntax factory method.
+ @param obj the object used to construct an instance of
+ RoleSyntax. It must be an instance of RoleSyntax
+ or Asn1Sequence.
+ @return the instance of RoleSyntax built from the
+ supplied object.
+ @throws java.lang.ArgumentException if the object passed
+ to the factory is not an instance of RoleSyntax or
+ Asn1Sequence.
+
+
+ Constructor.
+ @param roleAuthority the role authority of this RoleSyntax.
+ @param roleName the role name of this RoleSyntax.
+
+
+ Constructor. Invoking this constructor is the same as invoking
+ new RoleSyntax(null, roleName).
+ @param roleName the role name of this RoleSyntax.
+
+
+ Utility constructor. Takes a string argument representing
+ the role name, builds a GeneralName to hold the role name
+ and calls the constructor that takes a GeneralName.
+ @param roleName
+
+
+ Constructor that builds an instance of RoleSyntax by
+ extracting the encoded elements from the Asn1Sequence
+ object supplied.
+ @param seq an instance of Asn1Sequence that holds
+ the encoded elements used to build this RoleSyntax.
+
+
+ Gets the role name as a java.lang.string object.
+ @return the role name of this RoleSyntax represented as a
+ string object.
+
+
+ Gets the role authority as a string[] object.
+ @return the role authority of this RoleSyntax represented as a
+ string[] array.
+
+
+ Implementation of the method ToAsn1Object as
+ required by the superclass ASN1Encodable.
+
+
+
+
+ Gets the role authority of this RoleSyntax.
+ @return an instance of GeneralNames holding the
+ role authority of this RoleSyntax.
+
+
+ Gets the role name of this RoleSyntax.
+ @return an instance of GeneralName holding the
+ role name of this RoleSyntax.
+
+
+ This outputs the key in Pkcs1v2 format.
+
+ RSAPublicKey ::= Sequence {
+ modulus Integer, -- n
+ publicExponent Integer, -- e
+ }
+
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructor from a given details.
+
+ @param pseudonym The pseudonym.
+
+
+ Constructor from a given details.
+
+ @param surname The surname.
+ @param givenName A sequence of directory strings making up the givenName
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @see org.bouncycastle.asn1.x509.sigi.NameOrPseudonym
+ @see org.bouncycastle.asn1.x509.sigi.SigIObjectIdentifiers
+
+
+ Constructor from Asn1Sequence.
+
+ The sequence is of type NameOrPseudonym:
+
+
+
+ @param seq The ASN.1 sequence.
+
+
+ Constructor from a given details.
+
+ @param nameOrPseudonym Name or pseudonym.
+ @param nameDistinguisher Name distinguisher.
+ @param dateOfBirth Date of birth.
+ @param placeOfBirth Place of birth.
+ @param gender Gender.
+ @param postalAddress Postal Address.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @return an Asn1Object
+
+
+ Object Identifiers of SigI specifciation (German Signature Law
+ Interoperability specification).
+
+
+ Key purpose IDs for German SigI (Signature Interoperability
+ Specification)
+
+
+ Certificate policy IDs for German SigI (Signature Interoperability
+ Specification)
+
+
+ Other Name IDs for German SigI (Signature Interoperability Specification)
+
+
+ To be used for for the generation of directory service certificates.
+
+
+ ID for PersonalData
+
+
+ Certificate is conform to german signature law.
+
+
+ This extension may contain further X.500 attributes of the subject. See also
+ RFC 3039.
+
+
+ SubjectDirectoryAttributes ::= Attributes
+ Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
+ Attribute ::= SEQUENCE
+ {
+ type AttributeType
+ values SET OF AttributeValue
+ }
+
+ AttributeType ::= OBJECT IDENTIFIER
+ AttributeValue ::= ANY DEFINED BY AttributeType
+
+
+ @see org.bouncycastle.asn1.x509.X509Name for AttributeType ObjectIdentifiers.
+
+
+ Constructor from Asn1Sequence.
+
+ The sequence is of type SubjectDirectoryAttributes:
+
+
+ SubjectDirectoryAttributes ::= Attributes
+ Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
+ Attribute ::= SEQUENCE
+ {
+ type AttributeType
+ values SET OF AttributeValue
+ }
+
+ AttributeType ::= OBJECT IDENTIFIER
+ AttributeValue ::= ANY DEFINED BY AttributeType
+
+
+ @param seq
+ The ASN.1 sequence.
+
+
+ Constructor from an ArrayList of attributes.
+
+ The ArrayList consists of attributes of type {@link Attribute Attribute}
+
+ @param attributes The attributes.
+
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+ SubjectDirectoryAttributes ::= Attributes
+ Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
+ Attribute ::= SEQUENCE
+ {
+ type AttributeType
+ values SET OF AttributeValue
+ }
+
+ AttributeType ::= OBJECT IDENTIFIER
+ AttributeValue ::= ANY DEFINED BY AttributeType
+
+
+ @return a DERObject
+
+
+ @return Returns the attributes.
+
+
+ The SubjectKeyIdentifier object.
+
+ SubjectKeyIdentifier::= OCTET STRING
+
+
+
+ Calculates the keyIdentifier using a SHA1 hash over the BIT STRING
+ from SubjectPublicKeyInfo as defined in RFC3280.
+
+ @param spki the subject public key info.
+
+
+ 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 keyInfo the key info object containing the subjectPublicKey field.
+ @return the key identifier.
+
+
+ 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 keyInfo the key info object containing the subjectPublicKey field.
+ @return the key identifier.
+
+
+ The object that contains the public key stored in a certficate.
+
+ The GetEncoded() method in the public keys in the JCE produces a DER
+ encoded one of these.
+
+
+ for when the public key is an encoded object - if the bitstring
+ can't be decoded this routine raises an IOException.
+
+ @exception IOException - if the bit string doesn't represent a Der
+ encoded object.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ for when the public key is raw bits...
+
+
+ Target structure used in target information extension for attribute
+ certificates from RFC 3281.
+
+
+ The targetCert field is currently not supported and must not be used
+ according to RFC 3281.
+
+
+ Creates an instance of a Target from the given object.
+
+ obj can be a Target or a {@link Asn1TaggedObject}
+
+ @param obj The object.
+ @return A Target instance.
+ @throws ArgumentException if the given object cannot be
+ interpreted as Target.
+
+
+ Constructor from Asn1TaggedObject.
+
+ @param tagObj The tagged object.
+ @throws ArgumentException if the encoding is wrong.
+
+
+ Constructor from given details.
+
+ Exactly one of the parameters must be not null.
+
+ @param type the choice type to apply to the name.
+ @param name the general name.
+ @throws ArgumentException if type is invalid.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+
+ @return an Asn1Object
+
+
+ @return Returns the targetGroup.
+
+
+ @return Returns the targetName.
+
+
+ Target information extension for attributes certificates according to RFC
+ 3281.
+
+
+ SEQUENCE OF Targets
+
+
+
+
+ Creates an instance of a TargetInformation from the given object.
+
+ obj can be a TargetInformation or a {@link Asn1Sequence}
+
+ @param obj The object.
+ @return A TargetInformation instance.
+ @throws ArgumentException if the given object cannot be interpreted as TargetInformation.
+
+
+ Constructor from a Asn1Sequence.
+
+ @param seq The Asn1Sequence.
+ @throws ArgumentException if the sequence does not contain
+ correctly encoded Targets elements.
+
+
+ Returns the targets in this target information extension.
+
+ The ArrayList is cloned before it is returned.
+
+ @return Returns the targets.
+
+
+ Constructs a target information from a single targets element.
+ According to RFC 3281 only one targets element must be produced.
+
+ @param targets A Targets instance.
+
+
+ According to RFC 3281 only one targets element must be produced. If
+ multiple targets are given they must be merged in
+ into one targets element.
+
+ @param targets An array with {@link Targets}.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+ SEQUENCE OF Targets
+
+
+
+ According to RFC 3281 only one targets element must be produced. If
+ multiple targets are given in the constructor they are merged into one
+ targets element. If this was produced from a
+ {@link Org.BouncyCastle.Asn1.Asn1Sequence} the encoding is kept.
+
+ @return an Asn1Object
+
+
+ Targets structure used in target information extension for attribute
+ certificates from RFC 3281.
+
+
+
+ @see org.bouncycastle.asn1.x509.Target
+ @see org.bouncycastle.asn1.x509.TargetInformation
+
+
+ Creates an instance of a Targets from the given object.
+
+ obj can be a Targets or a {@link Asn1Sequence}
+
+ @param obj The object.
+ @return A Targets instance.
+ @throws ArgumentException if the given object cannot be interpreted as Target.
+
+
+ Constructor from Asn1Sequence.
+
+ @param targets The ASN.1 SEQUENCE.
+ @throws ArgumentException if the contents of the sequence are
+ invalid.
+
+
+ Constructor from given targets.
+
+ The ArrayList is copied.
+
+ @param targets An ArrayList of {@link Target}s.
+ @see Target
+ @throws ArgumentException if the ArrayList contains not only Targets.
+
+
+ Returns the targets in an ArrayList.
+
+ The ArrayList is cloned before it is returned.
+
+ @return Returns the targets.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Returns:
+
+
+ Targets ::= SEQUENCE OF Target
+
+
+ @return an Asn1Object
+
+
+ The TbsCertificate object.
+
+ Note: issuerUniqueID and subjectUniqueID are both deprecated by the IETF. This class
+ will parse them, but you really shouldn't be creating new ones.
+
+
+ PKIX RFC-2459 - TbsCertList object.
+
+ TbsCertList ::= Sequence {
+ version Version OPTIONAL,
+ -- if present, shall be v2
+ signature AlgorithmIdentifier,
+ issuer Name,
+ thisUpdate Time,
+ nextUpdate Time OPTIONAL,
+ revokedCertificates Sequence OF Sequence {
+ userCertificate CertificateSerialNumber,
+ revocationDate Time,
+ crlEntryExtensions Extensions OPTIONAL
+ -- if present, shall be v2
+ } OPTIONAL,
+ crlExtensions [0] EXPLICIT Extensions OPTIONAL
+ -- if present, shall be v2
+ }
+
+
+
+ creates a time object from a given date - if the date is between 1950
+ and 2049 a UTCTime object is Generated, otherwise a GeneralizedTime
+ is used.
+
+
+
+ Return our time as DateTime.
+
+ A date time.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+ @see PolicyQualifierId
+ @see PolicyInformation
+
+
+ Creates a new UserNotice instance.
+
+ @param noticeRef a NoticeReference value
+ @param explicitText a DisplayText value
+
+
+ Creates a new UserNotice instance.
+
+ @param noticeRef a NoticeReference value
+ @param str the explicitText field as a string.
+
+
+ Creates a new UserNotice instance.
+
Useful from reconstructing a UserNotice instance
+ from its encodable/encoded form.
+
+ @param as an ASN1Sequence value obtained from either
+ calling @{link toASN1Object()} for a UserNotice
+ instance or from parsing it from a DER-encoded stream.
+
+
+ Generator for Version 1 TbsCertificateStructures.
+
+
+
+
+ @param attribute
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ V2Form ::= Sequence {
+ issuerName GeneralNames OPTIONAL,
+ baseCertificateID [0] IssuerSerial OPTIONAL,
+ objectDigestInfo [1] ObjectDigestInfo OPTIONAL
+ -- issuerName MUST be present in this profile
+ -- baseCertificateID and objectDigestInfo MUST NOT
+ -- be present in this profile
+ }
+
+
+
+ Generator for Version 2 TbsCertList structures.
+
+ TbsCertList ::= Sequence {
+ version Version OPTIONAL,
+ -- if present, shall be v2
+ signature AlgorithmIdentifier,
+ issuer Name,
+ thisUpdate Time,
+ nextUpdate Time OPTIONAL,
+ revokedCertificates Sequence OF Sequence {
+ userCertificate CertificateSerialNumber,
+ revocationDate Time,
+ crlEntryExtensions Extensions OPTIONAL
+ -- if present, shall be v2
+ } OPTIONAL,
+ crlExtensions [0] EXPLICIT Extensions OPTIONAL
+ -- if present, shall be v2
+ }
+
+
+ Note: This class may be subject to change
+
+
+ Generator for Version 3 TbsCertificateStructures.
+
+
+
+ The default converter for X509 DN entries when going from their
+ string value to ASN.1 strings.
+
+
+ * It turns out that the number of standard ways the fields in a DN should be
+ * encoded into their ASN.1 counterparts is rapidly approaching the
+ * number of machines on the internet. By default the X509Name class
+ * will produce UTF8Strings in line with the current recommendations (RFC 3280).
+ *
+ *
+
+
+ Convert an inline encoded hex string rendition of an ASN.1
+ object back into its corresponding ASN.1 object.
+
+ @param str the hex encoded object
+ @param off the index at which the encoding starts
+ @return the decoded object
+
+
+ return true if the passed in string can be represented without
+ loss as a PrintableString, false otherwise.
+
+
+ Convert the passed in string value into the appropriate ASN.1
+ encoded object.
+
+ @param oid the oid associated with the value in the DN.
+ @param value the value of the particular DN component.
+ @return the ASN.1 equivalent for the value.
+
+
+ Apply default conversion for the given value depending on the oid
+ and the character range of the value.
+
+ @param oid the object identifier for the DN entry
+ @param value the value associated with it
+ @return the ASN.1 equivalent for the string value.
+
+
+ an object for the elements in the X.509 V3 extension block.
+
+
+ Convert the value of the passed in extension to an object.
+ The extension to parse.
+ The object the value string contains.
+ If conversion is not possible.
+
+
+ Subject Directory Attributes
+
+
+ Subject Key Identifier
+
+
+ Key Usage
+
+
+ Private Key Usage Period
+
+
+ Subject Alternative Name
+
+
+ Issuer Alternative Name
+
+
+ Basic Constraints
+
+
+ CRL Number
+
+
+ Reason code
+
+
+ Hold Instruction Code
+
+
+ Invalidity Date
+
+
+ Delta CRL indicator
+
+
+ Issuing Distribution Point
+
+
+ Certificate Issuer
+
+
+ Name Constraints
+
+
+ CRL Distribution Points
+
+
+ Certificate Policies
+
+
+ Policy Mappings
+
+
+ Authority Key Identifier
+
+
+ Policy Constraints
+
+
+ Extended Key Usage
+
+
+ Freshest CRL
+
+
+ Inhibit Any Policy
+
+
+ Authority Info Access
+
+
+ Subject Info Access
+
+
+ Logo Type
+
+
+ BiometricInfo
+
+
+ QCStatements
+
+
+ Audit identity extension in attribute certificates.
+
+
+ NoRevAvail extension in attribute certificates.
+
+
+ TargetInformation extension in attribute certificates.
+
+
+ Constructor from Asn1Sequence.
+
+ the extensions are a list of constructed sequences, either with (Oid, OctetString) or (Oid, Boolean, OctetString)
+
+
+ constructor from a table of extensions.
+
+ it's is assumed the table contains Oid/string pairs.
+
+
+ Constructor from a table of extensions with ordering.
+
+ It's is assumed the table contains Oid/string pairs.
+
+
+ Constructor from two vectors
+
+ @param objectIDs an ArrayList of the object identifiers.
+ @param values an ArrayList of the extension values.
+
+
+ return the extension represented by the object identifier
+ passed in.
+
+ @return the extension if it's present, null otherwise.
+
+
+
+
+
+ return an Enumeration of the extension field's object ids.
+
+
+ Generator for X.509 extensions
+
+
+ Reset the generator
+
+
+
+ Add an extension with the given oid and the passed in value to be included
+ in the OCTET STRING associated with the extension.
+
+ OID for the extension.
+ True if critical, false otherwise.
+ The ASN.1 object to be included in the extension.
+
+
+
+ Add an extension with the given oid and the passed in byte array to be wrapped
+ in the OCTET STRING associated with the extension.
+
+ OID for the extension.
+ True if critical, false otherwise.
+ The byte array to be wrapped.
+
+
+ Generate an X509Extensions object based on the current state of the generator.
+ An X509Extensions object
+
+
+ Return true if there are no extension present in this generator.
+ True if empty, false otherwise
+
+
+
+ RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
+
+ RelativeDistinguishedName ::= SET SIZE (1..MAX) OF AttributeTypeAndValue
+
+ AttributeTypeAndValue ::= SEQUENCE {
+ type OBJECT IDENTIFIER,
+ value ANY }
+
+
+
+ country code - StringType(SIZE(2))
+
+
+ organization - StringType(SIZE(1..64))
+
+
+ organizational unit name - StringType(SIZE(1..64))
+
+
+ Title
+
+
+ common name - StringType(SIZE(1..64))
+
+
+ street - StringType(SIZE(1..64))
+
+
+ device serial number name - StringType(SIZE(1..64))
+
+
+ locality name - StringType(SIZE(1..64))
+
+
+ state, or province name - StringType(SIZE(1..64))
+
+
+ Naming attributes of type X520name
+
+
+ businessCategory - DirectoryString(SIZE(1..128)
+
+
+ postalCode - DirectoryString(SIZE(1..40)
+
+
+ dnQualifier - DirectoryString(SIZE(1..64)
+
+
+ RFC 3039 Pseudonym - DirectoryString(SIZE(1..64)
+
+
+ RFC 3039 DateOfBirth - GeneralizedTime - YYYYMMDD000000Z
+
+
+ RFC 3039 PlaceOfBirth - DirectoryString(SIZE(1..128)
+
+
+ RFC 3039 DateOfBirth - PrintableString (SIZE(1)) -- "M", "F", "m" or "f"
+
+
+ RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166
+ codes only
+
+
+ RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166
+ codes only
+
+
+ ISIS-MTT NameAtBirth - DirectoryString(SIZE(1..64)
+
+
+ RFC 3039 PostalAddress - SEQUENCE SIZE (1..6) OF
+ DirectoryString(SIZE(1..30))
+
+
+ RFC 2256 dmdName
+
+
+ id-at-telephoneNumber
+
+
+ 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.
+
+
+ more from PKCS#9
+
+
+ email address in Verisign certificates
+
+
+ LDAP User id.
+
+
+ default look up table translating OID values into their common symbols following
+ the convention in RFC 2253 with a few extras
+
+
+ look up table translating OID values into their common symbols following the convention in RFC 2253
+
+
+ look up table translating OID values into their common symbols following the convention in RFC 1779
+
+
+
+ look up table translating common symbols into their OIDS.
+
+
+ Return a X509Name based on the passed in tagged object.
+
+ @param obj tag object holding name.
+ @param explicitly true if explicitly tagged false otherwise.
+ @return the X509Name
+
+
+ Constructor from Asn1Sequence
+
+ the principal will be a list of constructed sets, each containing an (OID, string) pair.
+
+
+ Constructor from a table of attributes with ordering.
+
+ it's is assumed the table contains OID/string pairs, and the contents
+ of the table are copied into an internal table as part of the
+ construction process. The ordering ArrayList should contain the OIDs
+ in the order they are meant to be encoded or printed in ToString.
+
+
+ Constructor from a table of attributes with ordering.
+
+ it's is assumed the table contains OID/string pairs, and the contents
+ of the table are copied into an internal table as part of the
+ construction process. The ordering ArrayList should contain the OIDs
+ in the order they are meant to be encoded or printed in ToString.
+
+ The passed in converter will be used to convert the strings into their
+ ASN.1 counterparts.
+
+
+ Takes two vectors one of the oids and the other of the values.
+
+
+ Takes two vectors one of the oids and the other of the values.
+
+ The passed in converter will be used to convert the strings into their
+ ASN.1 counterparts.
+
+
+ Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ some such, converting it into an ordered set of name attributes.
+
+
+ Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ some such, converting it into an ordered set of name attributes with each
+ string value being converted to its associated ASN.1 type using the passed
+ in converter.
+
+
+ Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ some such, converting it into an ordered set of name attributes. If reverse
+ is true, create the encoded version of the sequence starting from the
+ last element in the string.
+
+
+ Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ some such, converting it into an ordered set of name attributes with each
+ string value being converted to its associated ASN.1 type using the passed
+ in converter. If reverse is true the ASN.1 sequence representing the DN will
+ be built by starting at the end of the string, rather than the start.
+
+
+ Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ some such, converting it into an ordered set of name attributes. lookUp
+ should provide a table of lookups, indexed by lowercase only strings and
+ yielding a DerObjectIdentifier, other than that OID. and numeric oids
+ will be processed automatically.
+
+ If reverse is true, create the encoded version of the sequence
+ starting from the last element in the string.
+ @param reverse true if we should start scanning from the end (RFC 2553).
+ @param lookUp table of names and their oids.
+ @param dirName the X.500 string to be parsed.
+
+
+ Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ some such, converting it into an ordered set of name attributes. lookUp
+ should provide a table of lookups, indexed by lowercase only strings and
+ yielding a DerObjectIdentifier, other than that OID. and numeric oids
+ will be processed automatically. The passed in converter is used to convert the
+ string values to the right of each equals sign to their ASN.1 counterparts.
+
+ @param reverse true if we should start scanning from the end, false otherwise.
+ @param lookUp table of names and oids.
+ @param dirName the string dirName
+ @param converter the converter to convert string values into their ASN.1 equivalents
+
+
+ return an IList of the oids in the name, in the order they were found.
+
+
+ return an IList of the values found in the name, in the order they
+ were found.
+
+
+ return an IList of the values found in the name, in the order they
+ were found, with the DN label corresponding to passed in oid.
+
+
+ The X509Name object to test equivalency against.
+ If true, the order of elements must be the same,
+ as well as the values associated with each element.
+
+
+ test for equivalence - note: case is ignored.
+
+
+ convert the structure to a string - if reverse is true the
+ oids and values are listed out starting with the last element
+ in the sequence (ala RFC 2253), otherwise the string will begin
+ with the first element of the structure. If no string definition
+ for the oid is found in oidSymbols the string value of the oid is
+ added. Two standard symbol tables are provided DefaultSymbols, and
+ RFC2253Symbols as part of this class.
+
+ @param reverse if true start at the end of the sequence and work back.
+ @param oidSymbols look up table strings for oids.
+
+
+ determines whether or not strings should be processed and printed
+ from back to front.
+
+
+ class for breaking up an X500 Name into it's component tokens, ala
+ java.util.StringTokenizer. We need this class as some of the
+ lightweight Java environment don't support classes like
+ StringTokenizer.
+
+
+ ASN.1 def for Diffie-Hellman key exchange KeySpecificInfo structure. See
+ RFC 2631, or X9.42, for further details.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ ANS.1 def for Diffie-Hellman key exchange OtherInfo structure. See
+ RFC 2631, or X9.42, for further details.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ table of the current named curves defined in X.962 EC-DSA.
+
+
+ return the X9ECParameters object for the named curve represented by
+ the passed in object identifier. Null if the curve isn't present.
+
+ @param oid an object identifier representing a named curve, if present.
+
+
+ return the object identifier signified by the passed in name. Null
+ if there is no object identifier associated with name.
+
+ @return the object identifier associated with name, if present.
+
+
+ return the named curve name represented by the given object identifier.
+
+
+ returns an enumeration containing the name strings for curves
+ contained in this structure.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ ASN.1 def for Elliptic-Curve Curve structure. See
+ X9.62, for further details.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ Curve ::= Sequence {
+ a FieldElement,
+ b FieldElement,
+ seed BIT STRING OPTIONAL
+ }
+
+
+
+ ASN.1 def for Elliptic-Curve ECParameters structure. See
+ X9.62, for further details.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+
+
+ class for describing an ECPoint as a Der object.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ ECPoint ::= OCTET STRING
+
+
+ Octet string produced using ECPoint.GetEncoded().
+
+
+ Class for processing an ECFieldElement as a DER object.
+
+
+ Produce an object suitable for an Asn1OutputStream.
+
+ FieldElement ::= OCTET STRING
+
+
+
+
if q is an odd prime then the field element is
+ processed as an Integer and converted to an octet string
+ according to x 9.62 4.3.1.
+
if q is 2m then the bit string
+ contained in the field element is converted into an octet
+ string with the same ordering padded at the front if necessary.
+
+
+
+
+
+ ASN.1 def for Elliptic-Curve Field ID structure. See
+ X9.62, for further details.
+
+
+ Constructor for elliptic curves over prime fields
+ F2.
+ @param primeP The prime p defining the prime field.
+
+
+ Constructor for elliptic curves over binary fields
+ F2m.
+ @param m The exponent m of
+ F2m.
+ @param k1 The integer k1 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param k2 The integer k2 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param k3 The integer k3 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z)..
+
+
+ Produce a Der encoding of the following structure.
+
+
+
+ X9.42
+
+
+ id-dsa-with-sha1 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
+ us(840) x9-57 (10040) x9cm(4) 3 }
+
+
+ X9.63
+
+
+ reader for Base64 armored objects - read the headers and then start returning
+ bytes when the data is reached. An IOException is thrown if the CRC check
+ fails.
+
+
+ decode the base 64 encoded input data.
+
+ @return the offset the data starts in out.
+
+
+ Create a stream for reading a PGP armoured message, parsing up to a header
+ and then reading the data that follows.
+
+ @param input
+
+
+ Create an armoured input stream which will assume the data starts
+ straight away, or parse for headers first depending on the value of
+ hasHeaders.
+
+ @param input
+ @param hasHeaders true if headers are to be looked for, false otherwise.
+
+
+ @return true if we are inside the clear text section of a PGP
+ signed message.
+
+
+ @return true if the stream is actually at end of file.
+
+
+ Return the armor header line (if there is one)
+ @return the armor header line, null if none present.
+
+
+ Return the armor headers (the lines after the armor header line),
+ @return an array of armor headers, null if there aren't any.
+
+
+ Basic output stream.
+
+
+ encode the input data producing a base 64 encoded byte array.
+
+
+ Set an additional header entry.
+
+ @param name the name of the header entry.
+ @param v the value of the header entry.
+
+
+ Reset the headers to only contain a Version string.
+
+
+ Start a clear text signed message.
+ @param hashAlgorithm
+
+
+ Note: Dispose does nor Dispose the underlying stream. So it is possible to write
+ multiple objects using armoring to a single stream.
+
+
+ Basic type for a image attribute packet.
+
+
+ Basic type for a user attribute sub-packet.
+
+
+ return the generic data making up the packet.
+
+
+ Reader for PGP objects.
+
+
+ Returns the next packet tag in the stream.
+
+
+
+ A stream that overlays our input stream, allowing the user to only read a segment of it.
+ NB: dataLength will be negative if the segment length is in the upper range above 2**31.
+
+
+
+ Base class for a PGP object.
+
+
+ Basic output stream.
+
+
+ Create a stream representing a general packet.
+ Output stream to write to.
+
+
+ Create a stream representing an old style partial object.
+ Output stream to write to.
+ The packet tag for the object.
+
+
+ Create a stream representing a general packet.
+ Output stream to write to.
+ Packet tag.
+ Size of chunks making up the packet.
+ If true, the header is written out in old format.
+
+
+ Create a new style partial input stream buffered into chunks.
+ Output stream to write to.
+ Packet tag.
+ Size of chunks making up the packet.
+
+
+ Create a new style partial input stream buffered into chunks.
+ Output stream to write to.
+ Packet tag.
+ Buffer to use for collecting chunks.
+
+
+ Flush the underlying stream.
+
+
+ Finish writing out the current packet without closing the underlying stream.
+
+
+ Generic compressed data object.
+
+
+ Note: you can only read from this once...
+
+
+ The algorithm tag value.
+
+
+ Basic tags for compression algorithms.
+
+
+ Basic type for a PGP packet.
+
+
+ Base class for a DSA public key.
+
+
+ Base interface for a PGP key.
+
+
+
+ The base format for this key - in the case of the symmetric keys it will generally
+ be raw indicating that the key is just a straight byte representation, for an asymmetric
+ key the format will be PGP, indicating the key is a string of MPIs encoded in PGP format.
+
+ "RAW" or "PGP".
+
+
+ The stream to read the packet from.
+
+
+ Return the standard PGP encoding of the key.
+
+
+ The format, as a string, always "PGP".
+
+
+ Base class for a DSA secret key.
+
+
+ @param in
+
+
+ Return the standard PGP encoding of the key.
+
+
+ The format, as a string, always "PGP".
+
+
+ @return x
+
+
+ Base class for an ElGamal public key.
+
+
+ Return the standard PGP encoding of the key.
+
+
+ The format, as a string, always "PGP".
+
+
+ Base class for an ElGamal secret key.
+
+
+ @param in
+
+
+ @param x
+
+
+ Return the standard PGP encoding of the key.
+
+
+ The format, as a string, always "PGP".
+
+
+ Basic packet for an experimental packet.
+
+
+ Basic tags for hash algorithms.
+
+
+ Generic literal data packet.
+
+
+ The format tag value.
+
+
+ The modification time of the file in milli-seconds (since Jan 1, 1970 UTC)
+
+
+ Basic type for a marker packet.
+
+
+ Basic packet for a modification detection code packet.
+
+
+ A multiple precision integer
+
+
+ Generic signature object
+
+
+ The encryption algorithm tag.
+
+
+ The hash algorithm tag.
+
+
+ Basic PGP packet tag types.
+
+
+ Public Key Algorithm tag numbers.
+
+
+ Basic packet for a PGP public key.
+
+
+ Basic packet for a PGP public key.
+
+
+ Construct a version 4 public key packet.
+
+
+ Basic packet for a PGP public subkey
+
+
+ Construct a version 4 public subkey packet.
+
+
+ Base class for an RSA public key.
+
+
+ Construct an RSA public key from the passed in stream.
+
+
+ The modulus.
+ The public exponent.
+
+
+ Return the standard PGP encoding of the key.
+
+
+ The format, as a string, always "PGP".
+
+
+ Base class for an RSA secret (or priate) key.
+
+
+ Return the standard PGP encoding of the key.
+
+
+ The format, as a string, always "PGP".
+
+
+ The string to key specifier class.
+
+
+ The IV for the key generation algorithm.
+
+
+ The hash algorithm.
+
+
+ The iteration count
+
+
+ The protection mode - only if GnuDummyS2K
+
+
+ Basic packet for a PGP secret key.
+
+
+ Basic packet for a PGP secret key.
+
+
+ Generic signature packet.
+
+
+ Generate a version 4 signature packet.
+
+ @param signatureType
+ @param keyAlgorithm
+ @param hashAlgorithm
+ @param hashedData
+ @param unhashedData
+ @param fingerprint
+ @param signature
+
+
+ Generate a version 2/3 signature packet.
+
+ @param signatureType
+ @param keyAlgorithm
+ @param hashAlgorithm
+ @param fingerprint
+ @param signature
+
+
+ return the signature trailer that must be included with the data
+ to reconstruct the signature
+
+ @return byte[]
+
+
+ * return the signature as a set of integers - note this is normalised to be the
+ * ASN.1 encoding of what appears in the signature packet.
+
+
+ Return the byte encoding of the signature section.
+ @return uninterpreted signature bytes.
+
+
+ return the keyId
+ @return the keyId that created the signature.
+
+
+ Return the creation time in milliseconds since 1 Jan., 1970 UTC.
+
+
+ Basic type for a PGP Signature sub-packet.
+
+
+ Return the generic data making up the packet.
+
+
+ reader for signature sub-packets
+
+
+ Basic PGP signature sub-packet tag types.
+
+
+ Packet embedded signature
+
+
+ packet giving signature creation time.
+
+
+ packet giving signature creation time.
+
+
+ packet giving time after creation at which the key expires.
+
+
+ Return the number of seconds after creation time a key is valid for.
+
+ @return second count for key validity.
+
+
+ Packet holding the key flag values.
+
+
+
+ Return the flag values contained in the first 4 octets (note: at the moment
+ the standard only uses the first one).
+
+
+
+ Class provided a NotationData object according to
+ RFC2440, Chapter 5.2.3.15. Notation Data
+
+
+ packet giving signature creation time.
+
+
+ packet giving whether or not the signature is signed using the primary user ID for the key.
+
+
+ packet giving whether or not is revocable.
+
+
+
+ Represents revocation key OpenPGP signature sub packet.
+
+
+
+
+ Represents revocation reason OpenPGP signature sub packet.
+
+
+
+ packet giving signature creation time.
+
+
+ packet giving signature expiration time.
+
+
+ return time in seconds before signature expires after creation time.
+
+
+ packet giving the User ID of the signer.
+
+
+ packet giving trust.
+
+
+ Basic type for a symmetric key encrypted packet.
+
+
+ Basic tags for symmetric key algorithms
+
+
+ Basic type for a symmetric encrypted session key packet
+
+
+ @return byte[]
+
+
+ @return int
+
+
+ @return S2k
+
+
+ @return int
+
+
+ Basic type for a trust packet.
+
+
+ Basic type for a user attribute packet.
+
+
+ reader for user attribute sub-packets
+
+
+ Basic PGP user attribute sub-packet tag types.
+
+
+ Basic type for a user ID packet.
+
+
+
+ The 'Signature' parameter is only available when generating unsigned attributes.
+
+
+
+ containing class for an CMS Authenticated Data object
+
+
+ return a store of the intended recipients for this message
+
+
+ return a table of the digested attributes indexed by
+ the OID of the attribute.
+
+
+ return a table of the undigested attributes indexed by
+ the OID of the attribute.
+
+
+ return the ASN.1 encoded representation of this object.
+
+
+ return the object identifier for the content MAC algorithm.
+
+
+ return the ContentInfo
+
+
+ General class for generating a CMS authenticated-data message.
+
+ A simple example of usage.
+
+
+ CMSAuthenticatedDataGenerator fact = new CMSAuthenticatedDataGenerator();
+
+ fact.addKeyTransRecipient(cert);
+
+ CMSAuthenticatedData data = fact.generate(content, algorithm, "BC");
+
+
+
+ General class for generating a CMS enveloped-data message.
+
+ A simple example of usage.
+
+
+ CMSEnvelopedDataGenerator fact = new CMSEnvelopedDataGenerator();
+
+ fact.addKeyTransRecipient(cert);
+
+ CMSEnvelopedData data = fact.generate(content, algorithm, "BC");
+
+
+
+ Constructor allowing specific source of randomness
+ Instance of SecureRandom to use.
+
+
+ add a recipient.
+
+ @param cert recipient's public key certificate
+ @exception ArgumentException if there is a problem with the certificate
+
+
+ add a recipient
+
+ @param key the public key used by the recipient
+ @param subKeyId the identifier for the recipient's public key
+ @exception ArgumentException if there is a problem with the key
+
+
+ add a KEK recipient.
+ @param key the secret key to use for wrapping
+ @param keyIdentifier the byte string that identifies the key
+
+
+ add a KEK recipient.
+ @param key the secret key to use for wrapping
+ @param keyIdentifier the byte string that identifies the key
+
+
+ Add a key agreement based recipient.
+
+ @param agreementAlgorithm key agreement algorithm to use.
+ @param senderPrivateKey private key to initialise sender side of agreement with.
+ @param senderPublicKey sender public key to include with message.
+ @param recipientCert recipient's public key certificate.
+ @param cekWrapAlgorithm OID for key wrapping algorithm to use.
+ @exception SecurityUtilityException if the algorithm requested cannot be found
+ @exception InvalidKeyException if the keys are inappropriate for the algorithm specified
+
+
+ Add multiple key agreement based recipients (sharing a single KeyAgreeRecipientInfo structure).
+
+ @param agreementAlgorithm key agreement algorithm to use.
+ @param senderPrivateKey private key to initialise sender side of agreement with.
+ @param senderPublicKey sender public key to include with message.
+ @param recipientCerts recipients' public key certificates.
+ @param cekWrapAlgorithm OID for key wrapping algorithm to use.
+ @exception SecurityUtilityException if the algorithm requested cannot be found
+ @exception InvalidKeyException if the keys are inappropriate for the algorithm specified
+
+
+ base constructor
+
+
+ constructor allowing specific source of randomness
+
+ @param rand instance of SecureRandom to use
+
+
+ base constructor
+
+
+ constructor allowing specific source of randomness
+ @param rand instance of SecureRandom to use
+
+
+ generate an enveloped object that contains an CMS Enveloped Data
+ object using the given provider and the passed in key generator.
+
+
+ generate an authenticated object that contains an CMS Authenticated Data object
+
+
+ Parsing class for an CMS Authenticated Data object from an input stream.
+
+ Note: that because we are in a streaming mode only one recipient can be tried and it is important
+ that the methods on the parser are called in the appropriate order.
+
+
+ Example of use - assuming the first recipient matches the private key we have.
+
+ CMSAuthenticatedDataParser ad = new CMSAuthenticatedDataParser(inputStream);
+
+ RecipientInformationStore recipients = ad.getRecipientInfos();
+
+ Collection c = recipients.getRecipients();
+ Iterator it = c.iterator();
+
+ if (it.hasNext())
+ {
+ RecipientInformation recipient = (RecipientInformation)it.next();
+
+ CMSTypedStream recData = recipient.getContentStream(privateKey, "BC");
+
+ processDataStream(recData.getContentStream());
+
+ if (!Arrays.equals(ad.getMac(), recipient.getMac())
+ {
+ System.err.println("Data corrupted!!!!");
+ }
+ }
+
+ Note: this class does not introduce buffering - if you are processing large files you should create
+ the parser with:
+
+ CMSAuthenticatedDataParser ep = new CMSAuthenticatedDataParser(new BufferedInputStream(inputStream, bufSize));
+
+ where bufSize is a suitably large buffer size.
+
+
+
+ Close the underlying data stream.
+ @throws IOException if the close fails.
+
+
+ return a store of the intended recipients for this message
+
+
+ return a table of the unauthenticated attributes indexed by
+ the OID of the attribute.
+ @exception java.io.IOException
+
+
+ return a table of the unauthenticated attributes indexed by
+ the OID of the attribute.
+ @exception java.io.IOException
+
+
+ return the object identifier for the mac algorithm.
+
+
+ return the ASN.1 encoded encryption algorithm parameters, or null if
+ there aren't any.
+
+
+ General class for generating a CMS authenticated-data message stream.
+
+
+
+
+ base constructor
+
+
+ constructor allowing specific source of randomness
+ @param rand instance of SecureRandom to use
+
+
+ Set the underlying string size for encapsulated data
+
+ @param bufferSize length of octet strings to buffer the data.
+
+
+ Use a BER Set to store the recipient information
+
+
+ generate an enveloped object that contains an CMS Enveloped Data
+ object using the given provider and the passed in key generator.
+ @throws java.io.IOException
+
+
+ generate an enveloped object that contains an CMS Enveloped Data object
+
+
+ generate an enveloped object that contains an CMS Enveloped Data object
+
+
+ containing class for an CMS AuthEnveloped Data object
+
+
+ containing class for an CMS Compressed Data object
+
+
+ Return the uncompressed content.
+
+ @return the uncompressed content
+ @throws CmsException if there is an exception uncompressing the data.
+
+
+ Return the uncompressed content, throwing an exception if the data size
+ is greater than the passed in limit. If the content is exceeded getCause()
+ on the CMSException will contain a StreamOverflowException
+
+ @param limit maximum number of bytes to read
+ @return the content read
+ @throws CMSException if there is an exception uncompressing the data.
+
+
+ return the ASN.1 encoded representation of this object.
+
+
+ return the ContentInfo
+
+
+ * General class for generating a compressed CMS message.
+ *
+ * A simple example of usage.
+ *
+ *
+ * CMSCompressedDataGenerator fact = new CMSCompressedDataGenerator();
+ * CMSCompressedData data = fact.Generate(content, algorithm);
+ *
+ *
+
+
+ Generate an object that contains an CMS Compressed Data
+
+
+ Class for reading a CMS Compressed Data stream.
+
+ CMSCompressedDataParser cp = new CMSCompressedDataParser(inputStream);
+
+ process(cp.GetContent().GetContentStream());
+
+ Note: this class does not introduce buffering - if you are processing large files you should create
+ the parser with:
+
+ CMSCompressedDataParser ep = new CMSCompressedDataParser(new BufferedInputStream(inputStream, bufSize));
+
+ where bufSize is a suitably large buffer size.
+
+
+ General class for generating a compressed CMS message stream.
+
+ A simple example of usage.
+
+
+ CMSCompressedDataStreamGenerator gen = new CMSCompressedDataStreamGenerator();
+
+ Stream cOut = gen.Open(outputStream, CMSCompressedDataStreamGenerator.ZLIB);
+
+ cOut.Write(data);
+
+ cOut.Close();
+
+
+
+ base constructor
+
+
+ Set the underlying string size for encapsulated data
+
+ @param bufferSize length of octet strings to buffer the data.
+
+
+ containing class for an CMS Enveloped Data object
+
+
+ return a store of the intended recipients for this message
+
+
+ return a table of the unprotected attributes indexed by
+ the OID of the attribute.
+
+
+ return the ASN.1 encoded representation of this object.
+
+
+ return the object identifier for the content encryption algorithm.
+
+
+ return the ContentInfo
+
+
+
+ General class for generating a CMS enveloped-data message.
+
+ A simple example of usage.
+
+
+ CmsEnvelopedDataGenerator fact = new CmsEnvelopedDataGenerator();
+
+ fact.AddKeyTransRecipient(cert);
+
+ CmsEnvelopedData data = fact.Generate(content, algorithm);
+
+
+
+
+ Constructor allowing specific source of randomness
+ Instance of SecureRandom to use.
+
+
+
+ Generate an enveloped object that contains a CMS Enveloped Data
+ object using the passed in key generator.
+
+
+
+ Generate an enveloped object that contains an CMS Enveloped Data object.
+
+
+ Generate an enveloped object that contains an CMS Enveloped Data object.
+
+
+ Parsing class for an CMS Enveloped Data object from an input stream.
+
+ Note: that because we are in a streaming mode only one recipient can be tried and it is important
+ that the methods on the parser are called in the appropriate order.
+
+
+ Example of use - assuming the first recipient matches the private key we have.
+
+ CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(inputStream);
+
+ RecipientInformationStore recipients = ep.GetRecipientInfos();
+
+ Collection c = recipients.getRecipients();
+ Iterator it = c.iterator();
+
+ if (it.hasNext())
+ {
+ RecipientInformation recipient = (RecipientInformation)it.next();
+
+ CMSTypedStream recData = recipient.getContentStream(privateKey);
+
+ processDataStream(recData.getContentStream());
+ }
+
+ Note: this class does not introduce buffering - if you are processing large files you should create
+ the parser with:
+
+ CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(new BufferedInputStream(inputStream, bufSize));
+
+ where bufSize is a suitably large buffer size.
+
+
+
+ return a store of the intended recipients for this message
+
+
+ return a table of the unprotected attributes indexed by
+ the OID of the attribute.
+ @throws IOException
+
+
+ return the object identifier for the content encryption algorithm.
+
+
+ return the ASN.1 encoded encryption algorithm parameters, or null if
+ there aren't any.
+
+
+ General class for generating a CMS enveloped-data message stream.
+
+
+
+
+ Constructor allowing specific source of randomness
+ Instance of SecureRandom to use.
+
+
+ Set the underlying string size for encapsulated data.
+ Length of octet strings to buffer the data.
+
+
+ Use a BER Set to store the recipient information.
+
+
+
+ Generate an enveloped object that contains an CMS Enveloped Data
+ object using the passed in key generator.
+
+
+
+ generate an enveloped object that contains an CMS Enveloped Data object
+ @throws IOException
+
+
+ generate an enveloped object that contains an CMS Enveloped Data object
+ @throws IOException
+
+
+ all parameter classes implement this.
+
+
+
+ Generic routine to copy out the data we want processed.
+
+
+ This routine may be called multiple times.
+
+
+
+ a holding class for a byte array of data to be processed.
+
+
+ A clone of the byte array
+
+
+ general class for handling a pkcs7-signature message.
+
+ A simple example of usage - note, in the example below the validity of
+ the certificate isn't verified, just the fact that one of the certs
+ matches the given signer...
+
+
+
+
+ Content with detached signature, digests precomputed
+
+ @param hashes a map of precomputed digests for content indexed by name of hash.
+ @param sigBlock the signature object.
+
+
+ base constructor - content with detached signature.
+
+ @param signedContent the content that was signed.
+ @param sigData the signature object.
+
+
+ base constructor - with encapsulated content
+
+
+ return the collection of signers that are associated with the
+ signatures for the message.
+
+
+ return a X509Store containing the attribute certificates, if any, contained
+ in this message.
+
+ @param type type of store to create
+ @return a store of attribute certificates
+ @exception NoSuchStoreException if the store type isn't available.
+ @exception CmsException if a general exception prevents creation of the X509Store
+
+
+ return a X509Store containing the public key certificates, if any, contained
+ in this message.
+
+ @param type type of store to create
+ @return a store of public key certificates
+ @exception NoSuchStoreException if the store type isn't available.
+ @exception CmsException if a general exception prevents creation of the X509Store
+
+
+ return a X509Store containing CRLs, if any, contained
+ in this message.
+
+ @param type type of store to create
+ @return a store of CRLs
+ @exception NoSuchStoreException if the store type isn't available.
+ @exception CmsException if a general exception prevents creation of the X509Store
+
+
+ return the ASN.1 encoded representation of this object.
+
+
+ Replace the signerinformation store associated with this
+ CmsSignedData object with the new one passed in. You would
+ probably only want to do this if you wanted to change the unsigned
+ attributes associated with a signer, or perhaps delete one.
+
+ @param signedData the signed data object to be used as a base.
+ @param signerInformationStore the new signer information store to use.
+ @return a new signed data object.
+
+
+ Replace the certificate and CRL information associated with this
+ CmsSignedData object with the new one passed in.
+
+ @param signedData the signed data object to be used as a base.
+ @param x509Certs the new certificates to be used.
+ @param x509Crls the new CRLs to be used.
+ @return a new signed data object.
+ @exception CmsException if there is an error processing the stores
+
+
+ Return the version number for this object.
+
+
+
+ Return the DerObjectIdentifier associated with the encapsulated
+ content info structure carried in the signed data.
+
+
+
+ return the ContentInfo
+
+
+ * general class for generating a pkcs7-signature message.
+ *
+ *
+
+
+ Default type for the signed data.
+
+
+ Constructor allowing specific source of randomness
+ Instance of SecureRandom to use.
+
+
+ Add the attribute certificates contained in the passed in store to the
+ generator.
+
+ @param store a store of Version 2 attribute certificates
+ @throws CmsException if an error occurse processing the store.
+
+
+ Add a store of precalculated signers to the generator.
+
+ @param signerStore store of signers
+
+
+ Return a map of oids and byte arrays representing the digests calculated on the content during
+ the last generate.
+
+ @return a map of oids (as String objects) and byte[] representing digests.
+
+
+ Constructor allowing specific source of randomness
+ Instance of SecureRandom to use.
+
+
+ * add a signer - no attributes other than the default ones will be
+ * provided here.
+ *
+ * @param key signing key to use
+ * @param cert certificate containing corresponding public key
+ * @param digestOID digest algorithm OID
+
+
+ add a signer, specifying the digest encryption algorithm to use - no attributes other than the default ones will be
+ provided here.
+
+ @param key signing key to use
+ @param cert certificate containing corresponding public key
+ @param encryptionOID digest encryption algorithm OID
+ @param digestOID digest algorithm OID
+
+
+ add a signer - no attributes other than the default ones will be
+ provided here.
+
+
+ add a signer, specifying the digest encryption algorithm to use - no attributes other than the default ones will be
+ provided here.
+
+
+ * add a signer with extra signed/unsigned attributes.
+ *
+ * @param key signing key to use
+ * @param cert certificate containing corresponding public key
+ * @param digestOID digest algorithm OID
+ * @param signedAttr table of attributes to be included in signature
+ * @param unsignedAttr table of attributes to be included as unsigned
+
+
+ add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes.
+
+ @param key signing key to use
+ @param cert certificate containing corresponding public key
+ @param encryptionOID digest encryption algorithm OID
+ @param digestOID digest algorithm OID
+ @param signedAttr table of attributes to be included in signature
+ @param unsignedAttr table of attributes to be included as unsigned
+
+
+ * add a signer with extra signed/unsigned attributes.
+ *
+ * @param key signing key to use
+ * @param subjectKeyID subjectKeyID of corresponding public key
+ * @param digestOID digest algorithm OID
+ * @param signedAttr table of attributes to be included in signature
+ * @param unsignedAttr table of attributes to be included as unsigned
+
+
+ add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes.
+
+ @param key signing key to use
+ @param subjectKeyID subjectKeyID of corresponding public key
+ @param encryptionOID digest encryption algorithm OID
+ @param digestOID digest algorithm OID
+ @param signedAttr table of attributes to be included in signature
+ @param unsignedAttr table of attributes to be included as unsigned
+
+
+ add a signer with extra signed/unsigned attributes based on generators.
+
+
+ add a signer, specifying the digest encryption algorithm, with extra signed/unsigned attributes based on generators.
+
+
+ add a signer with extra signed/unsigned attributes based on generators.
+
+
+ add a signer, including digest encryption algorithm, with extra signed/unsigned attributes based on generators.
+
+
+ generate a signed object that for a CMS Signed Data object
+
+
+ generate a signed object that for a CMS Signed Data
+ object - if encapsulate is true a copy
+ of the message will be included in the signature. The content type
+ is set according to the OID represented by the string signedContentType.
+
+
+ generate a signed object that for a CMS Signed Data
+ object - if encapsulate is true a copy
+ of the message will be included in the signature with the
+ default content type "data".
+
+
+ generate a set of one or more SignerInformation objects representing counter signatures on
+ the passed in SignerInformation object.
+
+ @param signer the signer to be countersigned
+ @param sigProvider the provider to be used for counter signing.
+ @return a store containing the signers.
+
+
+ Parsing class for an CMS Signed Data object from an input stream.
+
+ Note: that because we are in a streaming mode only one signer can be tried and it is important
+ that the methods on the parser are called in the appropriate order.
+
+
+ A simple example of usage for an encapsulated signature.
+
+
+ Two notes: first, in the example below the validity of
+ the certificate isn't verified, just the fact that one of the certs
+ matches the given signer, and, second, because we are in a streaming
+ mode the order of the operations is important.
+
+ Note also: this class does not introduce buffering - if you are processing large files you should create
+ the parser with:
+
+ CmsSignedDataParser ep = new CmsSignedDataParser(new BufferedInputStream(encapSigData, bufSize));
+
+ where bufSize is a suitably large buffer size.
+
+
+ base constructor - with encapsulated content
+
+
+ base constructor
+
+ @param signedContent the content that was signed.
+ @param sigData the signature object.
+
+
+ return the collection of signers that are associated with the
+ signatures for the message.
+ @throws CmsException
+
+
+ return a X509Store containing the attribute certificates, if any, contained
+ in this message.
+
+ @param type type of store to create
+ @return a store of attribute certificates
+ @exception org.bouncycastle.x509.NoSuchStoreException if the store type isn't available.
+ @exception CmsException if a general exception prevents creation of the X509Store
+
+
+ return a X509Store containing the public key certificates, if any, contained
+ in this message.
+
+ @param type type of store to create
+ @return a store of public key certificates
+ @exception NoSuchStoreException if the store type isn't available.
+ @exception CmsException if a general exception prevents creation of the X509Store
+
+
+ return a X509Store containing CRLs, if any, contained
+ in this message.
+
+ @param type type of store to create
+ @return a store of CRLs
+ @exception NoSuchStoreException if the store type isn't available.
+ @exception CmsException if a general exception prevents creation of the X509Store
+
+
+ Replace the signerinformation store associated with the passed
+ in message contained in the stream original with the new one passed in.
+ You would probably only want to do this if you wanted to change the unsigned
+ attributes associated with a signer, or perhaps delete one.
+
+ The output stream is returned unclosed.
+
+ @param original the signed data stream to be used as a base.
+ @param signerInformationStore the new signer information store to use.
+ @param out the stream to Write the new signed data object to.
+ @return out.
+
+
+ Replace the certificate and CRL information associated with this
+ CMSSignedData object with the new one passed in.
+
+ The output stream is returned unclosed.
+
+ @param original the signed data stream to be used as a base.
+ @param certsAndCrls the new certificates and CRLs to be used.
+ @param out the stream to Write the new signed data object to.
+ @return out.
+ @exception CmsException if there is an error processing the CertStore
+
+
+ Return the version number for the SignedData object
+
+ @return the version number
+
+
+
+ Return the DerObjectIdentifier associated with the encapsulated
+ content info structure carried in the signed data.
+
+
+
+ General class for generating a pkcs7-signature message stream.
+
+
+
+ Constructor allowing specific source of randomness
+ Instance of SecureRandom to use.
+
+
+ Set the underlying string size for encapsulated data
+
+ @param bufferSize length of octet strings to buffer the data.
+
+
+ add a signer - no attributes other than the default ones will be
+ provided here.
+ @throws NoSuchAlgorithmException
+ @throws InvalidKeyException
+
+
+ add a signer, specifying the digest encryption algorithm - no attributes other than the default ones will be
+ provided here.
+ @throws NoSuchProviderException
+ @throws NoSuchAlgorithmException
+ @throws InvalidKeyException
+
+
+ add a signer with extra signed/unsigned attributes.
+ @throws NoSuchAlgorithmException
+ @throws InvalidKeyException
+
+
+ add a signer with extra signed/unsigned attributes - specifying digest
+ encryption algorithm.
+ @throws NoSuchProviderException
+ @throws NoSuchAlgorithmException
+ @throws InvalidKeyException
+
+
+ add a signer - no attributes other than the default ones will be
+ provided here.
+ @throws NoSuchAlgorithmException
+ @throws InvalidKeyException
+
+
+ add a signer - no attributes other than the default ones will be
+ provided here.
+ @throws NoSuchProviderException
+ @throws NoSuchAlgorithmException
+ @throws InvalidKeyException
+
+
+ add a signer with extra signed/unsigned attributes.
+ @throws NoSuchAlgorithmException
+ @throws InvalidKeyException
+
+
+ generate a signed object that for a CMS Signed Data object
+
+
+ generate a signed object that for a CMS Signed Data
+ object - if encapsulate is true a copy
+ of the message will be included in the signature with the
+ default content type "data".
+
+
+ generate a signed object that for a CMS Signed Data
+ object using the given provider - if encapsulate is true a copy
+ of the message will be included in the signature with the
+ default content type "data". If dataOutputStream is non null the data
+ being signed will be written to the stream as it is processed.
+ @param out stream the CMS object is to be written to.
+ @param encapsulate true if data should be encapsulated.
+ @param dataOutputStream output stream to copy the data being signed to.
+
+
+ generate a signed object that for a CMS Signed Data
+ object - if encapsulate is true a copy
+ of the message will be included in the signature. The content type
+ is set according to the OID represented by the string signedContentType.
+
+
+ generate a signed object that for a CMS Signed Data
+ object using the given provider - if encapsulate is true a copy
+ of the message will be included in the signature. The content type
+ is set according to the OID represented by the string signedContentType.
+ @param out stream the CMS object is to be written to.
+ @param signedContentType OID for data to be signed.
+ @param encapsulate true if data should be encapsulated.
+ @param dataOutputStream output stream to copy the data being signed to.
+
+
+ Return the digest algorithm using one of the standard JCA string
+ representations rather than the algorithm identifier (if possible).
+
+
+ Return the digest encryption algorithm using one of the standard
+ JCA string representations rather than the algorithm identifier (if
+ possible).
+
+
+ Default authenticated attributes generator.
+
+
+ Initialise to use all defaults
+
+
+ Initialise with some extra attributes or overrides.
+
+ @param attributeTable initial attribute table to use.
+
+
+ Create a standard attribute table from the passed in parameters - this will
+ normally include contentType and messageDigest. If the constructor
+ using an AttributeTable was used, entries in it for contentType and
+ messageDigest will override the generated ones.
+
+ @param parameters source parameters for table generation.
+
+ @return a filled in IDictionary of attributes.
+
+
+ @param parameters source parameters
+ @return the populated attribute table
+
+
+ Default signed attributes generator.
+
+
+ Initialise to use all defaults
+
+
+ Initialise with some extra attributes or overrides.
+
+ @param attributeTable initial attribute table to use.
+
+
+ Create a standard attribute table from the passed in parameters - this will
+ normally include contentType, signingTime, and messageDigest. If the constructor
+ using an AttributeTable was used, entries in it for contentType, signingTime, and
+ messageDigest will override the generated ones.
+
+ @param parameters source parameters for table generation.
+
+ @return a filled in Hashtable of attributes.
+
+
+ @param parameters source parameters
+ @return the populated attribute table
+
+
+
+ Generate a RecipientInfo object for the given key.
+
+
+ A
+
+
+ A
+
+
+ A
+
+
+
+
+ the RecipientInfo class for a recipient who has been sent a message
+ encrypted using a secret key known to the other side.
+
+
+ Return the MAC calculated for the content stream. Note: this call is only meaningful once all
+ the content has been read.
+
+ @return byte array containing the mac.
+
+
+ * return the object identifier for the key encryption algorithm.
+ *
+ * @return OID for key encryption algorithm.
+
+
+ * return the ASN.1 encoded key encryption algorithm parameters, or null if
+ * there aren't any.
+ *
+ * @return ASN.1 encoding of key encryption algorithm parameters.
+
+
+ decrypt the content and return an input stream.
+
+
+ the RecipientInfo class for a recipient who has been sent a message
+ encrypted using key agreement.
+
+
+ decrypt the content and return an input stream.
+
+
+ the KeyTransRecipientInformation class for a recipient who has been sent a secret
+ key encrypted using their public key that needs to be used to
+ extract the message.
+
+
+ decrypt the content and return it as a byte array.
+
+
+ a basic index for an originator.
+
+
+
+ An ISet of DerObjectIdentifier objects.
+
+
+
+ the RecipientInfo class for a recipient who has been sent a message
+ encrypted using a password.
+
+
+ decrypt the content and return an input stream.
+
+
+ return the object identifier for the key derivation algorithm, or null
+ if there is none present.
+
+ @return OID for key derivation algorithm, if present.
+
+
+
+ PKCS5 scheme-2 - password converted to bytes assuming ASCII.
+
+
+
+ PKCS5 scheme-2 - password converted to bytes using UTF-8.
+
+
+ Return the first RecipientInformation object that matches the
+ passed in selector. Null if there are no matches.
+
+ @param selector to identify a recipient
+ @return a single RecipientInformation object. Null if none matches.
+
+
+ Return all recipients in the collection
+
+ @return a collection of recipients.
+
+
+ Return possible empty collection with recipients matching the passed in RecipientID
+
+ @param selector a recipient id to select against.
+ @return a collection of RecipientInformation objects.
+
+
+ Return the number of recipients in the collection.
+
+ @return number of recipients identified.
+
+
+ a basic index for a signer.
+
+
+ an expanded SignerInfo block from a CMS Signed message
+
+
+ return the content digest that was calculated during verification.
+
+
+ return the encoded signature
+
+
+ Return a SignerInformationStore containing the counter signatures attached to this
+ signer. If no counter signatures are present an empty store is returned.
+
+
+ return the DER encoding of the signed attributes.
+ @throws IOException if an encoding error occurs.
+
+
+ verify that the given public key successfully handles and confirms the
+ signature associated with this signer.
+
+
+ verify that the given certificate successfully handles and confirms
+ the signature associated with this signer and, if a signingTime
+ attribute is available, that the certificate was valid at the time the
+ signature was generated.
+
+
+ Return the base ASN.1 CMS structure that this object contains.
+
+ @return an object containing a CMS SignerInfo structure.
+
+
+ Return a signer information object with the passed in unsigned
+ attributes replacing the ones that are current associated with
+ the object passed in.
+
+ @param signerInformation the signerInfo to be used as the basis.
+ @param unsignedAttributes the unsigned attributes to add.
+ @return a copy of the original SignerInformationObject with the changed attributes.
+
+
+ Return a signer information object with passed in SignerInformationStore representing counter
+ signatures attached as an unsigned attribute.
+
+ @param signerInformation the signerInfo to be used as the basis.
+ @param counterSigners signer info objects carrying counter signature.
+ @return a copy of the original SignerInformationObject with the changed attributes.
+
+
+ return the version number for this objects underlying SignerInfo structure.
+
+
+ return the object identifier for the signature.
+
+
+ return the signature parameters, or null if there aren't any.
+
+
+ return the object identifier for the signature.
+
+
+ return the signature/encryption algorithm parameters, or null if
+ there aren't any.
+
+
+ return a table of the signed attributes - indexed by
+ the OID of the attribute.
+
+
+ return a table of the unsigned attributes indexed by
+ the OID of the attribute.
+
+
+ Return the first SignerInformation object that matches the
+ passed in selector. Null if there are no matches.
+
+ @param selector to identify a signer
+ @return a single SignerInformation object. Null if none matches.
+
+
+ An ICollection of all signers in the collection
+
+
+ Return possible empty collection with signers matching the passed in SignerID
+
+ @param selector a signer id to select against.
+ @return a collection of SignerInformation objects.
+
+
+ The number of signers in the collection.
+
+
+ Basic generator that just returns a preconstructed attribute table
+
+
+ a Diffie-Hellman key exchange engine.
+
+ note: This uses MTI/A0 key agreement in order to make the key agreement
+ secure against passive attacks. If you're doing Diffie-Hellman and both
+ parties have long term public keys you should look at using this. For
+ further information have a look at RFC 2631.
+
+ It's possible to extend this to more than two parties as well, for the moment
+ that is left as an exercise for the reader.
+
+
+ calculate our initial message.
+
+
+ given a message from a given party and the corresponding public key
+ calculate the next message in the agreement sequence. In this case
+ this will represent the shared secret.
+
+
+ a Diffie-Hellman key agreement class.
+
+ note: This is only the basic algorithm, it doesn't take advantage of
+ long term public keys if they are available. See the DHAgreement class
+ for a "better" implementation.
+
+
+ The basic interface that basic Diffie-Hellman implementations
+ conforms to.
+
+
+ initialise the agreement engine.
+
+
+ given a public key from a given party calculate the next
+ message in the agreement sequence.
+
+
+ given a short term public key from a given party calculate the next
+ message in the agreement sequence.
+
+
+ P1363 7.2.1 ECSVDP-DH
+
+ ECSVDP-DH is Elliptic Curve Secret Value Derivation Primitive,
+ Diffie-Hellman version. It is based on the work of [DH76], [Mil86],
+ and [Kob87]. This primitive derives a shared secret value from one
+ party's private key and another party's public key, where both have
+ the same set of EC domain parameters. If two parties correctly
+ execute this primitive, they will produce the same output. This
+ primitive can be invoked by a scheme to derive a shared secret key;
+ specifically, it may be used with the schemes ECKAS-DH1 and
+ DL/ECKAS-DH2. It assumes that the input keys are valid (see also
+ Section 7.2.2).
+
+
+ P1363 7.2.2 ECSVDP-DHC
+
+ ECSVDP-DHC is Elliptic Curve Secret Value Derivation Primitive,
+ Diffie-Hellman version with cofactor multiplication. It is based on
+ the work of [DH76], [Mil86], [Kob87], [LMQ98] and [Kal98a]. This
+ primitive derives a shared secret value from one party's private key
+ and another party's public key, where both have the same set of EC
+ domain parameters. If two parties correctly execute this primitive,
+ they will produce the same output. This primitive can be invoked by a
+ scheme to derive a shared secret key; specifically, it may be used
+ with the schemes ECKAS-DH1 and DL/ECKAS-DH2. It does not assume the
+ validity of the input public key (see also Section 7.2.1).
+
+ Note: As stated P1363 compatibility mode with ECDH can be preset, and
+ in this case the implementation doesn't have a ECDH compatibility mode
+ (if you want that just use ECDHBasicAgreement and note they both implement
+ BasicAgreement!).
+
+
+ Parameters for key/byte stream derivation classes
+
+
+ RFC 2631 Diffie-hellman KEK derivation function.
+
+
+ base interface for general purpose byte derivation functions.
+
+
+ return the message digest used as the basis for the function
+
+
+ X9.63 based key derivation function for ECDH CMS.
+
+
+ Implements the client side SRP-6a protocol. Note that this class is stateful, and therefore NOT threadsafe.
+ This implementation of SRP is based on the optimized message sequence put forth by Thomas Wu in the paper
+ "SRP-6: Improvements and Refinements to the Secure Remote Password Protocol, 2002"
+
+
+ Initialises the client to begin new authentication attempt
+ @param N The safe prime associated with the client's verifier
+ @param g The group parameter associated with the client's verifier
+ @param digest The digest algorithm associated with the client's verifier
+ @param random For key generation
+
+
+ Generates client's credentials given the client's salt, identity and password
+ @param salt The salt used in the client's verifier.
+ @param identity The user's identity (eg. username)
+ @param password The user's password
+ @return Client's public value to send to server
+
+
+ Generates client's verification message given the server's credentials
+ @param serverB The server's credentials
+ @return Client's verification message for the server
+ @throws CryptoException If server's credentials are invalid
+
+
+ Implements the server side SRP-6a protocol. Note that this class is stateful, and therefore NOT threadsafe.
+ This implementation of SRP is based on the optimized message sequence put forth by Thomas Wu in the paper
+ "SRP-6: Improvements and Refinements to the Secure Remote Password Protocol, 2002"
+
+
+ Initialises the server to accept a new client authentication attempt
+ @param N The safe prime associated with the client's verifier
+ @param g The group parameter associated with the client's verifier
+ @param v The client's verifier
+ @param digest The digest algorithm associated with the client's verifier
+ @param random For key generation
+
+
+ Generates the server's credentials that are to be sent to the client.
+ @return The server's public value to the client
+
+
+ Processes the client's credentials. If valid the shared secret is generated and returned.
+ @param clientA The client's credentials
+ @return A shared secret BigInteger
+ @throws CryptoException If client's credentials are invalid
+
+
+ Generates new SRP verifier for user
+
+
+ Initialises generator to create new verifiers
+ @param N The safe prime to use (see DHParametersGenerator)
+ @param g The group parameter to use (see DHParametersGenerator)
+ @param digest The digest to use. The same digest type will need to be used later for the actual authentication
+ attempt. Also note that the final session key size is dependent on the chosen digest.
+
+
+ Creates a new SRP verifier
+ @param salt The salt to use, generally should be large and random
+ @param identity The user's identifying information (eg. username)
+ @param password The user's password
+ @return A new verifier for use in future SRP authentication
+
+
+ a holding class for public/private parameter pairs.
+
+
+ basic constructor.
+
+ @param publicParam a public key parameters object.
+ @param privateParam the corresponding private key parameters.
+
+
+ return the public key parameters.
+
+ @return the public key parameters.
+
+
+ return the private key parameters.
+
+ @return the private key parameters.
+
+
+ The AEAD block ciphers already handle buffering internally, so this class
+ just takes care of implementing IBufferedCipher methods.
+
+
+ Block cipher engines are expected to conform to this interface.
+
+
+ Initialise the cipher.
+ If true the cipher is initialised for encryption,
+ if false for decryption.
+ The key and other data required by the cipher.
+
+
+
+ Reset the cipher. After resetting the cipher is in the same state
+ as it was after the last init (if there was one).
+
+
+
+ The name of the algorithm this cipher implements.
+
+
+ initialise the cipher.
+
+ @param forEncryption if true the cipher is initialised for
+ encryption, if false for decryption.
+ @param param the key and other data required by the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ return the blocksize for the underlying cipher.
+
+ @return the blocksize for the underlying cipher.
+
+
+ return the size of the output buffer required for an update
+ an input of len bytes.
+
+ @param len the length of the input.
+ @return the space required to accommodate a call to update
+ with len bytes of input.
+
+
+ return the size of the output buffer required for an update plus a
+ doFinal with an input of len bytes.
+
+ @param len the length of the input.
+ @return the space required to accommodate a call to update and doFinal
+ with len bytes of input.
+
+
+ process a single byte, producing an output block if neccessary.
+
+ @param in the input byte.
+ @param out the space for any output that might be produced.
+ @param outOff the offset from which the output will be copied.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there isn't enough space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+
+
+ process an array of bytes, producing output if necessary.
+
+ @param in the input byte array.
+ @param inOff the offset at which the input data starts.
+ @param len the number of bytes to be copied out of the input array.
+ @param out the space for any output that might be produced.
+ @param outOff the offset from which the output will be copied.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there isn't enough space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+
+
+ Process the last block in the buffer.
+
+ @param out the array the block currently being held is copied into.
+ @param outOff the offset at which the copying starts.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there is insufficient space in out for
+ the output, or the input is not block size aligned and should be.
+ @exception InvalidOperationException if the underlying cipher is not
+ initialised.
+ @exception InvalidCipherTextException if padding is expected and not found.
+ @exception DataLengthException if the input is not block size
+ aligned.
+
+
+ Reset the buffer and cipher. After resetting the object is in the same
+ state as it was after the last init (if there was one).
+
+
+ a buffer wrapper for an asymmetric block cipher, allowing input
+ to be accumulated in a piecemeal fashion until final processing.
+
+
+ base constructor.
+
+ @param cipher the cipher this buffering object wraps.
+
+
+ return the amount of data sitting in the buffer.
+
+ @return the amount of data sitting in the buffer.
+
+
+ initialise the buffer and the underlying cipher.
+
+ @param forEncryption if true the cipher is initialised for
+ encryption, if false for decryption.
+ @param param the key and other data required by the cipher.
+
+
+ process the contents of the buffer using the underlying
+ cipher.
+
+ @return the result of the encryption/decryption process on the
+ buffer.
+ @exception InvalidCipherTextException if we are given a garbage block.
+
+
+ Reset the buffer
+
+
+ A wrapper class that allows block ciphers to be used to process data in
+ a piecemeal fashion. The BufferedBlockCipher outputs a block only when the
+ buffer is full and more data is being added, or on a doFinal.
+
+ Note: in the case where the underlying cipher is either a CFB cipher or an
+ OFB one the last block may not be a multiple of the block size.
+
+
+
+ constructor for subclasses
+
+
+ Create a buffered block cipher without padding.
+
+ @param cipher the underlying block cipher this buffering object wraps.
+ false otherwise.
+
+
+ initialise the cipher.
+
+ @param forEncryption if true the cipher is initialised for
+ encryption, if false for decryption.
+ @param param the key and other data required by the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ return the blocksize for the underlying cipher.
+
+ @return the blocksize for the underlying cipher.
+
+
+ return the size of the output buffer required for an update
+ an input of len bytes.
+
+ @param len the length of the input.
+ @return the space required to accommodate a call to update
+ with len bytes of input.
+
+
+ return the size of the output buffer required for an update plus a
+ doFinal with an input of len bytes.
+
+ @param len the length of the input.
+ @return the space required to accommodate a call to update and doFinal
+ with len bytes of input.
+
+
+ process a single byte, producing an output block if neccessary.
+
+ @param in the input byte.
+ @param out the space for any output that might be produced.
+ @param outOff the offset from which the output will be copied.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there isn't enough space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+
+
+ process an array of bytes, producing output if necessary.
+
+ @param in the input byte array.
+ @param inOff the offset at which the input data starts.
+ @param len the number of bytes to be copied out of the input array.
+ @param out the space for any output that might be produced.
+ @param outOff the offset from which the output will be copied.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there isn't enough space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+
+
+ Process the last block in the buffer.
+
+ @param out the array the block currently being held is copied into.
+ @param outOff the offset at which the copying starts.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there is insufficient space in out for
+ the output, or the input is not block size aligned and should be.
+ @exception InvalidOperationException if the underlying cipher is not
+ initialised.
+ @exception InvalidCipherTextException if padding is expected and not found.
+ @exception DataLengthException if the input is not block size
+ aligned.
+
+
+ Reset the buffer and cipher. After resetting the object is in the same
+ state as it was after the last init (if there was one).
+
+
+ The base class for symmetric, or secret, cipher key generators.
+
+
+ initialise the key generator.
+
+ @param param the parameters to be used for key generation
+
+
+ Generate a secret key.
+
+ @return a byte array containing the key value.
+
+
+ this exception is thrown if a buffer that is meant to have output
+ copied into it turns out to be too short, or if we've been given
+ insufficient input. In general this exception will Get thrown rather
+ than an ArrayOutOfBounds exception.
+
+
+ base constructor.
+
+
+ create a DataLengthException with the given message.
+
+ @param message the message to be carried with the exception.
+
+
+ base implementation of MD4 family style digest as outlined in
+ "Handbook of Applied Cryptography", pages 344 - 347.
+
+
+ interface that a message digest conforms to.
+
+
+ return the size, in bytes, of the digest produced by this message digest.
+
+ @return the size, in bytes, of the digest produced by this message digest.
+
+
+ return the size, in bytes, of the internal buffer used by this digest.
+
+ @return the size, in bytes, of the internal buffer used by this digest.
+
+
+ update the message digest with a single byte.
+
+ @param inByte the input byte to be entered.
+
+
+ update the message digest with a block of bytes.
+
+ @param input the byte array containing the data.
+ @param inOff the offset into the byte array where the data starts.
+ @param len the length of the data.
+
+
+ Close the digest, producing the final digest value. The doFinal
+ call leaves the digest reset.
+
+ @param output the array the digest is to be copied into.
+ @param outOff the offset into the out array the digest is to start at.
+
+
+ reset the digest back to it's initial state.
+
+
+ return the algorithm name
+
+ @return the algorithm name
+
+
+ implementation of GOST R 34.11-94
+
+
+ Standard constructor
+
+
+ Constructor to allow use of a particular sbox with GOST28147
+ @see GOST28147Engine#getSBox(String)
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables to the IV values.
+
+
+ Base class for SHA-384 and SHA-512.
+
+
+ Constructor for variable length word
+
+
+ Copy constructor. We are using copy constructors in place
+ of the object.Clone() interface as this interface is not
+ supported by J2ME.
+
+
+ adjust the byte counts so that byteCount2 represents the
+ upper long (less 3 bits) word of the byte count.
+
+
+ implementation of MD2
+ as outlined in RFC1319 by B.Kaliski from RSA Laboratories April 1992
+
+
+ Close the digest, producing the final digest value. The doFinal
+ call leaves the digest reset.
+
+ @param out the array the digest is to be copied into.
+ @param outOff the offset into the out array the digest is to start at.
+
+
+ reset the digest back to it's initial state.
+
+
+ update the message digest with a single byte.
+
+ @param in the input byte to be entered.
+
+
+ update the message digest with a block of bytes.
+
+ @param in the byte array containing the data.
+ @param inOff the offset into the byte array where the data starts.
+ @param len the length of the data.
+
+
+ return the algorithm name
+
+ @return the algorithm name
+
+
+ implementation of MD4 as RFC 1320 by R. Rivest, MIT Laboratory for
+ Computer Science and RSA Data Security, Inc.
+
+ NOTE: This algorithm is only included for backwards compatibility
+ with legacy applications, it's not secure, don't use it for anything new!
+
+
+ Standard constructor
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables to the IV values.
+
+
+ implementation of MD5 as outlined in "Handbook of Applied Cryptography", pages 346 - 347.
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables to the IV values.
+
+
+ implementation of RipeMD128
+
+
+ Standard constructor
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables to the IV values.
+
+
+ implementation of RipeMD see,
+ http://www.esat.kuleuven.ac.be/~bosselae/ripemd160.html
+
+
+ Standard constructor
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables to the IV values.
+
+
+
+
Implementation of RipeMD256.
+
Note: this algorithm offers the same level of security as RipeMD128.
+
+
+
+ Standard constructor
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+
+ reset the chaining variables to the IV values.
+
+
+
+
Implementation of RipeMD 320.
+
Note: this algorithm offers the same level of security as RipeMD160.
+
+
+
+ Standard constructor
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+
+ reset the chaining variables to the IV values.
+
+
+ implementation of SHA-1 as outlined in "Handbook of Applied Cryptography", pages 346 - 349.
+
+ It is interesting to ponder why the, apart from the extra IV, the other difference here from MD5
+ is the "endienness" of the word processing!
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables
+
+
+ SHA-224 as described in RFC 3874
+
+
+
+ Standard constructor
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables
+
+
+ Draft FIPS 180-2 implementation of SHA-256. Note: As this is
+ based on a draft this implementation is subject to change.
+
+
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables
+
+
+ Draft FIPS 180-2 implementation of SHA-384. Note: As this is
+ based on a draft this implementation is subject to change.
+
+
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables
+
+
+ Draft FIPS 180-2 implementation of SHA-512. Note: As this is
+ based on a draft this implementation is subject to change.
+
+
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables
+
+
+ Wrapper class that reduces the output length of a particular digest to
+ only the first n bytes of the digest function.
+
+
+ Base constructor.
+
+ @param baseDigest underlying digest to use.
+ @param length length in bytes of the output of doFinal.
+ @exception ArgumentException if baseDigest is null, or length is greater than baseDigest.GetDigestSize().
+
+
+ implementation of Tiger based on:
+
+ http://www.cs.technion.ac.il/~biham/Reports/Tiger
+
+
+ Standard constructor
+
+
+ Copy constructor. This will copy the state of the provided
+ message digest.
+
+
+ reset the chaining variables
+
+
+ Implementation of WhirlpoolDigest, based on Java source published by Barreto
+ and Rijmen.
+
+
+
+ Copy constructor. This will copy the state of the provided message
+ digest.
+
+
+ Reset the chaining variables
+
+
+ ISO 9796-1 padding. Note in the light of recent results you should
+ only use this with RSA (rather than the "simpler" Rabin keys) and you
+ should never use it with anything other than a hash (ie. even if the
+ message is small don't sign the message, sign it's hash) or some "random"
+ value. See your favorite search engine for details.
+
+
+ Base interface for a public/private key block cipher.
+
+
+ Initialise the cipher.
+ Initialise for encryption if true, for decryption if false.
+ The key or other data required by the cipher.
+
+
+ The maximum size, in bytes, an input block may be.
+
+
+ The maximum size, in bytes, an output block will be.
+
+
+ Process a block.
+ The input buffer.
+ The offset into inBuf that the input block begins.
+ The length of the input block.
+ Input decrypts improperly.
+ Input is too large for the cipher.
+
+
+ The name of the algorithm this cipher implements.
+
+
+ return the input block size. The largest message we can process
+ is (key_size_in_bits + 3)/16, which in our world comes to
+ key_size_in_bytes / 2.
+
+
+ return the maximum possible size for the output.
+
+
+ set the number of bits in the next message to be treated as
+ pad bits.
+
+
+ retrieve the number of pad bits in the last decoded message.
+
+
+ @exception InvalidCipherTextException if the decrypted block is not a valid ISO 9796 bit string
+
+
+ Optimal Asymmetric Encryption Padding (OAEP) - see PKCS 1 V 2.
+
+
+ @exception InvalidCipherTextException if the decrypted block turns out to
+ be badly formatted.
+
+
+ int to octet string.
+
+
+ mask generator function, as described in PKCS1v2.
+
+
+ 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.
+
+
+ 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.BouncyCastle.Pkcs1.Strict to false.
+
+
+ Basic constructor.
+ @param cipher
+
+
+ @exception InvalidCipherTextException if the decrypted block is not in Pkcs1 format.
+
+
+ The same effect can be achieved by setting the static property directly
+
+ The static property is checked during construction of the encoding object, it is set to
+ true by default.
+
+
+
+ an implementation of the AES (Rijndael), from FIPS-197.
+
+ For further details see: http://csrc.nist.gov/encryption/aes/.
+
+ This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at
+ http://fp.gladman.plus.com/cryptography_technology/rijndael/
+
+ There are three levels of tradeoff of speed vs memory
+ Because java has no preprocessor, they are written as three separate classes from which to choose
+
+ The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption
+ and 4 for decryption.
+
+ The middle performance version uses only one 256 word table for each, for a total of 2Kbytes,
+ adding 12 rotate operations per round to compute the values contained in the other tables from
+ the contents of the first.
+
+ The slowest version uses no static tables at all and computes the values in each round.
+
+
+ This file contains the middle performance version with 2Kbytes of static tables for round precomputation.
+
+
+
+ Base interface for a symmetric key block cipher.
+
+
+ Initialise the cipher.
+ Initialise for encryption if true, for decryption if false.
+ The key or other data required by the cipher.
+
+
+ The block size for this cipher, in bytes.
+
+
+ Process a block.
+ The input buffer.
+ The offset into inBuf that the input block begins.
+ The output buffer.
+ The offset into outBuf to write the output block.
+ If input block is wrong size, or outBuf too small.
+ The number of bytes processed and produced.
+
+
+
+ Reset the cipher to the same state as it was after the last init (if there was one).
+
+
+
+ The name of the algorithm this cipher implements.
+
+
+ Indicates whether this cipher can handle partial blocks.
+
+
+ Calculate the necessary round keys
+ The number of calculations depends on key size and block size
+ AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits
+ This code is written assuming those are the only possible values
+
+
+ default constructor - 128 bit block size.
+
+
+ initialise an AES cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ an implementation of the AES (Rijndael)), from FIPS-197.
+
+ For further details see: http://csrc.nist.gov/encryption/aes/.
+
+ This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at
+ http://fp.gladman.plus.com/cryptography_technology/rijndael/
+
+ There are three levels of tradeoff of speed vs memory
+ Because java has no preprocessor), they are written as three separate classes from which to choose
+
+ The fastest uses 8Kbytes of static tables to precompute round calculations), 4 256 word tables for encryption
+ and 4 for decryption.
+
+ The middle performance version uses only one 256 word table for each), for a total of 2Kbytes),
+ adding 12 rotate operations per round to compute the values contained in the other tables from
+ the contents of the first
+
+ The slowest version uses no static tables at all and computes the values in each round
+
+
+ This file contains the fast version with 8Kbytes of static tables for round precomputation
+
+
+
+ Calculate the necessary round keys
+ The number of calculations depends on key size and block size
+ AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits
+ This code is written assuming those are the only possible values
+
+
+ default constructor - 128 bit block size.
+
+
+ initialise an AES cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ an implementation of the AES (Rijndael), from FIPS-197.
+
+ For further details see: http://csrc.nist.gov/encryption/aes/.
+
+ This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at
+ http://fp.gladman.plus.com/cryptography_technology/rijndael/
+
+ There are three levels of tradeoff of speed vs memory
+ Because java has no preprocessor, they are written as three separate classes from which to choose
+
+ The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption
+ and 4 for decryption.
+
+ The middle performance version uses only one 256 word table for each, for a total of 2Kbytes,
+ adding 12 rotate operations per round to compute the values contained in the other tables from
+ the contents of the first
+
+ The slowest version uses no static tables at all and computes the values
+ in each round.
+
+
+ This file contains the slowest performance version with no static tables
+ for round precomputation, but it has the smallest foot print.
+
+
+
+ Calculate the necessary round keys
+ The number of calculations depends on key size and block size
+ AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits
+ This code is written assuming those are the only possible values
+
+
+ default constructor - 128 bit block size.
+
+
+ initialise an AES cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+
+ An implementation of the AES Key Wrapper from the NIST Key Wrap Specification.
+
+ For further details see: http://csrc.nist.gov/encryption/kms/key-wrap.pdf.
+
+
+
+
+ An implementation of the AES Key Wrapper from the NIST Key Wrap
+ Specification as described in RFC 3394.
+
+ For further details see: http://www.ietf.org/rfc/rfc3394.txt
+ and http://csrc.nist.gov/encryption/kms/key-wrap.pdf.
+
+
+
+ The name of the algorithm this cipher implements.
+
+
+ A class that provides Blowfish key encryption operations,
+ such as encoding data and generating keys.
+ All the algorithms herein are from Applied Cryptography
+ and implement a simplified cryptography interface.
+
+
+ initialise a Blowfish cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ apply the encryption cycle to each value pair in the table.
+
+
+ Encrypt the given input starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+ The input will be an exact multiple of our blocksize.
+
+
+ Decrypt the given input starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+ The input will be an exact multiple of our blocksize.
+
+
+ Camellia - based on RFC 3713.
+
+
+ Camellia - based on RFC 3713, smaller implementation, about half the size of CamelliaEngine.
+
+
+
+ An implementation of the Camellia key wrapper based on RFC 3657/RFC 3394.
+
+ For further details see: http://www.ietf.org/rfc/rfc3657.txt.
+
+
+
+ A class that provides CAST key encryption operations,
+ such as encoding data and generating keys.
+
+ All the algorithms herein are from the Internet RFC's
+
+ RFC2144 - Cast5 (64bit block, 40-128bit key)
+ RFC2612 - CAST6 (128bit block, 128-256bit key)
+
+ and implement a simplified cryptography interface.
+
+
+ initialise a CAST cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ Encrypt the given input starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+
+ @param src The plaintext buffer
+ @param srcIndex An offset into src
+ @param dst The ciphertext buffer
+ @param dstIndex An offset into dst
+
+
+ Decrypt the given input starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+
+ @param src The plaintext buffer
+ @param srcIndex An offset into src
+ @param dst The ciphertext buffer
+ @param dstIndex An offset into dst
+
+
+ The first of the three processing functions for the
+ encryption and decryption.
+
+ @param D the input to be processed
+ @param Kmi the mask to be used from Km[n]
+ @param Kri the rotation value to be used
+
+
+
+ The second of the three processing functions for the
+ encryption and decryption.
+
+ @param D the input to be processed
+ @param Kmi the mask to be used from Km[n]
+ @param Kri the rotation value to be used
+
+
+
+ The third of the three processing functions for the
+ encryption and decryption.
+
+ @param D the input to be processed
+ @param Kmi the mask to be used from Km[n]
+ @param Kri the rotation value to be used
+
+
+
+ Does the 16 rounds to encrypt the block.
+
+ @param L0 the LH-32bits of the plaintext block
+ @param R0 the RH-32bits of the plaintext block
+
+
+ A class that provides CAST6 key encryption operations,
+ such as encoding data and generating keys.
+
+ All the algorithms herein are from the Internet RFC
+
+ RFC2612 - CAST6 (128bit block, 128-256bit key)
+
+ and implement a simplified cryptography interface.
+
+
+ Encrypt the given input starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+
+ @param src The plaintext buffer
+ @param srcIndex An offset into src
+ @param dst The ciphertext buffer
+ @param dstIndex An offset into dst
+
+
+ Decrypt the given input starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+
+ @param src The plaintext buffer
+ @param srcIndex An offset into src
+ @param dst The ciphertext buffer
+ @param dstIndex An offset into dst
+
+
+ Does the 12 quad rounds rounds to encrypt the block.
+
+ @param A the 00-31 bits of the plaintext block
+ @param B the 32-63 bits of the plaintext block
+ @param C the 64-95 bits of the plaintext block
+ @param D the 96-127 bits of the plaintext block
+ @param result the resulting ciphertext
+
+
+ Does the 12 quad rounds rounds to decrypt the block.
+
+ @param A the 00-31 bits of the ciphertext block
+ @param B the 32-63 bits of the ciphertext block
+ @param C the 64-95 bits of the ciphertext block
+ @param D the 96-127 bits of the ciphertext block
+ @param result the resulting plaintext
+
+
+ A class that provides a basic DESede (or Triple DES) engine.
+
+
+ A class that provides a basic DES engine.
+
+
+ initialise a DES cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ what follows is mainly taken from "Applied Cryptography", by
+ Bruce Schneier, however it also bears great resemblance to Richard
+ Outerbridge's D3DES...
+
+
+ Generate an integer based working key based on our secret key
+ and what we processing we are planning to do.
+
+ Acknowledgements for this routine go to James Gillogly and Phil Karn.
+ (whoever, and wherever they are!).
+
+
+ the DES engine.
+
+
+ initialise a DESede cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ * Wrap keys according to
+ *
+ * draft-ietf-smime-key-wrap-01.txt.
+ *
+ * Note:
+ *
+ *
this is based on a draft, and as such is subject to change - don't use this class for anything requiring long term storage.
+ *
if you are using this to wrap triple-des keys you need to set the
+ * parity bits on the key and, if it's a two-key triple-des key, pad it
+ * yourself.
+ *
+ *
+
+
+ Field engine
+
+
+ Field param
+
+
+ Field paramPlusIV
+
+
+ Field iv
+
+
+ Field forWrapping
+
+
+ Field IV2
+
+
+ Method init
+
+ @param forWrapping
+ @param param
+
+
+ Method wrap
+
+ @param in
+ @param inOff
+ @param inLen
+ @return
+
+
+ Method unwrap
+
+ @param in
+ @param inOff
+ @param inLen
+ @return
+ @throws InvalidCipherTextException
+
+
+ Some key wrap algorithms make use of the Key Checksum defined
+ in CMS [CMS-Algorithms]. This is used to provide an integrity
+ check value for the key being wrapped. The algorithm is
+
+ - Compute the 20 octet SHA-1 hash on the key being wrapped.
+ - Use the first 8 octets of this hash as the checksum value.
+
+ @param key
+ @return
+ @throws Exception
+ @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
+
+
+ @param key
+ @param checksum
+ @return
+ @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
+
+
+ Method GetAlgorithmName
+
+ @return
+
+
+ this does your basic ElGamal algorithm.
+
+
+ initialise the ElGamal engine.
+
+ @param forEncryption true if we are encrypting, false otherwise.
+ @param param the necessary ElGamal key parameters.
+
+
+ Return the maximum size for an input block to this engine.
+ For ElGamal this is always one byte less than the size of P on
+ encryption, and twice the length as the size of P on decryption.
+
+ @return maximum size for an input block.
+
+
+ Return the maximum size for an output block to this engine.
+ For ElGamal this is always one byte less than the size of P on
+ decryption, and twice the length as the size of P on encryption.
+
+ @return maximum size for an output block.
+
+
+ Process a single block using the basic ElGamal algorithm.
+
+ @param in the input array.
+ @param inOff the offset into the input buffer where the data starts.
+ @param length the length of the data to be processed.
+ @return the result of the ElGamal process.
+ @exception DataLengthException the input block is too large.
+
+
+ implementation of GOST 28147-89
+
+
+ standard constructor.
+
+
+ initialise an Gost28147 cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is inappropriate.
+
+
+ Return the S-Box associated with SBoxName
+ @param sBoxName name of the S-Box
+ @return byte array representing the S-Box
+
+
+ HC-128 is a software-efficient stream cipher created by Hongjun Wu. It
+ generates keystream from a 128-bit secret key and a 128-bit initialization
+ vector.
+
+ It is a third phase candidate in the eStream contest, and is patent-free.
+ No attacks are known as of today (April 2007). See
+
+ http://www.ecrypt.eu.org/stream/hcp3.html
+
+
+
+ The interface stream ciphers conform to.
+
+
+ Initialise the cipher.
+ If true the cipher is initialised for encryption,
+ if false for decryption.
+ The key and other data required by the cipher.
+
+ If the parameters argument is inappropriate.
+
+
+
+ encrypt/decrypt a single byte returning the result.
+ the byte to be processed.
+ the result of processing the input byte.
+
+
+
+ Process a block of bytes from input putting the result into output.
+
+ The input byte array.
+
+ The offset into input where the data to be processed starts.
+
+ The number of bytes to be processed.
+ The output buffer the processed bytes go into.
+
+ The offset into output the processed data starts at.
+
+ If the output buffer is too small.
+
+
+
+ Reset the cipher to the same state as it was after the last init (if there was one).
+
+
+
+ The name of the algorithm this cipher implements.
+
+
+ Initialise a HC-128 cipher.
+
+ @param forEncryption whether or not we are for encryption. Irrelevant, as
+ encryption and decryption are the same.
+ @param params the parameters required to set up the cipher.
+ @throws ArgumentException if the params argument is
+ inappropriate (ie. the key is not 128 bit long).
+
+
+ HC-256 is a software-efficient stream cipher created by Hongjun Wu. It
+ generates keystream from a 256-bit secret key and a 256-bit initialization
+ vector.
+
+ Its brother, HC-128, is a third phase candidate in the eStream contest.
+ The algorithm is patent-free. No attacks are known as of today (April 2007).
+ See
+
+ http://www.ecrypt.eu.org/stream/hcp3.html
+
+
+
+ Initialise a HC-256 cipher.
+
+ @param forEncryption whether or not we are for encryption. Irrelevant, as
+ encryption and decryption are the same.
+ @param params the parameters required to set up the cipher.
+ @throws ArgumentException if the params argument is
+ inappropriate (ie. the key is not 256 bit long).
+
+
+ support class for constructing intergrated encryption ciphers
+ for doing basic message exchanges on top of key agreement ciphers
+
+
+ set up for use with stream mode, where the key derivation function
+ is used to provide a stream of bytes to xor with the message.
+
+ @param agree the key agreement used as the basis for the encryption
+ @param kdf the key derivation function used for byte generation
+ @param mac the message authentication code generator for the message
+
+
+ set up for use in conjunction with a block cipher to handle the
+ message.
+
+ @param agree the key agreement used as the basis for the encryption
+ @param kdf the key derivation function used for byte generation
+ @param mac the message authentication code generator for the message
+ @param cipher the cipher to used for encrypting the message
+
+
+ Initialise the encryptor.
+
+ @param forEncryption whether or not this is encryption/decryption.
+ @param privParam our private key parameters
+ @param pubParam the recipient's/sender's public key parameters
+ @param param encoding and derivation parameters.
+
+
+ Implementation of Bob Jenkin's ISAAC (Indirection Shift Accumulate Add and Count).
+ see: http://www.burtleburtle.net/bob/rand/isaacafa.html
+
+
+ initialise an ISAAC cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param params the parameters required to set up the cipher.
+ @exception ArgumentException if the params argument is
+ inappropriate.
+
+
+ NaccacheStern Engine. For details on this cipher, please see
+ http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
+
+
+ Initializes this algorithm. Must be called before all other Functions.
+
+ @see org.bouncycastle.crypto.AsymmetricBlockCipher#init(bool,
+ org.bouncycastle.crypto.CipherParameters)
+
+
+ Returns the input block size of this algorithm.
+
+ @see org.bouncycastle.crypto.AsymmetricBlockCipher#GetInputBlockSize()
+
+
+ Returns the output block size of this algorithm.
+
+ @see org.bouncycastle.crypto.AsymmetricBlockCipher#GetOutputBlockSize()
+
+
+ Process a single Block using the Naccache-Stern algorithm.
+
+ @see org.bouncycastle.crypto.AsymmetricBlockCipher#ProcessBlock(byte[],
+ int, int)
+
+
+ Encrypts a BigInteger aka Plaintext with the public key.
+
+ @param plain
+ The BigInteger to encrypt
+ @return The byte[] representation of the encrypted BigInteger (i.e.
+ crypted.toByteArray())
+
+
+ Adds the contents of two encrypted blocks mod sigma
+
+ @param block1
+ the first encrypted block
+ @param block2
+ the second encrypted block
+ @return encrypt((block1 + block2) mod sigma)
+ @throws InvalidCipherTextException
+
+
+ Convenience Method for data exchange with the cipher.
+
+ Determines blocksize and splits data to blocksize.
+
+ @param data the data to be processed
+ @return the data after it went through the NaccacheSternEngine.
+ @throws InvalidCipherTextException
+
+
+ Computes the integer x that is expressed through the given primes and the
+ congruences with the chinese remainder theorem (CRT).
+
+ @param congruences
+ the congruences c_i
+ @param primes
+ the primes p_i
+ @return an integer x for that x % p_i == c_i
+
+
+ A Noekeon engine, using direct-key mode.
+
+
+ Create an instance of the Noekeon encryption algorithm
+ and set some defaults
+
+
+ initialise
+
+ @param forEncryption whether or not we are for encryption.
+ @param params the parameters required to set up the cipher.
+ @exception ArgumentException if the params argument is
+ inappropriate.
+
+
+ Re-key the cipher.
+
+ @param key the key to be used
+
+
+ The no-op engine that just copies bytes through, irrespective of whether encrypting and decrypting.
+ Provided for the sake of completeness.
+
+
+ an implementation of RC2 as described in RFC 2268
+ "A Description of the RC2(r) Encryption Algorithm" R. Rivest.
+
+
+ initialise a RC2 cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ return the result rotating the 16 bit number in x left by y
+
+
+ Wrap keys according to RFC 3217 - RC2 mechanism
+
+
+ Field engine
+
+
+ Field param
+
+
+ Field paramPlusIV
+
+
+ Field iv
+
+
+ Field forWrapping
+
+
+ Field IV2
+
+
+ Method init
+
+ @param forWrapping
+ @param param
+
+
+ Method wrap
+
+ @param in
+ @param inOff
+ @param inLen
+ @return
+
+
+ Method unwrap
+
+ @param in
+ @param inOff
+ @param inLen
+ @return
+ @throws InvalidCipherTextException
+
+
+ Some key wrap algorithms make use of the Key Checksum defined
+ in CMS [CMS-Algorithms]. This is used to provide an integrity
+ check value for the key being wrapped. The algorithm is
+
+ - Compute the 20 octet SHA-1 hash on the key being wrapped.
+ - Use the first 8 octets of this hash as the checksum value.
+
+ @param key
+ @return
+ @throws Exception
+ @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
+
+
+ @param key
+ @param checksum
+ @return
+ @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
+
+
+ Method GetAlgorithmName
+
+ @return
+
+
+ initialise a RC4 cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ The specification for RC5 came from the RC5 Encryption Algorithm
+ publication in RSA CryptoBytes, Spring of 1995.
+ http://www.rsasecurity.com/rsalabs/cryptobytes.
+
+ This implementation has a word size of 32 bits.
+
+
+ Create an instance of the RC5 encryption algorithm
+ and set some defaults
+
+
+ initialise a RC5-32 cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ Re-key the cipher.
+
+ @param key the key to be used
+
+
+ Encrypt the given block starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+
+ @param in in byte buffer containing data to encrypt
+ @param inOff offset into src buffer
+ @param out out buffer where encrypted data is written
+ @param outOff offset into out buffer
+
+
+ Perform a left "spin" of the word. The rotation of the given
+ word x is rotated left by y bits.
+ Only the lg(32) low-order bits of y
+ are used to determine the rotation amount. Here it is
+ assumed that the wordsize used is a power of 2.
+
+ @param x word to rotate
+ @param y number of bits to rotate % 32
+
+
+ Perform a right "spin" of the word. The rotation of the given
+ word x is rotated left by y bits.
+ Only the lg(32) low-order bits of y
+ are used to determine the rotation amount. Here it is
+ assumed that the wordsize used is a power of 2.
+
+ @param x word to rotate
+ @param y number of bits to rotate % 32
+
+
+ The specification for RC5 came from the RC5 Encryption Algorithm
+ publication in RSA CryptoBytes, Spring of 1995.
+ http://www.rsasecurity.com/rsalabs/cryptobytes.
+
+ This implementation is set to work with a 64 bit word size.
+
+
+ Create an instance of the RC5 encryption algorithm
+ and set some defaults
+
+
+ initialise a RC5-64 cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ Re-key the cipher.
+
+ @param key the key to be used
+
+
+ Encrypt the given block starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+
+ @param in in byte buffer containing data to encrypt
+ @param inOff offset into src buffer
+ @param out out buffer where encrypted data is written
+ @param outOff offset into out buffer
+
+
+ Perform a left "spin" of the word. The rotation of the given
+ word x is rotated left by y bits.
+ Only the lg(wordSize) low-order bits of y
+ are used to determine the rotation amount. Here it is
+ assumed that the wordsize used is a power of 2.
+
+ @param x word to rotate
+ @param y number of bits to rotate % wordSize
+
+
+ Perform a right "spin" of the word. The rotation of the given
+ word x is rotated left by y bits.
+ Only the lg(wordSize) low-order bits of y
+ are used to determine the rotation amount. Here it is
+ assumed that the wordsize used is a power of 2.
+
+ @param x word to rotate
+ @param y number of bits to rotate % wordSize
+
+
+ An RC6 engine.
+
+
+ Create an instance of the RC6 encryption algorithm
+ and set some defaults
+
+
+ initialise a RC5-32 cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ Re-key the cipher.
+
+ @param inKey the key to be used
+
+
+ Perform a left "spin" of the word. The rotation of the given
+ word x is rotated left by y bits.
+ Only the lg(wordSize) low-order bits of y
+ are used to determine the rotation amount. Here it is
+ assumed that the wordsize used is a power of 2.
+
+ @param x word to rotate
+ @param y number of bits to rotate % wordSize
+
+
+ Perform a right "spin" of the word. The rotation of the given
+ word x is rotated left by y bits.
+ Only the lg(wordSize) low-order bits of y
+ are used to determine the rotation amount. Here it is
+ assumed that the wordsize used is a power of 2.
+
+ @param x word to rotate
+ @param y number of bits to rotate % wordSize
+
+
+ an implementation of the RFC 3211 Key Wrap
+ Specification.
+
+
+ an implementation of Rijndael, based on the documentation and reference implementation
+ by Paulo Barreto, Vincent Rijmen, for v2.0 August '99.
+
+ Note: this implementation is based on information prior to readonly NIST publication.
+
+
+
+ multiply two elements of GF(2^m)
+ needed for MixColumn and InvMixColumn
+
+
+ xor corresponding text input and round key input bytes
+
+
+ Row 0 remains unchanged
+ The other three rows are shifted a variable amount
+
+
+ Replace every byte of the input by the byte at that place
+ in the nonlinear S-box
+
+
+ Mix the bytes of every column in a linear way
+
+
+ Mix the bytes of every column in a linear way
+ This is the opposite operation of Mixcolumn
+
+
+ Calculate the necessary round keys
+ The number of calculations depends on keyBits and blockBits
+
+
+ default constructor - 128 bit block size.
+
+
+ basic constructor - set the cipher up for a given blocksize
+
+ @param blocksize the blocksize in bits, must be 128, 192, or 256.
+
+
+ initialise a Rijndael cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ this does your basic RSA algorithm with blinding
+
+
+ initialise the RSA engine.
+
+ @param forEncryption true if we are encrypting, false otherwise.
+ @param param the necessary RSA key parameters.
+
+
+ Return the maximum size for an input block to this engine.
+ For RSA this is always one byte less than the key size on
+ encryption, and the same length as the key size on decryption.
+
+ @return maximum size for an input block.
+
+
+ Return the maximum size for an output block to this engine.
+ For RSA this is always one byte less than the key size on
+ decryption, and the same length as the key size on encryption.
+
+ @return maximum size for an output block.
+
+
+ Process a single block using the basic RSA algorithm.
+
+ @param inBuf the input array.
+ @param inOff the offset into the input buffer where the data starts.
+ @param inLen the length of the data to be processed.
+ @return the result of the RSA process.
+ @exception DataLengthException the input block is too large.
+
+
+ This does your basic RSA Chaum's blinding and unblinding as outlined in
+ "Handbook of Applied Cryptography", page 475. You need to use this if you are
+ trying to get another party to generate signatures without them being aware
+ of the message they are signing.
+
+
+ Initialise the blinding engine.
+
+ @param forEncryption true if we are encrypting (blinding), false otherwise.
+ @param param the necessary RSA key parameters.
+
+
+ Return the maximum size for an input block to this engine.
+ For RSA this is always one byte less than the key size on
+ encryption, and the same length as the key size on decryption.
+
+ @return maximum size for an input block.
+
+
+ Return the maximum size for an output block to this engine.
+ For RSA this is always one byte less than the key size on
+ decryption, and the same length as the key size on encryption.
+
+ @return maximum size for an output block.
+
+
+ Process a single block using the RSA blinding algorithm.
+
+ @param in the input array.
+ @param inOff the offset into the input buffer where the data starts.
+ @param inLen the length of the data to be processed.
+ @return the result of the RSA process.
+ @throws DataLengthException the input block is too large.
+
+
+ this does your basic RSA algorithm.
+
+
+ initialise the RSA engine.
+
+ @param forEncryption true if we are encrypting, false otherwise.
+ @param param the necessary RSA key parameters.
+
+
+ Return the maximum size for an input block to this engine.
+ For RSA this is always one byte less than the key size on
+ encryption, and the same length as the key size on decryption.
+
+ @return maximum size for an input block.
+
+
+ Return the maximum size for an output block to this engine.
+ For RSA this is always one byte less than the key size on
+ decryption, and the same length as the key size on encryption.
+
+ @return maximum size for an output block.
+
+
+ this does your basic RSA algorithm.
+
+
+ initialise the RSA engine.
+
+ @param forEncryption true if we are encrypting, false otherwise.
+ @param param the necessary RSA key parameters.
+
+
+ Return the maximum size for an input block to this engine.
+ For RSA this is always one byte less than the key size on
+ encryption, and the same length as the key size on decryption.
+
+ @return maximum size for an input block.
+
+
+ Return the maximum size for an output block to this engine.
+ For RSA this is always one byte less than the key size on
+ decryption, and the same length as the key size on encryption.
+
+ @return maximum size for an output block.
+
+
+ Process a single block using the basic RSA algorithm.
+
+ @param inBuf the input array.
+ @param inOff the offset into the input buffer where the data starts.
+ @param inLen the length of the data to be processed.
+ @return the result of the RSA process.
+ @exception DataLengthException the input block is too large.
+
+
+ Implementation of Daniel J. Bernstein's Salsa20 stream cipher, Snuffle 2005
+
+
+ Constants
+
+
+ initialise a Salsa20 cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param params the parameters required to set up the cipher.
+ @exception ArgumentException if the params argument is
+ inappropriate.
+
+
+ Implementation of the SEED algorithm as described in RFC 4009
+
+
+
+ An implementation of the SEED key wrapper based on RFC 4010/RFC 3394.
+
+ For further details see: http://www.ietf.org/rfc/rfc4010.txt.
+
+
+
+ * Serpent is a 128-bit 32-round block cipher with variable key lengths,
+ * including 128, 192 and 256 bit keys conjectured to be at least as
+ * secure as three-key triple-DES.
+ *
+ * Serpent was designed by Ross Anderson, Eli Biham and Lars Knudsen as a
+ * candidate algorithm for the NIST AES Quest.>
+ *
+
+
+ initialise a Serpent cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ Process one block of input from the array in and write it to
+ the out array.
+
+ @param in the array containing the input data.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the output data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ Expand a user-supplied key material into a session key.
+
+ @param key The user-key bytes (multiples of 4) to use.
+ @exception ArgumentException
+
+
+ Encrypt one block of plaintext.
+
+ @param in the array containing the input data.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the output data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+
+
+ Decrypt one block of ciphertext.
+
+ @param in the array containing the input data.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the output data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+
+
+ S0 - { 3, 8,15, 1,10, 6, 5,11,14,13, 4, 2, 7, 0, 9,12 } - 15 terms.
+
+
+ InvSO - {13, 3,11, 0,10, 6, 5,12, 1,14, 4, 7,15, 9, 8, 2 } - 15 terms.
+
+
+ S1 - {15,12, 2, 7, 9, 0, 5,10, 1,11,14, 8, 6,13, 3, 4 } - 14 terms.
+
+
+ InvS1 - { 5, 8, 2,14,15, 6,12, 3,11, 4, 7, 9, 1,13,10, 0 } - 14 steps.
+
+
+ S2 - { 8, 6, 7, 9, 3,12,10,15,13, 1,14, 4, 0,11, 5, 2 } - 16 terms.
+
+
+ InvS2 - {12, 9,15, 4,11,14, 1, 2, 0, 3, 6,13, 5, 8,10, 7 } - 16 steps.
+
+
+ S3 - { 0,15,11, 8,12, 9, 6, 3,13, 1, 2, 4,10, 7, 5,14 } - 16 terms.
+
+
+ InvS3 - { 0, 9,10, 7,11,14, 6,13, 3, 5,12, 2, 4, 8,15, 1 } - 15 terms
+
+
+ S4 - { 1,15, 8, 3,12, 0,11, 6, 2, 5, 4,10, 9,14, 7,13 } - 15 terms.
+
+
+ InvS4 - { 5, 0, 8, 3,10, 9, 7,14, 2,12,11, 6, 4,15,13, 1 } - 15 terms.
+
+
+ S5 - {15, 5, 2,11, 4,10, 9,12, 0, 3,14, 8,13, 6, 7, 1 } - 16 terms.
+
+
+ InvS5 - { 8,15, 2, 9, 4, 1,13,14,11, 6, 5, 3, 7,12,10, 0 } - 16 terms.
+
+
+ S6 - { 7, 2,12, 5, 8, 4, 6,11,14, 9, 1,15,13, 3,10, 0 } - 15 terms.
+
+
+ InvS6 - {15,10, 1,13, 5, 3, 6, 0, 4, 9,14, 7, 2,12, 8,11 } - 15 terms.
+
+
+ S7 - { 1,13,15, 0,14, 8, 2,11, 7, 4,12,10, 9, 3, 5, 6 } - 16 terms.
+
+
+ InvS7 - { 3, 0, 6,13, 9,14,15, 8, 5,12,11, 7,10, 1, 4, 2 } - 17 terms.
+
+
+ Apply the linear transformation to the register set.
+
+
+ Apply the inverse of the linear transformation to the register set.
+
+
+ a class that provides a basic SKIPJACK engine.
+
+
+ initialise a SKIPJACK cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ The G permutation
+
+
+ the inverse of the G permutation.
+
+
+ An TEA engine.
+
+
+ Create an instance of the TEA encryption algorithm
+ and set some defaults
+
+
+ initialise
+
+ @param forEncryption whether or not we are for encryption.
+ @param params the parameters required to set up the cipher.
+ @exception ArgumentException if the params argument is
+ inappropriate.
+
+
+ Re-key the cipher.
+
+ @param key the key to be used
+
+
+ A class that provides Twofish encryption operations.
+
+ This Java implementation is based on the Java reference
+ implementation provided by Bruce Schneier and developed
+ by Raif S. Naffah.
+
+
+ Define the fixed p0/p1 permutations used in keyed S-box lookup.
+ By changing the following constant definitions, the S-boxes will
+ automatically Get changed in the Twofish engine.
+
+
+ gSubKeys[] and gSBox[] are eventually used in the
+ encryption and decryption methods.
+
+
+ initialise a Twofish cipher.
+
+ @param forEncryption whether or not we are for encryption.
+ @param parameters the parameters required to set up the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ Encrypt the given input starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+ The input will be an exact multiple of our blocksize.
+
+ encryptBlock uses the pre-calculated gSBox[] and subKey[]
+ arrays.
+
+
+ Decrypt the given input starting at the given offset and place
+ the result in the provided buffer starting at the given offset.
+ The input will be an exact multiple of our blocksize.
+
+
+ Use (12, 8) Reed-Solomon code over GF(256) to produce
+ a key S-box 32-bit entity from 2 key material 32-bit
+ entities.
+
+ @param k0 first 32-bit entity
+ @param k1 second 32-bit entity
+ @return Remainder polynomial Generated using RS code
+
+
+ * Reed-Solomon code parameters: (12,8) reversible code:
+ *
+ * where a = primitive root of field generator 0x14D
+ *
+
+
+ initialise a VMPC cipher.
+
+ @param forEncryption
+ whether or not we are for encryption.
+ @param params
+ the parameters required to set up the cipher.
+ @exception ArgumentException
+ if the params argument is inappropriate.
+
+
+ An XTEA engine.
+
+
+ Create an instance of the TEA encryption algorithm
+ and set some defaults
+
+
+ initialise
+
+ @param forEncryption whether or not we are for encryption.
+ @param params the parameters required to set up the cipher.
+ @exception ArgumentException if the params argument is
+ inappropriate.
+
+
+ Re-key the cipher.
+
+ @param key the key to be used
+
+
+ Basic KDF generator for derived keys and ivs as defined by IEEE P1363a/ISO 18033
+
+ This implementation is based on ISO 18033/P1363a.
+
+
+ Construct a KDF Parameters generator.
+
+ @param counterStart value of counter.
+ @param digest the digest to be used as the source of derived keys.
+
+
+ fill len bytes of the output buffer with bytes generated from
+ the derivation function.
+
+ @throws ArgumentException if the size of the request will cause an overflow.
+ @throws DataLengthException if the out buffer is too small.
+
+
+ return the underlying digest.
+
+
+ initialise the key generator - if strength is set to zero
+ the key generated will be 64 bits in size, otherwise
+ strength can be 64 or 56 bits (if you don't count the parity bits).
+
+ @param param the parameters to be used for key generation
+
+
+ initialise the key generator - if strength is set to zero
+ the key Generated will be 192 bits in size, otherwise
+ strength can be 128 or 192 (or 112 or 168 if you don't count
+ parity bits), depending on whether you wish to do 2-key or 3-key
+ triple DES.
+
+ @param param the parameters to be used for key generation
+
+
+ a basic Diffie-Hellman key pair generator.
+
+ This generates keys consistent for use with the basic algorithm for
+ Diffie-Hellman.
+
+
+ interface that a public/private key pair generator should conform to.
+
+
+ intialise the key pair generator.
+
+ @param the parameters the key pair is to be initialised with.
+
+
+ return an AsymmetricCipherKeyPair containing the Generated keys.
+
+ @return an AsymmetricCipherKeyPair containing the Generated keys.
+
+
+ a Diffie-Hellman key pair generator.
+
+ This generates keys consistent for use in the MTI/A0 key agreement protocol
+ as described in "Handbook of Applied Cryptography", Pages 516-519.
+
+
+ which Generates the p and g values from the given parameters,
+ returning the DHParameters object.
+
+ Note: can take a while...
+
+
+ * a DSA key pair generator.
+ *
+ * This Generates DSA keys in line with the method described
+ * in FIPS 186-3 B.1 FFC Key Pair Generation.
+
+
+ Generate suitable parameters for DSA, in line with FIPS 186-2.
+
+
+ initialise the key generator.
+
+ @param size size of the key (range 2^512 -> 2^1024 - 64 bit increments)
+ @param certainty measure of robustness of prime (for FIPS 186-2 compliance this should be at least 80).
+ @param random random byte source.
+
+
+ which Generates the p and g values from the given parameters,
+ returning the DsaParameters object.
+
+ Note: can take a while...
+
+
+ generate suitable parameters for DSA, in line with
+ FIPS 186-3 A.1 Generation of the FFC Primes p and q.
+
+
+ Given the domain parameters this routine Generates an EC key
+ pair in accordance with X9.62 section 5.2.1 pages 26, 27.
+
+
+ a ElGamal key pair generator.
+
+ This Generates keys consistent for use with ElGamal as described in
+ page 164 of "Handbook of Applied Cryptography".
+
+
+ * which Generates the p and g values from the given parameters,
+ * returning the ElGamalParameters object.
+ *
+ * Note: can take a while...
+ *
+
+
+ a GOST3410 key pair generator.
+ This generates GOST3410 keys in line with the method described
+ in GOST R 34.10-94.
+
+
+ generate suitable parameters for GOST3410.
+
+
+ initialise the key generator.
+
+ @param size size of the key
+ @param typeProcedure type procedure A,B = 1; A',B' - else
+ @param random random byte source.
+
+
+ Procedure C
+ procedure generates the a value from the given p,q,
+ returning the a value.
+
+
+ which generates the p , q and a values from the given parameters,
+ returning the Gost3410Parameters object.
+
+
+ KFD2 generator for derived keys and ivs as defined by IEEE P1363a/ISO 18033
+
+ This implementation is based on IEEE P1363/ISO 18033.
+
+
+ Construct a KDF1 byte generator.
+
+ @param digest the digest to be used as the source of derived keys.
+
+
+ KDF2 generator for derived keys and ivs as defined by IEEE P1363a/ISO 18033
+
+ This implementation is based on IEEE P1363/ISO 18033.
+
+
+ Construct a KDF2 bytes generator. Generates key material
+ according to IEEE P1363 or ISO 18033 depending on the initialisation.
+
+ @param digest the digest to be used as the source of derived keys.
+
+
+ Generator for MGF1 as defined in Pkcs 1v2
+
+
+ @param digest the digest to be used as the source of Generated bytes
+
+
+ int to octet string.
+
+
+ fill len bytes of the output buffer with bytes Generated from
+ the derivation function.
+
+ @throws DataLengthException if the out buffer is too small.
+
+
+ return the underlying digest.
+
+
+ Key generation parameters for NaccacheStern cipher. For details on this cipher, please see
+
+ http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
+
+
+ Generates a permuted ArrayList from the original one. The original List
+ is not modified
+
+ @param arr
+ the ArrayList to be permuted
+ @param rand
+ the source of Randomness for permutation
+ @return a new ArrayList with the permuted elements.
+
+
+ Finds the first 'count' primes starting with 3
+
+ @param count
+ the number of primes to find
+ @return a vector containing the found primes as Integer
+
+
+ Generator for PBE derived keys and ivs as usd by OpenSSL.
+
+ The scheme is a simple extension of PKCS 5 V2.0 Scheme 1 using MD5 with an
+ iteration count of 1.
+
+
+
+ super class for all Password Based Encyrption (Pbe) parameter generator classes.
+
+
+ base constructor.
+
+
+ initialise the Pbe generator.
+
+ @param password the password converted into bytes (see below).
+ @param salt the salt to be mixed with the password.
+ @param iterationCount the number of iterations the "mixing" function
+ is to be applied for.
+
+
+ return the password byte array.
+
+ @return the password byte array.
+
+
+ return the salt byte array.
+
+ @return the salt byte array.
+
+
+ Generate derived parameters for a key of length keySize.
+
+ @param keySize the length, in bits, of the key required.
+ @return a parameters object representing a key.
+
+
+ Generate derived parameters for a key of length keySize, and
+ an initialisation vector (IV) of length ivSize.
+
+ @param keySize the length, in bits, of the key required.
+ @param ivSize the length, in bits, of the iv required.
+ @return a parameters object representing a key and an IV.
+
+
+ Generate derived parameters for a key of length keySize, specifically
+ for use with a MAC.
+
+ @param keySize the length, in bits, of the key required.
+ @return a parameters object representing a key.
+
+
+ converts a password to a byte array according to the scheme in
+ Pkcs5 (ascii, no padding)
+
+ @param password a character array representing the password.
+ @return a byte array representing the password.
+
+
+ converts a password to a byte array according to the scheme in
+ PKCS5 (UTF-8, no padding)
+
+ @param password a character array representing the password.
+ @return a byte array representing the password.
+
+
+ converts a password to a byte array according to the scheme in
+ Pkcs12 (unicode, big endian, 2 zero pad bytes at the end).
+
+ @param password a character array representing the password.
+ @return a byte array representing the password.
+
+
+ return the iteration count.
+
+ @return the iteration count.
+
+
+ Construct a OpenSSL Parameters generator.
+
+
+ Initialise - note the iteration count for this algorithm is fixed at 1.
+
+ @param password password to use.
+ @param salt salt to use.
+
+
+ the derived key function, the ith hash of the password and the salt.
+
+
+ Generate a key parameter derived from the password, salt, and iteration
+ count we are currently initialised with.
+
+ @param keySize the size of the key we want (in bits)
+ @return a KeyParameter object.
+ @exception ArgumentException if the key length larger than the base hash size.
+
+
+ Generate a key with initialisation vector parameter derived from
+ the password, salt, and iteration count we are currently initialised
+ with.
+
+ @param keySize the size of the key we want (in bits)
+ @param ivSize the size of the iv we want (in bits)
+ @return a ParametersWithIV object.
+ @exception ArgumentException if keySize + ivSize is larger than the base hash size.
+
+
+ Generate a key parameter for use with a MAC derived from the password,
+ salt, and iteration count we are currently initialised with.
+
+ @param keySize the size of the key we want (in bits)
+ @return a KeyParameter object.
+ @exception ArgumentException if the key length larger than the base hash size.
+
+
+ Generator for Pbe derived keys and ivs as defined by Pkcs 12 V1.0.
+
+ The document this implementation is based on can be found at
+
+ RSA's Pkcs12 Page
+
+
+
+ Construct a Pkcs 12 Parameters generator.
+
+ @param digest the digest to be used as the source of derived keys.
+ @exception ArgumentException if an unknown digest is passed in.
+
+
+ add a + b + 1, returning the result in a. The a value is treated
+ as a BigInteger of length (b.Length * 8) bits. The result is
+ modulo 2^b.Length in case of overflow.
+
+
+ generation of a derived key ala Pkcs12 V1.0.
+
+
+ Generate a key parameter derived from the password, salt, and iteration
+ count we are currently initialised with.
+
+ @param keySize the size of the key we want (in bits)
+ @return a KeyParameter object.
+
+
+ Generate a key with initialisation vector parameter derived from
+ the password, salt, and iteration count we are currently initialised
+ with.
+
+ @param keySize the size of the key we want (in bits)
+ @param ivSize the size of the iv we want (in bits)
+ @return a ParametersWithIV object.
+
+
+ Generate a key parameter for use with a MAC derived from the password,
+ salt, and iteration count we are currently initialised with.
+
+ @param keySize the size of the key we want (in bits)
+ @return a KeyParameter object.
+
+
+ Generator for Pbe derived keys and ivs as defined by Pkcs 5 V2.0 Scheme 1.
+ Note this generator is limited to the size of the hash produced by the
+ digest used to drive it.
+
+ The document this implementation is based on can be found at
+
+ RSA's Pkcs5 Page
+
+
+
+ Construct a Pkcs 5 Scheme 1 Parameters generator.
+
+ @param digest the digest to be used as the source of derived keys.
+
+
+ the derived key function, the ith hash of the mPassword and the mSalt.
+
+
+ Generate a key parameter derived from the mPassword, mSalt, and iteration
+ count we are currently initialised with.
+
+ @param keySize the size of the key we want (in bits)
+ @return a KeyParameter object.
+ @exception ArgumentException if the key length larger than the base hash size.
+
+
+ Generate a key with initialisation vector parameter derived from
+ the mPassword, mSalt, and iteration count we are currently initialised
+ with.
+
+ @param keySize the size of the key we want (in bits)
+ @param ivSize the size of the iv we want (in bits)
+ @return a ParametersWithIV object.
+ @exception ArgumentException if keySize + ivSize is larger than the base hash size.
+
+
+ Generate a key parameter for use with a MAC derived from the mPassword,
+ mSalt, and iteration count we are currently initialised with.
+
+ @param keySize the size of the key we want (in bits)
+ @return a KeyParameter object.
+ @exception ArgumentException if the key length larger than the base hash size.
+
+
+ Generator for Pbe derived keys and ivs as defined by Pkcs 5 V2.0 Scheme 2.
+ This generator uses a SHA-1 HMac as the calculation function.
+
+ The document this implementation is based on can be found at
+
+ RSA's Pkcs5 Page
+
+
+ construct a Pkcs5 Scheme 2 Parameters generator.
+
+
+ Generate a key parameter derived from the password, salt, and iteration
+ count we are currently initialised with.
+
+ @param keySize the size of the key we want (in bits)
+ @return a KeyParameter object.
+
+
+ Generate a key with initialisation vector parameter derived from
+ the password, salt, and iteration count we are currently initialised
+ with.
+
+ @param keySize the size of the key we want (in bits)
+ @param ivSize the size of the iv we want (in bits)
+ @return a ParametersWithIV object.
+
+
+ Generate a key parameter for use with a MAC derived from the password,
+ salt, and iteration count we are currently initialised with.
+
+ @param keySize the size of the key we want (in bits)
+ @return a KeyParameter object.
+
+
+ Generate a random factor suitable for use with RSA blind signatures
+ as outlined in Chaum's blinding and unblinding as outlined in
+ "Handbook of Applied Cryptography", page 475.
+
+
+ Initialise the factor generator
+
+ @param param the necessary RSA key parameters.
+
+
+ Generate a suitable blind factor for the public key the generator was initialised with.
+
+ @return a random blind factor
+
+
+ an RSA key pair generator.
+
+
+ interface for classes implementing the Digital Signature Algorithm
+
+
+ initialise the signer for signature generation or signature
+ verification.
+
+ @param forSigning true if we are generating a signature, false
+ otherwise.
+ @param param key parameters for signature generation.
+
+
+ sign the passed in message (usually the output of a hash function).
+
+ @param message the message to be signed.
+ @return two big integers representing the r and s values respectively.
+
+
+ verify the message message against the signature values r and s.
+
+ @param message the message that was supposed to have been signed.
+ @param r the r signature value.
+ @param s the s signature value.
+
+
+ The base interface for implementations of message authentication codes (MACs).
+
+
+ Initialise the MAC.
+
+ @param param the key and other data required by the MAC.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ Return the block size for this MAC (in bytes).
+
+ @return the block size for this MAC in bytes.
+
+
+ add a single byte to the mac for processing.
+
+ @param in the byte to be processed.
+ @exception InvalidOperationException if the MAC is not initialised.
+
+
+ @param in the array containing the input.
+ @param inOff the index in the array the data begins at.
+ @param len the length of the input starting at inOff.
+ @exception InvalidOperationException if the MAC is not initialised.
+ @exception DataLengthException if there isn't enough data in in.
+
+
+ Compute the final stage of the MAC writing the output to the out
+ parameter.
+
+ doFinal leaves the MAC in the same state it was after the last init.
+
+ @param out the array the MAC is to be output to.
+ @param outOff the offset into the out buffer the output is to start at.
+ @exception DataLengthException if there isn't enough space in out.
+ @exception InvalidOperationException if the MAC is not initialised.
+
+
+ Reset the MAC. At the end of resetting the MAC should be in the
+ in the same state it was after the last init (if there was one).
+
+
+ Return the name of the algorithm the MAC implements.
+
+ @return the name of the algorithm the MAC implements.
+
+
+ this exception is thrown whenever we find something we don't expect in a
+ message.
+
+
+ base constructor.
+
+
+ create a InvalidCipherTextException with the given message.
+
+ @param message the message to be carried with the exception.
+
+
+ Initialise the signer for signing or verification.
+
+ @param forSigning true if for signing, false otherwise
+ @param param necessary parameters.
+
+
+ update the internal digest with the byte b
+
+
+ update the internal digest with the byte array in
+
+
+ Generate a signature for the message we've been loaded with using
+ the key we were initialised with.
+
+
+ return true if the internal state represents the signature described
+ in the passed in array.
+
+
+ reset the internal state
+
+
+ Return the name of the algorithm the signer implements.
+
+ @return the name of the algorithm the signer implements.
+
+
+ Signer with message recovery.
+
+
+ Returns true if the signer has recovered the full message as
+ part of signature verification.
+
+ @return true if full message recovered.
+
+
+ Returns a reference to what message was recovered (if any).
+
+ @return full/partial message, null if nothing.
+
+
+ Perform an update with the recovered message before adding any other data. This must
+ be the first update method called, and calling it will result in the signer assuming
+ that further calls to update will include message content past what is recoverable.
+
+ @param signature the signature that we are in the process of verifying.
+ @throws IllegalStateException
+
+
+ The base class for parameters to key generators.
+
+
+ initialise the generator with a source of randomness
+ and a strength (in bits).
+
+ @param random the random byte source.
+ @param strength the size, in bits, of the keys we want to produce.
+
+
+ return the random source associated with this
+ generator.
+
+ @return the generators random source.
+
+
+ return the bit strength for keys produced by this generator,
+
+ @return the strength of the keys this generator produces (in bits).
+
+
+ standard CBC Block Cipher MAC - if no padding is specified the default of
+ pad of zeroes is used.
+
+
+ create a standard MAC based on a CBC block cipher. This will produce an
+ authentication code half the length of the block size of the cipher.
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+
+
+ create a standard MAC based on a CBC block cipher. This will produce an
+ authentication code half the length of the block size of the cipher.
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param padding the padding to be used to complete the last block.
+
+
+ create a standard MAC based on a block cipher with the size of the
+ MAC been given in bits. This class uses CBC mode as the basis for the
+ MAC generation.
+
+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ and in general should be less than the size of the block cipher as it reduces
+ the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
+
+
+ create a standard MAC based on a block cipher with the size of the
+ MAC been given in bits. This class uses CBC mode as the basis for the
+ MAC generation.
+
+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ and in general should be less than the size of the block cipher as it reduces
+ the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
+ @param padding the padding to be used to complete the last block.
+
+
+ Reset the mac generator.
+
+
+ implements a Cipher-FeedBack (CFB) mode on top of a simple cipher.
+
+
+ Basic constructor.
+
+ @param cipher the block cipher to be used as the basis of the
+ feedback mode.
+ @param blockSize the block size in bits (note: a multiple of 8)
+
+
+ Initialise the cipher and, possibly, the initialisation vector (IV).
+ If an IV isn't passed as part of the parameter, the IV will be all zeros.
+ An IV which is too short is handled in FIPS compliant fashion.
+
+ @param param the key and other data required by the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ return the block size we are operating at.
+
+ @return the block size we are operating at (in bytes).
+
+
+ Process one block of input from the array in and write it to
+ the out array.
+
+ @param in the array containing the input data.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the output data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ reset the chaining vector back to the IV and reset the underlying
+ cipher.
+
+
+ return the algorithm name and mode.
+
+ @return the name of the underlying algorithm followed by "/CFB"
+ and the block size in bits.
+
+
+ create a standard MAC based on a CFB block cipher. This will produce an
+ authentication code half the length of the block size of the cipher, with
+ the CFB mode set to 8 bits.
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+
+
+ create a standard MAC based on a CFB block cipher. This will produce an
+ authentication code half the length of the block size of the cipher, with
+ the CFB mode set to 8 bits.
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param padding the padding to be used.
+
+
+ create a standard MAC based on a block cipher with the size of the
+ MAC been given in bits. This class uses CFB mode as the basis for the
+ MAC generation.
+
+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ and in general should be less than the size of the block cipher as it reduces
+ the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param cfbBitSize the size of an output block produced by the CFB mode.
+ @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
+
+
+ create a standard MAC based on a block cipher with the size of the
+ MAC been given in bits. This class uses CFB mode as the basis for the
+ MAC generation.
+
+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ and in general should be less than the size of the block cipher as it reduces
+ the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param cfbBitSize the size of an output block produced by the CFB mode.
+ @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
+ @param padding a padding to be used.
+
+
+ Reset the mac generator.
+
+
+ CMAC - as specified at www.nuee.nagoya-u.ac.jp/labs/tiwata/omac/omac.html
+
+ CMAC is analogous to OMAC1 - see also en.wikipedia.org/wiki/CMAC
+
+ CMAC is a NIST recomendation - see
+ csrc.nist.gov/CryptoToolkit/modes/800-38_Series_Publications/SP800-38B.pdf
+
+ CMAC/OMAC1 is a blockcipher-based message authentication code designed and
+ analyzed by Tetsu Iwata and Kaoru Kurosawa.
+
+ CMAC/OMAC1 is a simple variant of the CBC MAC (Cipher Block Chaining Message
+ Authentication Code). OMAC stands for One-Key CBC MAC.
+
+ It supports 128- or 64-bits block ciphers, with any key size, and returns
+ a MAC with dimension less or equal to the block size of the underlying
+ cipher.
+
+
+
+ create a standard MAC based on a CBC block cipher (64 or 128 bit block).
+ This will produce an authentication code the length of the block size
+ of the cipher.
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+
+
+ create a standard MAC based on a block cipher with the size of the
+ MAC been given in bits.
+
+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ and in general should be less than the size of the block cipher as it reduces
+ the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param macSizeInBits the size of the MAC in bits, must be a multiple of 8 and @lt;= 128.
+
+
+ Reset the mac generator.
+
+
+ implementation of GOST 28147-89 MAC
+
+
+ HMAC implementation based on RFC2104
+
+ H(K XOR opad, H(K XOR ipad, text))
+
+
+ Reset the mac generator.
+
+
+ DES based CBC Block Cipher MAC according to ISO9797, algorithm 3 (ANSI X9.19 Retail MAC)
+
+ This could as well be derived from CBCBlockCipherMac, but then the property mac in the base
+ class must be changed to protected
+
+
+ create a Retail-MAC based on a CBC block cipher. This will produce an
+ authentication code of the length of the block size of the cipher.
+
+ @param cipher the cipher to be used as the basis of the MAC generation. This must
+ be DESEngine.
+
+
+ create a Retail-MAC based on a CBC block cipher. This will produce an
+ authentication code of the length of the block size of the cipher.
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param padding the padding to be used to complete the last block.
+
+
+ create a Retail-MAC based on a block cipher with the size of the
+ MAC been given in bits. This class uses single DES CBC mode as the basis for the
+ MAC generation.
+
+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ and in general should be less than the size of the block cipher as it reduces
+ the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
+
+
+ create a standard MAC based on a block cipher with the size of the
+ MAC been given in bits. This class uses single DES CBC mode as the basis for the
+ MAC generation. The final block is decrypted and then encrypted using the
+ middle and right part of the key.
+
+ Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
+ or 16 bits if being used as a data authenticator (FIPS Publication 113),
+ and in general should be less than the size of the block cipher as it reduces
+ the chance of an exhaustive attack (see Handbook of Applied Cryptography).
+
+ @param cipher the cipher to be used as the basis of the MAC generation.
+ @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
+ @param padding the padding to be used to complete the last block.
+
+
+ Reset the mac generator.
+
+
+
+ This exception is thrown whenever a cipher requires a change of key, iv
+ or similar after x amount of bytes enciphered
+
+
+
+ implements Cipher-Block-Chaining (CBC) mode on top of a simple cipher.
+
+
+ Basic constructor.
+
+ @param cipher the block cipher to be used as the basis of chaining.
+
+
+ return the underlying block cipher that we are wrapping.
+
+ @return the underlying block cipher that we are wrapping.
+
+
+ Initialise the cipher and, possibly, the initialisation vector (IV).
+ If an IV isn't passed as part of the parameter, the IV will be all zeros.
+
+ @param forEncryption if true the cipher is initialised for
+ encryption, if false for decryption.
+ @param param the key and other data required by the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ return the block size of the underlying cipher.
+
+ @return the block size of the underlying cipher.
+
+
+ Process one block of input from the array in and write it to
+ the out array.
+
+ @param in the array containing the input data.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the output data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ reset the chaining vector back to the IV and reset the underlying
+ cipher.
+
+
+ Do the appropriate chaining step for CBC mode encryption.
+
+ @param in the array containing the data to be encrypted.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the encrypted data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ Do the appropriate chaining step for CBC mode decryption.
+
+ @param in the array containing the data to be decrypted.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the decrypted data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ return the algorithm name and mode.
+
+ @return the name of the underlying algorithm followed by "/CBC".
+
+
+ * Implements the Counter with Cipher Block Chaining mode (CCM) detailed in
+ * NIST Special Publication 800-38C.
+ *
+ * Note: this mode is a packet mode - it needs all the data up front.
+ *
+
+
+
+ A block cipher mode that includes authenticated encryption with a streaming mode
+ and optional associated data.
+
+
+
+ Initialise the cipher.
+ Parameter can either be an AeadParameters or a ParametersWithIV object.
+ Initialise for encryption if true, for decryption if false.
+ The key or other data required by the cipher.
+
+
+ The block size for this cipher, in bytes.
+
+
+ Encrypt/decrypt a single byte.
+
+ @param input the byte to be processed.
+ @param outBytes the output buffer the processed byte goes into.
+ @param outOff the offset into the output byte array the processed data starts at.
+ @return the number of bytes written to out.
+ @exception DataLengthException if the output buffer is too small.
+
+
+ Process a block of bytes from in putting the result into out.
+
+ @param inBytes the input byte array.
+ @param inOff the offset into the in array where the data to be processed starts.
+ @param len the number of bytes to be processed.
+ @param outBytes the output buffer the processed bytes go into.
+ @param outOff the offset into the output byte array the processed data starts at.
+ @return the number of bytes written to out.
+ @exception DataLengthException if the output buffer is too small.
+
+
+ Finish the operation either appending or verifying the MAC at the end of the data.
+
+ @param outBytes space for any resulting output data.
+ @param outOff offset into out to start copying the data at.
+ @return number of bytes written into out.
+ @throws InvalidOperationException if the cipher is in an inappropriate state.
+ @throws InvalidCipherTextException if the MAC fails to match.
+
+
+ Return the value of the MAC associated with the last stream processed.
+
+ @return MAC for plaintext data.
+
+
+ Return the size of the output buffer required for a ProcessBytes
+ an input of len bytes.
+
+ @param len the length of the input.
+ @return the space required to accommodate a call to ProcessBytes
+ with len bytes of input.
+
+
+ Return the size of the output buffer required for a ProcessBytes plus a
+ DoFinal with an input of len bytes.
+
+ @param len the length of the input.
+ @return the space required to accommodate a call to ProcessBytes and DoFinal
+ with len bytes of input.
+
+
+
+ Reset the cipher to the same state as it was after the last init (if there was one).
+
+
+
+ The name of the algorithm this cipher implements.
+
+
+ Basic constructor.
+
+ @param cipher the block cipher to be used.
+
+
+ return the underlying block cipher that we are wrapping.
+
+ @return the underlying block cipher that we are wrapping.
+
+
+ Returns a byte array containing the mac calculated as part of the
+ last encrypt or decrypt operation.
+
+ @return the last mac calculated.
+
+
+ implements a Cipher-FeedBack (CFB) mode on top of a simple cipher.
+
+
+ Basic constructor.
+
+ @param cipher the block cipher to be used as the basis of the
+ feedback mode.
+ @param blockSize the block size in bits (note: a multiple of 8)
+
+
+ return the underlying block cipher that we are wrapping.
+
+ @return the underlying block cipher that we are wrapping.
+
+
+ Initialise the cipher and, possibly, the initialisation vector (IV).
+ If an IV isn't passed as part of the parameter, the IV will be all zeros.
+ An IV which is too short is handled in FIPS compliant fashion.
+
+ @param forEncryption if true the cipher is initialised for
+ encryption, if false for decryption.
+ @param param the key and other data required by the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ return the block size we are operating at.
+
+ @return the block size we are operating at (in bytes).
+
+
+ Process one block of input from the array in and write it to
+ the out array.
+
+ @param in the array containing the input data.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the output data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ Do the appropriate processing for CFB mode encryption.
+
+ @param in the array containing the data to be encrypted.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the encrypted data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ Do the appropriate processing for CFB mode decryption.
+
+ @param in the array containing the data to be decrypted.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the encrypted data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ reset the chaining vector back to the IV and reset the underlying
+ cipher.
+
+
+ return the algorithm name and mode.
+
+ @return the name of the underlying algorithm followed by "/CFB"
+ and the block size in bits.
+
+
+ A Cipher Text Stealing (CTS) mode cipher. CTS allows block ciphers to
+ be used to produce cipher text which is the same outLength as the plain text.
+
+
+ Create a buffered block cipher that uses Cipher Text Stealing
+
+ @param cipher the underlying block cipher this buffering object wraps.
+
+
+ return the size of the output buffer required for an update of 'length' bytes.
+
+ @param length the outLength of the input.
+ @return the space required to accommodate a call to update
+ with length bytes of input.
+
+
+ return the size of the output buffer required for an update plus a
+ doFinal with an input of length bytes.
+
+ @param length the outLength of the input.
+ @return the space required to accommodate a call to update and doFinal
+ with length bytes of input.
+
+
+ process a single byte, producing an output block if neccessary.
+
+ @param in the input byte.
+ @param out the space for any output that might be produced.
+ @param outOff the offset from which the output will be copied.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there isn't enough space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+
+
+ process an array of bytes, producing output if necessary.
+
+ @param in the input byte array.
+ @param inOff the offset at which the input data starts.
+ @param length the number of bytes to be copied out of the input array.
+ @param out the space for any output that might be produced.
+ @param outOff the offset from which the output will be copied.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there isn't enough space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+
+
+ Process the last block in the buffer.
+
+ @param out the array the block currently being held is copied into.
+ @param outOff the offset at which the copying starts.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there is insufficient space in out for
+ the output.
+ @exception InvalidOperationException if the underlying cipher is not
+ initialised.
+ @exception InvalidCipherTextException if cipher text decrypts wrongly (in
+ case the exception will never Get thrown).
+
+
+ A Two-Pass Authenticated-Encryption Scheme Optimized for Simplicity and
+ Efficiency - by M. Bellare, P. Rogaway, D. Wagner.
+
+ http://www.cs.ucdavis.edu/~rogaway/papers/eax.pdf
+
+ EAX is an AEAD scheme based on CTR and OMAC1/CMAC, that uses a single block
+ cipher to encrypt and authenticate data. It's on-line (the length of a
+ message isn't needed to begin processing it), has good performances, it's
+ simple and provably secure (provided the underlying block cipher is secure).
+
+ Of course, this implementations is NOT thread-safe.
+
+
+ Constructor that accepts an instance of a block cipher engine.
+
+ @param cipher the engine to use
+
+
+
+ Implements the Galois/Counter mode (GCM) detailed in
+ NIST Special Publication 800-38D.
+
+
+
+ implements the GOST 28147 OFB counter mode (GCTR).
+
+
+ Basic constructor.
+
+ @param cipher the block cipher to be used as the basis of the
+ counter mode (must have a 64 bit block size).
+
+
+ return the underlying block cipher that we are wrapping.
+
+ @return the underlying block cipher that we are wrapping.
+
+
+ Initialise the cipher and, possibly, the initialisation vector (IV).
+ If an IV isn't passed as part of the parameter, the IV will be all zeros.
+ An IV which is too short is handled in FIPS compliant fashion.
+
+ @param encrypting if true the cipher is initialised for
+ encryption, if false for decryption.
+ @param parameters the key and other data required by the cipher.
+ @exception ArgumentException if the parameters argument is inappropriate.
+
+
+ return the block size we are operating at (in bytes).
+
+ @return the block size we are operating at (in bytes).
+
+
+ Process one block of input from the array in and write it to
+ the out array.
+
+ @param in the array containing the input data.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the output data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ reset the feedback vector back to the IV and reset the underlying
+ cipher.
+
+
+ return the algorithm name and mode.
+
+ @return the name of the underlying algorithm followed by "/GCTR"
+ and the block size in bits
+
+
+ implements a Output-FeedBack (OFB) mode on top of a simple cipher.
+
+
+ Basic constructor.
+
+ @param cipher the block cipher to be used as the basis of the
+ feedback mode.
+ @param blockSize the block size in bits (note: a multiple of 8)
+
+
+ return the underlying block cipher that we are wrapping.
+
+ @return the underlying block cipher that we are wrapping.
+
+
+ Initialise the cipher and, possibly, the initialisation vector (IV).
+ If an IV isn't passed as part of the parameter, the IV will be all zeros.
+ An IV which is too short is handled in FIPS compliant fashion.
+
+ @param forEncryption if true the cipher is initialised for
+ encryption, if false for decryption.
+ @param param the key and other data required by the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ return the block size we are operating at (in bytes).
+
+ @return the block size we are operating at (in bytes).
+
+
+ Process one block of input from the array in and write it to
+ the out array.
+
+ @param in the array containing the input data.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the output data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ reset the feedback vector back to the IV and reset the underlying
+ cipher.
+
+
+ return the algorithm name and mode.
+
+ @return the name of the underlying algorithm followed by "/OFB"
+ and the block size in bits
+
+
+ * Implements OpenPGP's rather strange version of Cipher-FeedBack (CFB) mode
+ * on top of a simple cipher. This class assumes the IV has been prepended
+ * to the data stream already, and just accomodates the reset after
+ * (blockSize + 2) bytes have been read.
+ *
+
+
+ Basic constructor.
+
+ @param cipher the block cipher to be used as the basis of the
+ feedback mode.
+
+
+ return the underlying block cipher that we are wrapping.
+
+ @return the underlying block cipher that we are wrapping.
+
+
+ return the block size we are operating at.
+
+ @return the block size we are operating at (in bytes).
+
+
+ Process one block of input from the array in and write it to
+ the out array.
+
+ @param in the array containing the input data.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the output data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ reset the chaining vector back to the IV and reset the underlying
+ cipher.
+
+
+ Initialise the cipher and, possibly, the initialisation vector (IV).
+ If an IV isn't passed as part of the parameter, the IV will be all zeros.
+ An IV which is too short is handled in FIPS compliant fashion.
+
+ @param forEncryption if true the cipher is initialised for
+ encryption, if false for decryption.
+ @param parameters the key and other data required by the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ Encrypt one byte of data according to CFB mode.
+ @param data the byte to encrypt
+ @param blockOff offset in the current block
+ @returns the encrypted byte
+
+
+ Do the appropriate processing for CFB IV mode encryption.
+
+ @param in the array containing the data to be encrypted.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the encrypted data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ Do the appropriate processing for CFB IV mode decryption.
+
+ @param in the array containing the data to be decrypted.
+ @param inOff offset into the in array the data starts at.
+ @param out the array the encrypted data will be copied into.
+ @param outOff the offset into the out array the output will start at.
+ @exception DataLengthException if there isn't enough data in in, or
+ space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+ @return the number of bytes processed and produced.
+
+
+ return the algorithm name and mode.
+
+ @return the name of the underlying algorithm followed by "/PGPCFB"
+ and the block size in bits.
+
+
+ Implements the Segmented Integer Counter (SIC) mode on top of a simple
+ block cipher.
+
+
+ Basic constructor.
+
+ @param c the block cipher to be used.
+
+
+ return the underlying block cipher that we are wrapping.
+
+ @return the underlying block cipher that we are wrapping.
+
+
+ Block cipher padders are expected to conform to this interface
+
+
+ Initialise the padder.
+
+ @param param parameters, if any required.
+
+
+ add the pad bytes to the passed in block, returning the
+ number of bytes added.
+
+
+ return the number of pad bytes present in the block.
+ @exception InvalidCipherTextException if the padding is badly formed
+ or invalid.
+
+
+ Return the name of the algorithm the cipher implements.
+
+ @return the name of the algorithm the cipher implements.
+
+
+ A padder that adds ISO10126-2 padding to a block.
+
+
+ Initialise the padder.
+
+ @param random a SecureRandom if available.
+
+
+ add the pad bytes to the passed in block, returning the
+ number of bytes added.
+
+
+ return the number of pad bytes present in the block.
+
+
+ Return the name of the algorithm the cipher implements.
+
+ @return the name of the algorithm the cipher implements.
+
+
+ A padder that adds the padding according to the scheme referenced in
+ ISO 7814-4 - scheme 2 from ISO 9797-1. The first byte is 0x80, rest is 0x00
+
+
+ Initialise the padder.
+
+ @param random - a SecureRandom if available.
+
+
+ add the pad bytes to the passed in block, returning the
+ number of bytes added.
+
+
+ return the number of pad bytes present in the block.
+
+
+ Return the name of the algorithm the padder implements.
+
+ @return the name of the algorithm the padder implements.
+
+
+ A wrapper class that allows block ciphers to be used to process data in
+ a piecemeal fashion with padding. The PaddedBufferedBlockCipher
+ outputs a block only when the buffer is full and more data is being added,
+ or on a doFinal (unless the current block in the buffer is a pad block).
+ The default padding mechanism used is the one outlined in Pkcs5/Pkcs7.
+
+
+ Create a buffered block cipher with the desired padding.
+
+ @param cipher the underlying block cipher this buffering object wraps.
+ @param padding the padding type.
+
+
+ Create a buffered block cipher Pkcs7 padding
+
+ @param cipher the underlying block cipher this buffering object wraps.
+
+
+ initialise the cipher.
+
+ @param forEncryption if true the cipher is initialised for
+ encryption, if false for decryption.
+ @param param the key and other data required by the cipher.
+ @exception ArgumentException if the parameters argument is
+ inappropriate.
+
+
+ return the minimum size of the output buffer required for an update
+ plus a doFinal with an input of len bytes.
+
+ @param len the length of the input.
+ @return the space required to accommodate a call to update and doFinal
+ with len bytes of input.
+
+
+ return the size of the output buffer required for an update
+ an input of len bytes.
+
+ @param len the length of the input.
+ @return the space required to accommodate a call to update
+ with len bytes of input.
+
+
+ process a single byte, producing an output block if neccessary.
+
+ @param in the input byte.
+ @param out the space for any output that might be produced.
+ @param outOff the offset from which the output will be copied.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there isn't enough space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+
+
+ process an array of bytes, producing output if necessary.
+
+ @param in the input byte array.
+ @param inOff the offset at which the input data starts.
+ @param len the number of bytes to be copied out of the input array.
+ @param out the space for any output that might be produced.
+ @param outOff the offset from which the output will be copied.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there isn't enough space in out.
+ @exception InvalidOperationException if the cipher isn't initialised.
+
+
+ Process the last block in the buffer. If the buffer is currently
+ full and padding needs to be added a call to doFinal will produce
+ 2 * GetBlockSize() bytes.
+
+ @param out the array the block currently being held is copied into.
+ @param outOff the offset at which the copying starts.
+ @return the number of output bytes copied to out.
+ @exception DataLengthException if there is insufficient space in out for
+ the output or we are decrypting and the input is not block size aligned.
+ @exception InvalidOperationException if the underlying cipher is not
+ initialised.
+ @exception InvalidCipherTextException if padding is expected and not found.
+
+
+ A padder that adds Pkcs7/Pkcs5 padding to a block.
+
+
+ Initialise the padder.
+
+ @param random - a SecureRandom if available.
+
+
+ add the pad bytes to the passed in block, returning the
+ number of bytes added.
+
+
+ return the number of pad bytes present in the block.
+
+
+ Return the name of the algorithm the cipher implements.
+
+ @return the name of the algorithm the cipher implements.
+
+
+ A padder that adds Trailing-Bit-Compliment padding to a block.
+
+ This padding pads the block out compliment of the last bit
+ of the plain text.
+
+
+
+
+ Initialise the padder.
+ - a SecureRandom if available.
+
+
+
+ add the pad bytes to the passed in block, returning the
+ number of bytes added.
+
+ Note: this assumes that the last block of plain text is always
+ passed to it inside in. i.e. if inOff is zero, indicating the
+ entire block is to be overwritten with padding the value of in
+ should be the same as the last block of plain text.
+
+
+
+
+ return the number of pad bytes present in the block.
+
+
+ Return the name of the algorithm the cipher implements.
+ the name of the algorithm the cipher implements.
+
+
+
+ A padder that adds X9.23 padding to a block - if a SecureRandom is
+ passed in random padding is assumed, otherwise padding with zeros is used.
+
+
+ Initialise the padder.
+
+ @param random a SecureRandom if one is available.
+
+
+ add the pad bytes to the passed in block, returning the
+ number of bytes added.
+
+
+ return the number of pad bytes present in the block.
+
+
+ Return the name of the algorithm the cipher implements.
+
+ @return the name of the algorithm the cipher implements.
+
+
+ A padder that adds Null byte padding to a block.
+
+
+ Initialise the padder.
+
+
+ - a SecureRandom if available.
+
+
+
+ add the pad bytes to the passed in block, returning the
+ number of bytes added.
+
+
+
+ return the number of pad bytes present in the block.
+
+
+ Return the name of the algorithm the cipher implements.
+
+
+ the name of the algorithm the cipher implements.
+
+
+
+ Base constructor.
+
+ @param key key to be used by underlying cipher
+ @param macSize macSize in bits
+ @param nonce nonce to be used
+ @param associatedText associated text, if any
+
+
+ Base constructor.
+
+ @param key key to be used by underlying cipher
+ @param macSize macSize in bits
+ @param nonce nonce to be used
+ @param associatedText associated text, if any
+
+
+ DES has 16 weak keys. This method will check
+ if the given DES key material is weak or semi-weak.
+ Key material that is too short is regarded as weak.
+
+ @return true if the given DES key material is weak or semi-weak,
+ false otherwise.
+
+
+ DES Keys use the LSB as the odd parity bit. This can
+ be used to check for corrupt keys.
+
+ @param bytes the byte array to set the parity on.
+
+
+ return true if the passed in key is a DES-EDE weak key.
+
+ @param key bytes making up the key
+ @param offset offset into the byte array the key starts at
+ @param length number of bytes making up the key
+
+
+ return true if the passed in key is a DES-EDE weak key.
+
+ @param key bytes making up the key
+ @param offset offset into the byte array the key starts at
+
+
+ The minimum bitlength of the private value.
+
+
+ The bitlength of the private value.
+
+
+ return the generator - g
+
+
+ return private value limit - l
+
+
+ parameters for using an integrated cipher in stream mode.
+
+
+ @param derivation the derivation parameter for the KDF function.
+ @param encoding the encoding parameter for the KDF function.
+ @param macKeySize the size of the MAC key (in bits).
+
+
+ @param derivation the derivation parameter for the KDF function.
+ @param encoding the encoding parameter for the KDF function.
+ @param macKeySize the size of the MAC key (in bits).
+ @param cipherKeySize the size of the associated Cipher key (in bits).
+
+
+ parameters for Key derivation functions for ISO-18033
+
+
+ parameters for Key derivation functions for IEEE P1363a
+
+
+ Parameters for mask derivation functions.
+
+
+ Parameters for NaccacheStern public private key generation. For details on
+ this cipher, please see
+
+ http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
+
+
+ Parameters for generating a NaccacheStern KeyPair.
+
+ @param random
+ The source of randomness
+ @param strength
+ The desired strength of the Key in Bits
+ @param certainty
+ the probability that the generated primes are not really prime
+ as integer: 2^(-certainty) is then the probability
+ @param countSmallPrimes
+ How many small key factors are desired
+
+
+ Parameters for a NaccacheStern KeyPair.
+
+ @param random
+ The source of randomness
+ @param strength
+ The desired strength of the Key in Bits
+ @param certainty
+ the probability that the generated primes are not really prime
+ as integer: 2^(-certainty) is then the probability
+ @param cntSmallPrimes
+ How many small key factors are desired
+ @param debug
+ Turn debugging on or off (reveals secret information, use with
+ caution)
+
+
+ @return Returns the certainty.
+
+
+ @return Returns the countSmallPrimes.
+
+
+ Public key parameters for NaccacheStern cipher. For details on this cipher,
+ please see
+
+ http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
+
+
+ @param privateKey
+
+
+ @return Returns the g.
+
+
+ @return Returns the lowerSigmaBound.
+
+
+ @return Returns the n.
+
+
+ Private key parameters for NaccacheStern cipher. For details on this cipher,
+ please see
+
+ http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf
+
+
+ Constructs a NaccacheSternPrivateKey
+
+ @param g
+ the public enryption parameter g
+ @param n
+ the public modulus n = p*q
+ @param lowerSigmaBound
+ the public lower sigma bound up to which data can be encrypted
+ @param smallPrimes
+ the small primes, of which sigma is constructed in the right
+ order
+ @param phi_n
+ the private modulus phi(n) = (p-1)(q-1)
+
+
+ Cipher parameters with a fixed salt value associated with them.
+
+
+ Random generation based on the digest with counter. Calling AddSeedMaterial will
+ always increase the entropy of the hash.
+
+ Internal access to the digest is synchronized so a single one of these can be shared.
+
+
+
+ Generic interface for objects generating random bytes.
+
+
+ Add more seed material to the generator.
+ A byte array to be mixed into the generator's state.
+
+
+ Add more seed material to the generator.
+ A long value to be mixed into the generator's state.
+
+
+ Fill byte array with random values.
+ Array to be filled.
+
+
+ Fill byte array with random values.
+ Array to receive bytes.
+ Index to start filling at.
+ Length of segment to fill.
+
+
+
+ Takes bytes generated by an underling RandomGenerator and reverses the order in
+ each small window (of configurable size).
+
+ Access to internals is synchronized so a single one of these can be shared.
+
+
+
+
+ Add more seed material to the generator.
+ A byte array to be mixed into the generator's state.
+
+
+ Add more seed material to the generator.
+ A long value to be mixed into the generator's state.
+
+
+ Fill byte array with random values.
+ Array to be filled.
+
+
+ Fill byte array with random values.
+ Array to receive bytes.
+ Index to start filling at.
+ Length of segment to fill.
+
+
+ A thread based seed generator - one source of randomness.
+
+ Based on an idea from Marcus Lippert.
+
+
+
+ Generate seed bytes. Set fast to false for best quality.
+
+ If fast is set to true, the code should be round about 8 times faster when
+ generating a long sequence of random bytes. 20 bytes of random values using
+ the fast mode take less than half a second on a Nokia e70. If fast is set to false,
+ it takes round about 2500 ms.
+
+ @param numBytes the number of bytes to generate
+ @param fast true if fast mode should be used
+
+
+
+ Permutation generated by code:
+
+ // First 1850 fractional digit of Pi number.
+ byte[] key = new BigInteger("14159265358979323846...5068006422512520511").ToByteArray();
+ s = 0;
+ P = new byte[256];
+ for (int i = 0; i < 256; i++)
+ {
+ P[i] = (byte) i;
+ }
+ for (int m = 0; m < 768; m++)
+ {
+ s = P[(s + P[m & 0xff] + key[m % key.length]) & 0xff];
+ byte temp = P[m & 0xff];
+ P[m & 0xff] = P[s & 0xff];
+ P[s & 0xff] = temp;
+ }
+
+
+
+ Value generated in the same way as P.
+
+
+ update the internal digest with the byte b
+
+
+ update the internal digest with the byte array in
+
+
+ Generate a signature for the message we've been loaded with using
+ the key we were initialised with.
+
+
+ true if the internal state represents the signature described in the passed in array.
+
+
+ Reset the internal state
+
+
+ The Digital Signature Algorithm - as described in "Handbook of Applied
+ Cryptography", pages 452 - 453.
+
+
+ Generate a signature for the given message using the key we were
+ initialised with. For conventional DSA the message should be a SHA-1
+ hash of the message of interest.
+
+ @param message the message that will be verified later.
+
+
+ return true if the value r and s represent a DSA signature for
+ the passed in message for standard DSA the message should be a
+ SHA-1 hash of the real message to be verified.
+
+
+ EC-DSA as described in X9.62
+
+
+ Generate a signature for the given message using the key we were
+ initialised with. For conventional DSA the message should be a SHA-1
+ hash of the message of interest.
+
+ @param message the message that will be verified later.
+
+
+ return true if the value r and s represent a DSA signature for
+ the passed in message (for standard DSA the message should be
+ a SHA-1 hash of the real message to be verified).
+
+
+ GOST R 34.10-2001 Signature Algorithm
+
+
+ generate a signature for the given message using the key we were
+ initialised with. For conventional GOST3410 the message should be a GOST3411
+ hash of the message of interest.
+
+ @param message the message that will be verified later.
+
+
+ return true if the value r and s represent a GOST3410 signature for
+ the passed in message (for standard GOST3410 the message should be
+ a GOST3411 hash of the real message to be verified).
+
+
+ EC-NR as described in IEEE 1363-2000
+
+
+ generate a signature for the given message using the key we were
+ initialised with. Generally, the order of the curve should be at
+ least as long as the hash of the message of interest, and with
+ ECNR it *must* be at least as long.
+
+ @param digest the digest to be signed.
+ @exception DataLengthException if the digest is longer than the key allows
+
+
+ return true if the value r and s represent a signature for the
+ message passed in. Generally, the order of the curve should be at
+ least as long as the hash of the message of interest, and with
+ ECNR, it *must* be at least as long. But just in case the signer
+ applied mod(n) to the longer digest, this implementation will
+ apply mod(n) during verification.
+
+ @param digest the digest to be verified.
+ @param r the r value of the signature.
+ @param s the s value of the signature.
+ @exception DataLengthException if the digest is longer than the key allows
+
+
+ initialise the signer for signing or verification.
+
+ @param forSigning
+ true if for signing, false otherwise
+ @param parameters
+ necessary parameters.
+
+
+ update the internal digest with the byte b
+
+
+ update the internal digest with the byte array in
+
+
+ Generate a signature for the message we've been loaded with using the key
+ we were initialised with.
+
+
+ return true if the internal state represents the signature described in
+ the passed in array.
+
+
+ update the internal digest with the byte b
+
+
+ update the internal digest with the byte array in
+
+
+ Generate a signature for the message we've been loaded with using
+ the key we were initialised with.
+
+
+ true if the internal state represents the signature described in the passed in array.
+
+
+ Reset the internal state
+
+
+ Gost R 34.10-94 Signature Algorithm
+
+
+ generate a signature for the given message using the key we were
+ initialised with. For conventional Gost3410 the message should be a Gost3411
+ hash of the message of interest.
+
+ @param message the message that will be verified later.
+
+
+ return true if the value r and s represent a Gost3410 signature for
+ the passed in message for standard Gost3410 the message should be a
+ Gost3411 hash of the real message to be verified.
+
+
+ ISO9796-2 - mechanism using a hash function with recovery (scheme 2 and 3).
+
+ Note: the usual length for the salt is the length of the hash
+ function used in bytes.
+
+
+
+
+ Return a reference to the recoveredMessage message.
+
+ The full/partial recoveredMessage message.
+
+
+
+
+ Generate a signer for the with either implicit or explicit trailers
+ for ISO9796-2, scheme 2 or 3.
+
+ base cipher to use for signature creation/verification
+ digest to use.
+ length of salt in bytes.
+ whether or not the trailer is implicit or gives the hash.
+
+
+ Constructor for a signer with an explicit digest trailer.
+
+
+ cipher to use.
+
+ digest to sign with.
+
+ length of salt in bytes.
+
+
+
+ Initialise the signer.
+ true if for signing, false if for verification.
+ parameters for signature generation/verification. If the
+ parameters are for generation they should be a ParametersWithRandom,
+ a ParametersWithSalt, or just an RsaKeyParameters object. If RsaKeyParameters
+ are passed in a SecureRandom will be created.
+
+ if wrong parameter type or a fixed
+ salt is passed in which is the wrong length.
+
+
+
+ compare two byte arrays - constant time.
+
+
+ clear possible sensitive data
+
+
+ update the internal digest with the byte b
+
+
+ update the internal digest with the byte array in
+
+
+ reset the internal state
+
+
+ Generate a signature for the loaded message using the key we were
+ initialised with.
+
+
+
+ return true if the signature represents a ISO9796-2 signature
+ for the passed in message.
+
+
+
+
+ Return true if the full message was recoveredMessage.
+
+ true on full message recovery, false otherwise, or if not sure.
+
+
+
+ int to octet string.
+ int to octet string.
+
+
+ long to octet string.
+
+
+ mask generator function, as described in Pkcs1v2.
+
+
+ ISO9796-2 - mechanism using a hash function with recovery (scheme 1)
+
+
+
+ Return a reference to the recoveredMessage message.
+
+ The full/partial recoveredMessage message.
+
+
+
+
+ Generate a signer for the with either implicit or explicit trailers
+ for ISO9796-2.
+
+ base cipher to use for signature creation/verification
+ digest to use.
+ whether or not the trailer is implicit or gives the hash.
+
+
+ Constructor for a signer with an explicit digest trailer.
+
+
+ cipher to use.
+
+ digest to sign with.
+
+
+
+ compare two byte arrays - constant time.
+
+
+ clear possible sensitive data
+
+
+ update the internal digest with the byte b
+
+
+ update the internal digest with the byte array in
+
+
+ reset the internal state
+
+
+ Generate a signature for the loaded message using the key we were
+ initialised with.
+
+
+
+ return true if the signature represents a ISO9796-2 signature
+ for the passed in message.
+
+
+
+
+ Return true if the full message was recoveredMessage.
+
+ true on full message recovery, false otherwise.
+
+
+
+ RSA-PSS as described in Pkcs# 1 v 2.1.
+
+ Note: the usual value for the salt length is the number of
+ bytes in the hash function.
+
+
+
+ Basic constructor
+ the asymmetric cipher to use.
+ the digest to use.
+ the length of the salt to use (in bytes).
+
+
+ clear possible sensitive data
+
+
+ update the internal digest with the byte b
+
+
+ update the internal digest with the byte array in
+
+
+ reset the internal state
+
+
+ Generate a signature for the message we've been loaded with using
+ the key we were initialised with.
+
+
+
+ return true if the internal state represents the signature described
+ in the passed in array.
+
+
+
+ int to octet string.
+
+
+ mask generator function, as described in Pkcs1v2.
+
+
+
+ Load oid table.
+
+
+
+ Initialise the signer for signing or verification.
+
+ @param forSigning true if for signing, false otherwise
+ @param param necessary parameters.
+
+
+ update the internal digest with the byte b
+
+
+ update the internal digest with the byte array in
+
+
+ Generate a signature for the message we've been loaded with using
+ the key we were initialised with.
+
+
+ return true if the internal state represents the signature described
+ in the passed in array.
+
+
+ a wrapper for block ciphers with a single byte block size, so that they
+ can be treated like stream ciphers.
+
+
+ basic constructor.
+
+ @param cipher the block cipher to be wrapped.
+ @exception ArgumentException if the cipher has a block size other than
+ one.
+
+
+ initialise the underlying cipher.
+
+ @param forEncryption true if we are setting up for encryption, false otherwise.
+ @param param the necessary parameters for the underlying cipher to be initialised.
+
+
+ encrypt/decrypt a single byte returning the result.
+
+ @param in the byte to be processed.
+ @return the result of processing the input byte.
+
+
+ process a block of bytes from in putting the result into out.
+
+ @param in the input byte array.
+ @param inOff the offset into the in array where the data to be processed starts.
+ @param len the number of bytes to be processed.
+ @param out the output buffer the processed bytes go into.
+ @param outOff the offset into the output byte array the processed data stars at.
+ @exception DataLengthException if the output buffer is too small.
+
+
+ reset the underlying cipher. This leaves it in the same state
+ it was at after the last init (if there was one).
+
+
+ return the name of the algorithm we are wrapping.
+
+ @return the name of the algorithm we are wrapping.
+
+
+
+ RFC 2246 7.2
+
+
+
+
+ RFC 2246 7.2
+
+
+
+
+ A certificate verifyer, that will always return true.
+
+ DO NOT USE THIS FILE UNLESS YOU KNOW EXACTLY WHAT YOU ARE DOING.
+
+
+
+
+
+ This should be implemented by any class which can find out, if a given
+ certificate chain is being accepted by an client.
+
+
+
+ The certs, which are part of the chain.
+ True, if the chain is accepted, false otherwise
+
+
+ Return true.
+
+
+
+ A queue for bytes.
+
+ This file could be more optimized.
+
+
+
+
+ The initial size for our buffer.
+
+
+ The smallest number which can be written as 2^x which is bigger than i.
+
+
+ The buffer where we store our data.
+
+
+ How many bytes at the beginning of the buffer are skipped.
+
+
+ How many bytes in the buffer are valid data.
+
+
+ Read data from the buffer.
+ The buffer where the read data will be copied to.
+ How many bytes to skip at the beginning of buf.
+ How many bytes to read at all.
+ How many bytes from our data to skip.
+
+
+ Add some data to our buffer.
+ A byte-array to read data from.
+ How many bytes to skip at the beginning of the array.
+ How many bytes to read from the array.
+
+
+ Remove some bytes from our data from the beginning.
+ How many bytes to remove.
+
+
+ The number of bytes which are available in this buffer.
+
+
+ A representation for a certificate chain.
+
+
+ The certificates.
+
+
+ Parse the ServerCertificate message.
+
+ @param inStr The stream where to parse from.
+ @return A Certificate object with the certs, the server has sended.
+ @throws IOException If something goes wrong during parsing.
+
+
+ Encodes version of the ClientCertificate message
+
+ @param outStr stream to write the message to
+ @throws IOException If something goes wrong
+
+
+ Private constructor from a cert array.
+
+ @param certs The certs the chain should contain.
+
+
+ An array which contains the certs, this chain contains.
+
+
+ A of X509Name
+
+
+
+ RFC 2246 A.5
+
+
+
+
+ RFC 2246 7.4.4
+
+
+
+ A combined hash, which implements md5(m) || sha1(m).
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ RFC 2246 6.1
+
+
+
+
+ RFC 2246 6.2.1
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Called at the start of a new TLS session, before any other methods.
+
+
+ A
+
+
+
+
+ Get the list of cipher suites that this client supports.
+
+
+ An array of , each specifying a supported cipher suite.
+
+
+
+
+ Get the list of compression methods that this client supports.
+
+
+ An array of , each specifying a supported compression method.
+
+
+
+
+ Get the (optional) table of client extensions to be included in (extended) client hello.
+
+
+ A ( -> byte[]). May be null.
+
+
+
+
+
+ Reports the session ID once it has been determined.
+
+
+ A
+
+
+
+
+ Report the cipher suite that was selected by the server.
+
+
+ The protocol handler validates this value against the offered cipher suites
+
+
+
+ A
+
+
+
+
+ Report the compression method that was selected by the server.
+
+
+ The protocol handler validates this value against the offered compression methods
+
+
+
+ A
+
+
+
+
+ Report whether the server supports secure renegotiation
+
+
+ The protocol handler automatically processes the relevant extensions
+
+
+ A , true if the server supports secure renegotiation
+
+
+
+
+
+ Report the extensions from an extended server hello.
+
+
+ Will only be called if we returned a non-null result from .
+
+
+ A ( -> byte[])
+
+
+
+
+ Return an implementation of to negotiate the key exchange
+ part of the protocol.
+
+
+ A
+
+
+
+
+
+ Return an implementation of to handle authentication
+ part of the protocol.
+
+
+
+
+
+ Return an implementation of to handle record compression.
+
+
+
+
+
+ Return an implementation of to use for encryption/decryption.
+
+
+ A
+
+
+
+
+
+
+
+
+ RFC 4492 5.4
+
+
+
+ Indicates the elliptic curve domain parameters are conveyed verbosely, and the
+ underlying finite field is a prime field.
+
+
+ Indicates the elliptic curve domain parameters are conveyed verbosely, and the
+ underlying finite field is a characteristic-2 field.
+
+
+ Indicates that a named curve is used. This option SHOULD be used when applicable.
+
+
+
+ RFC 4492 5.1.2
+
+
+
+
+ RFC 4366 2.3
+
+
+
+
+ RFC 2246 7.4
+
+
+
+
+ A temporary class to wrap old CertificateVerifyer stuff for new TlsAuthentication.
+
+
+
+
+ Called by the protocol handler to report the server certificate.
+
+
+ This method is responsible for certificate verification and validation
+
+ The server received
+
+
+
+
+ Return client credentials in response to server's certificate request
+
+
+ A containing server certificate request details
+
+
+ A to be used for client authentication
+ (or null for no client authentication)
+
+
+
+
+
+ A temporary class to use LegacyTlsAuthentication
+
+
+
+
+ RFC 4492 5.1.1
+ The named curves defined here are those specified in SEC 2 [13]. Note that many of
+ these curves are also recommended in ANSI X9.62 [7] and FIPS 186-2 [11]. Values 0xFE00
+ through 0xFEFF are reserved for private use. Values 0xFF01 and 0xFF02 indicate that the
+ client supports arbitrary prime and characteristic-2 curves, respectively (the curve
+ parameters must be encoded explicitly in ECParameters).
+
+
+
+ An implementation of the TLS 1.0 record layer.
+
+
+ HMAC implementation based on original internet draft for HMAC (RFC 2104)
+
+ The difference is that padding is concatentated versus XORed with the key
+
+ H(K + opad, H(K + ipad, text))
+
+
+ Base constructor for one of the standard digest algorithms that the byteLength of
+ the algorithm is know for. Behaviour is undefined for digests other than MD5 or SHA1.
+
+ @param digest the digest.
+
+
+ Reset the mac generator.
+
+
+
+ A generic TLS 1.0 block cipher. This can be used for AES or 3DES for example.
+
+
+
+
+
+
+
+
+
+
+ TLS 1.0 DH key exchange.
+
+
+
+
+ A generic interface for key exchange implementations in TLS 1.0.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ECDHE key exchange (see RFC 4492)
+
+
+ ECDH key exchange (see RFC 4492)
+
+
+
+ A generic TLS MAC implementation, which can be used with any kind of
+ IDigest to act as an HMAC.
+
+
+
+ Generate a new instance of an TlsMac.
+
+ @param digest The digest to use.
+ @param key_block A byte-array where the key for this mac is located.
+ @param offset The number of bytes to skip, before the key starts in the buffer.
+ @param len The length of the key.
+
+
+ @return the MAC write secret
+
+
+ Increment the current write sequence number
+
+
+ Calculate the mac for some given data.
+
+ TlsMac will keep track of the sequence number internally.
+
+ @param type The message type of the message.
+ @param message A byte-buffer containing the message.
+ @param offset The number of bytes to skip, before the message starts.
+ @param len The length of the message.
+ @return A new byte-buffer containing the mac value.
+
+
+ @return the current write sequence number
+
+
+ @return The Keysize of the mac.
+
+
+
+ A NULL cipher suite, for use during handshake.
+
+
+
+ An implementation of all high level protocols in TLS 1.0.
+
+
+ Both streams can be the same object
+
+
+ Both streams can be the same object
+
+
+ This method is called, when a change cipher spec message is received.
+
+ @throws IOException If the message has an invalid content or the
+ handshake is not in the correct state.
+
+
+ Connects to the remote system.
+ Will be used when a certificate is received to verify
+ that this certificate is accepted by the client.
+ If handshake was not successful
+
+
+ Read data from the network. The method will return immediately, if there is
+ still some data left in the buffer, or block until some application
+ data has been read from the network.
+
+ @param buf The buffer where the data will be copied to.
+ @param offset The position where the data will be placed in the buffer.
+ @param len The maximum number of bytes to read.
+ @return The number of bytes read.
+ @throws IOException If something goes wrong during reading data.
+
+
+ Send some application data to the remote system.
+
+ The method will handle fragmentation internally.
+
+ @param buf The buffer with the data.
+ @param offset The position in the buffer where the data is placed.
+ @param len The length of the data.
+ @throws IOException If something goes wrong during sending.
+
+
+ Terminate this connection with an alert.
+
+ Can be used for normal closure too.
+
+ @param alertLevel The level of the alert, an be AlertLevel.fatal or AL_warning.
+ @param alertDescription The exact alert message.
+ @throws IOException If alert was fatal.
+
+
+ Closes this connection
+ If something goes wrong during closing.
+
+
+ Make sure the Stream is now empty. Fail otherwise.
+
+ @param is The Stream to check.
+ @throws IOException If is is not empty.
+
+
+ A Stream which can be used to send data.
+
+
+ A Stream which can be used to read data.
+
+
+ The secure bidirectional stream for this connection
+
+
+
+ TLS 1.0 RSA key exchange.
+
+
+
+
+ TLS 1.1 SRP key exchange.
+
+
+
+ Some helper fuctions for MicroTLS.
+
+
+ return a = a + b - b preserved.
+
+
+ unsigned comparison on two arrays - note the arrays may
+ start with leading zeros.
+
+
+ return z = x / y - done in place (z value preserved, x contains the
+ remainder)
+
+
+ return whether or not a BigInteger is probably prime with a
+ probability of 1 - (1/2)**certainty.
+
From Knuth Vol 2, pg 395.
+
+
+ Calculate the numbers u1, u2, and u3 such that:
+
+ u1 * a + u2 * b = u3
+
+ where u3 is the greatest common divider of a and b.
+ a and b using the extended Euclid algorithm (refer p. 323
+ of The Art of Computer Programming vol 2, 2nd ed).
+ This also seems to have the side effect of calculating
+ some form of multiplicative inverse.
+
+ @param a First number to calculate gcd for
+ @param b Second number to calculate gcd for
+ @param u1Out the return object for the u1 value
+ @param u2Out the return object for the u2 value
+ @return The greatest common divisor of a and b
+
+
+ return w with w = x * x - w is assumed to have enough space.
+
+
+ return x with x = y * z - x is assumed to have enough space.
+
+
+ Calculate mQuote = -m^(-1) mod b with b = 2^32 (32 = word size)
+
+
+ Montgomery multiplication: a = x * y * R^(-1) mod m
+
+ Based algorithm 14.36 of Handbook of Applied Cryptography.
+
+
m, x, y should have length n
+
a should have length (n + 1)
+
b = 2^32, R = b^n
+
+ The result is put in x
+
+ NOTE: the indices of x, y, m, a different in HAC and in Java
+
+
+ return x = x % y - done in place (y value preserved)
+
+
+ do a left shift - this returns a new array.
+
+
+ do a right shift - this does it in place.
+
+
+ do a right shift by one - this does it in place.
+
+
+ returns x = x - y - we assume x is >= y
+
+
+ Class representing a simple version of a big decimal. A
+ SimpleBigDecimal is basically a
+ {@link java.math.BigInteger BigInteger} with a few digits on the right of
+ the decimal point. The number of (binary) digits on the right of the decimal
+ point is called the scale of the SimpleBigDecimal.
+ Unlike in {@link java.math.BigDecimal BigDecimal}, the scale is not adjusted
+ automatically, but must be set manually. All SimpleBigDecimals
+ taking part in the same arithmetic operation must have equal scale. The
+ result of a multiplication of two SimpleBigDecimals returns a
+ SimpleBigDecimal with double scale.
+
+
+ Returns a SimpleBigDecimal representing the same numerical
+ value as value.
+ @param value The value of the SimpleBigDecimal to be
+ created.
+ @param scale The scale of the SimpleBigDecimal to be
+ created.
+ @return The such created SimpleBigDecimal.
+
+
+ Constructor for SimpleBigDecimal. The value of the
+ constructed SimpleBigDecimal Equals bigInt /
+ 2scale.
+ @param bigInt The bigInt value parameter.
+ @param scale The scale of the constructed SimpleBigDecimal.
+
+
+ Class holding methods for point multiplication based on the window
+ τ-adic nonadjacent form (WTNAF). The algorithms are based on the
+ paper "Improved Algorithms for Arithmetic on Anomalous Binary Curves"
+ by Jerome A. Solinas. The paper first appeared in the Proceedings of
+ Crypto 1997.
+
+
+ The window width of WTNAF. The standard value of 4 is slightly less
+ than optimal for running time, but keeps space requirements for
+ precomputation low. For typical curves, a value of 5 or 6 results in
+ a better running time. When changing this value, the
+ αu's must be computed differently, see
+ e.g. "Guide to Elliptic Curve Cryptography", Darrel Hankerson,
+ Alfred Menezes, Scott Vanstone, Springer-Verlag New York Inc., 2004,
+ p. 121-122
+
+
+ 24
+
+
+ The αu's for a=0 as an array
+ of ZTauElements.
+
+
+ The αu's for a=0 as an array
+ of TNAFs.
+
+
+ The αu's for a=1 as an array
+ of ZTauElements.
+
+
+ The αu's for a=1 as an array
+ of TNAFs.
+
+
+ Computes the norm of an element λ of
+ Z[τ].
+ @param mu The parameter μ of the elliptic curve.
+ @param lambda The element λ of
+ Z[τ].
+ @return The norm of λ.
+
+
+ Computes the norm of an element λ of
+ R[τ], where λ = u + vτ
+ and u and u are real numbers (elements of
+ R).
+ @param mu The parameter μ of the elliptic curve.
+ @param u The real part of the element λ of
+ R[τ].
+ @param v The τ-adic part of the element
+ λ of R[τ].
+ @return The norm of λ.
+
+
+ Rounds an element λ of R[τ]
+ to an element of Z[τ], such that their difference
+ has minimal norm. λ is given as
+ λ = λ0 + λ1τ.
+ @param lambda0 The component λ0.
+ @param lambda1 The component λ1.
+ @param mu The parameter μ of the elliptic curve. Must
+ equal 1 or -1.
+ @return The rounded element of Z[τ].
+ @throws ArgumentException if lambda0 and
+ lambda1 do not have same scale.
+
+
+ Approximate division by n. For an integer
+ k, the value λ = s k / n is
+ computed to c bits of accuracy.
+ @param k The parameter k.
+ @param s The curve parameter s0 or
+ s1.
+ @param vm The Lucas Sequence element Vm.
+ @param a The parameter a of the elliptic curve.
+ @param m The bit length of the finite field
+ Fm.
+ @param c The number of bits of accuracy, i.e. the scale of the returned
+ SimpleBigDecimal.
+ @return The value λ = s k / n computed to
+ c bits of accuracy.
+
+
+ Computes the τ-adic NAF (non-adjacent form) of an
+ element λ of Z[τ].
+ @param mu The parameter μ of the elliptic curve.
+ @param lambda The element λ of
+ Z[τ].
+ @return The τ-adic NAF of λ.
+
+
+ Applies the operation τ() to an
+ F2mPoint.
+ @param p The F2mPoint to which τ() is applied.
+ @return τ(p)
+
+
+ Returns the parameter μ of the elliptic curve.
+ @param curve The elliptic curve from which to obtain μ.
+ The curve must be a Koblitz curve, i.e. a Equals
+ 0 or 1 and b Equals
+ 1.
+ @return μ of the elliptic curve.
+ @throws ArgumentException if the given ECCurve is not a Koblitz
+ curve.
+
+
+ Calculates the Lucas Sequence elements Uk-1 and
+ Uk or Vk-1 and
+ Vk.
+ @param mu The parameter μ of the elliptic curve.
+ @param k The index of the second element of the Lucas Sequence to be
+ returned.
+ @param doV If set to true, computes Vk-1 and
+ Vk, otherwise Uk-1 and
+ Uk.
+ @return An array with 2 elements, containing Uk-1
+ and Uk or Vk-1
+ and Vk.
+
+
+ Computes the auxiliary value tw. If the width is
+ 4, then for mu = 1, tw = 6 and for
+ mu = -1, tw = 10
+ @param mu The parameter μ of the elliptic curve.
+ @param w The window width of the WTNAF.
+ @return the auxiliary value tw
+
+
+ Computes the auxiliary values s0 and
+ s1 used for partial modular reduction.
+ @param curve The elliptic curve for which to compute
+ s0 and s1.
+ @throws ArgumentException if curve is not a
+ Koblitz curve (Anomalous Binary Curve, ABC).
+
+
+ Partial modular reduction modulo
+ (τm - 1)/(τ - 1).
+ @param k The integer to be reduced.
+ @param m The bitlength of the underlying finite field.
+ @param a The parameter a of the elliptic curve.
+ @param s The auxiliary values s0 and
+ s1.
+ @param mu The parameter μ of the elliptic curve.
+ @param c The precision (number of bits of accuracy) of the partial
+ modular reduction.
+ @return ρ := k partmod (τm - 1)/(τ - 1)
+
+
+ Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint}
+ by a BigInteger using the reduced τ-adic
+ NAF (RTNAF) method.
+ @param p The F2mPoint to Multiply.
+ @param k The BigInteger by which to Multiply p.
+ @return k * p
+
+
+ Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint}
+ by an element λ of Z[τ]
+ using the τ-adic NAF (TNAF) method.
+ @param p The F2mPoint to Multiply.
+ @param lambda The element λ of
+ Z[τ].
+ @return λ * p
+
+
+ Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint}
+ by an element λ of Z[τ]
+ using the τ-adic NAF (TNAF) method, given the TNAF
+ of λ.
+ @param p The F2mPoint to Multiply.
+ @param u The the TNAF of λ..
+ @return λ * p
+
+
+ Computes the [τ]-adic window NAF of an element
+ λ of Z[τ].
+ @param mu The parameter μ of the elliptic curve.
+ @param lambda The element λ of
+ Z[τ] of which to compute the
+ [τ]-adic NAF.
+ @param width The window width of the resulting WNAF.
+ @param pow2w 2width.
+ @param tw The auxiliary value tw.
+ @param alpha The αu's for the window width.
+ @return The [τ]-adic window NAF of
+ λ.
+
+
+ Does the precomputation for WTNAF multiplication.
+ @param p The ECPoint for which to do the precomputation.
+ @param a The parameter a of the elliptic curve.
+ @return The precomputation array for p.
+
+
+ Class representing an element of Z[τ]. Let
+ λ be an element of Z[τ]. Then
+ λ is given as λ = u + vτ. The
+ components u and v may be used directly, there
+ are no accessor methods.
+ Immutable class.
+
+
+ The "real" part of λ.
+
+
+ The "τ-adic" part of λ.
+
+
+ Constructor for an element λ of
+ Z[τ].
+ @param u The "real" part of λ.
+ @param v The "τ-adic" part of
+ λ.
+
+
+ Base class for an elliptic curve.
+
+
+ Decode a point on this curve from its ASN.1 encoding. The different
+ encodings are taken account of, including point compression for
+ Fp (X9.62 s 4.2.1 pg 17).
+ @return The decoded point.
+
+
+ Elliptic curve over Fp
+
+
+ Elliptic curves over F2m. The Weierstrass equation is given by
+ y2 + xy = x3 + ax2 + b.
+
+
+ The exponent m of F2m.
+
+
+ TPB: The integer k where xm +
+ xk + 1 represents the reduction polynomial
+ f(z).
+ PPB: The integer k1 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+
+
+ TPB: Always set to 0
+ PPB: The integer k2 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+
+
+ TPB: Always set to 0
+ PPB: The integer k3 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+
+
+ The order of the base point of the curve.
+
+
+ The cofactor of the curve.
+
+
+ The point at infinity on this curve.
+
+
+ The parameter μ of the elliptic curve if this is
+ a Koblitz curve.
+
+
+ The auxiliary values s0 and
+ s1 used for partial modular reduction for
+ Koblitz curves.
+
+
+ Constructor for Trinomial Polynomial Basis (TPB).
+ @param m The exponent m of
+ F2m.
+ @param k The integer k where xm +
+ xk + 1 represents the reduction
+ polynomial f(z).
+ @param a The coefficient a in the Weierstrass equation
+ for non-supersingular elliptic curves over
+ F2m.
+ @param b The coefficient b in the Weierstrass equation
+ for non-supersingular elliptic curves over
+ F2m.
+
+
+ Constructor for Trinomial Polynomial Basis (TPB).
+ @param m The exponent m of
+ F2m.
+ @param k The integer k where xm +
+ xk + 1 represents the reduction
+ polynomial f(z).
+ @param a The coefficient a in the Weierstrass equation
+ for non-supersingular elliptic curves over
+ F2m.
+ @param b The coefficient b in the Weierstrass equation
+ for non-supersingular elliptic curves over
+ F2m.
+ @param n The order of the main subgroup of the elliptic curve.
+ @param h The cofactor of the elliptic curve, i.e.
+ #Ea(F2m) = h * n.
+
+
+ Constructor for Pentanomial Polynomial Basis (PPB).
+ @param m The exponent m of
+ F2m.
+ @param k1 The integer k1 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param k2 The integer k2 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param k3 The integer k3 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param a The coefficient a in the Weierstrass equation
+ for non-supersingular elliptic curves over
+ F2m.
+ @param b The coefficient b in the Weierstrass equation
+ for non-supersingular elliptic curves over
+ F2m.
+
+
+ Constructor for Pentanomial Polynomial Basis (PPB).
+ @param m The exponent m of
+ F2m.
+ @param k1 The integer k1 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param k2 The integer k2 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param k3 The integer k3 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param a The coefficient a in the Weierstrass equation
+ for non-supersingular elliptic curves over
+ F2m.
+ @param b The coefficient b in the Weierstrass equation
+ for non-supersingular elliptic curves over
+ F2m.
+ @param n The order of the main subgroup of the elliptic curve.
+ @param h The cofactor of the elliptic curve, i.e.
+ #Ea(F2m) = h * n.
+
+
+ Returns the parameter μ of the elliptic curve.
+ @return μ of the elliptic curve.
+ @throws ArgumentException if the given ECCurve is not a
+ Koblitz curve.
+
+
+ @return the auxiliary values s0 and
+ s1 used for partial modular reduction for
+ Koblitz curves.
+
+
+ Solves a quadratic equation z2 + z = beta(X9.62
+ D.1.6) The other solution is z + 1.
+
+ @param beta
+ The value to solve the qradratic equation for.
+ @return the solution for z2 + z = beta or
+ null if no solution exists.
+
+
+ Return true if curve uses a Trinomial basis.
+
+ @return true if curve Trinomial, false otherwise.
+
+
+ Returns true if this is a Koblitz curve (ABC curve).
+ @return true if this is a Koblitz curve (ABC curve), false otherwise
+
+
+ return a sqrt root - the routine verifies that the calculation
+ returns the right value - if none exists it returns null.
+
+
+ return the field name for this field.
+
+ @return the string "Fp".
+
+
+ Class representing the Elements of the finite field
+ F2m in polynomial basis (PB)
+ representation. Both trinomial (Tpb) and pentanomial (Ppb) polynomial
+ basis representations are supported. Gaussian normal basis (GNB)
+ representation is not supported.
+
+
+ Indicates gaussian normal basis representation (GNB). Number chosen
+ according to X9.62. GNB is not implemented at present.
+
+
+ Indicates trinomial basis representation (Tpb). Number chosen
+ according to X9.62.
+
+
+ Indicates pentanomial basis representation (Ppb). Number chosen
+ according to X9.62.
+
+
+ Tpb or Ppb.
+
+
+ The exponent m of F2m.
+
+
+ Tpb: The integer k where xm +
+ xk + 1 represents the reduction polynomial
+ f(z).
+ Ppb: The integer k1 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+
+
+ Tpb: Always set to 0
+ Ppb: The integer k2 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+
+
+ Tpb: Always set to 0
+ Ppb: The integer k3 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+
+
+ The IntArray holding the bits.
+
+
+ The number of ints required to hold m bits.
+
+
+ Constructor for Ppb.
+ @param m The exponent m of
+ F2m.
+ @param k1 The integer k1 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param k2 The integer k2 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param k3 The integer k3 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+ @param x The BigInteger representing the value of the field element.
+
+
+ Constructor for Tpb.
+ @param m The exponent m of
+ F2m.
+ @param k The integer k where xm +
+ xk + 1 represents the reduction
+ polynomial f(z).
+ @param x The BigInteger representing the value of the field element.
+
+
+ Checks, if the ECFieldElements a and b
+ are elements of the same field F2m
+ (having the same representation).
+ @param a field element.
+ @param b field element to be compared.
+ @throws ArgumentException if a and b
+ are not elements of the same field
+ F2m (having the same
+ representation).
+
+
+ @return the representation of the field
+ F2m, either of
+ {@link F2mFieldElement.Tpb} (trinomial
+ basis representation) or
+ {@link F2mFieldElement.Ppb} (pentanomial
+ basis representation).
+
+
+ @return the degree m of the reduction polynomial
+ f(z).
+
+
+ @return Tpb: The integer k where xm +
+ xk + 1 represents the reduction polynomial
+ f(z).
+ Ppb: The integer k1 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+
+
+ @return Tpb: Always returns 0
+ Ppb: The integer k2 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+
+
+ @return Tpb: Always set to 0
+ Ppb: The integer k3 where xm +
+ xk3 + xk2 + xk1 + 1
+ represents the reduction polynomial f(z).
+
+
+ base class for points on elliptic curves.
+
+
+ Sets the PreCompInfo. Used by ECMultipliers
+ to save the precomputation for this ECPoint to store the
+ precomputation result for use by subsequent multiplication.
+ @param preCompInfo The values precomputed by the
+ ECMultiplier.
+
+
+ Sets the appropriate ECMultiplier, unless already set.
+
+
+ return the field element encoded with point compression. (S 4.3.6)
+
+
+ Multiplies this ECPoint by the given number.
+ @param k The multiplicator.
+ @return k * this.
+
+
+ Elliptic curve points over Fp
+
+
+ Create a point which encodes with point compression.
+
+ @param curve the curve to use
+ @param x affine x co-ordinate
+ @param y affine y co-ordinate
+
+
+ Create a point that encodes with or without point compresion.
+
+ @param curve the curve to use
+ @param x affine x co-ordinate
+ @param y affine y co-ordinate
+ @param withCompression if true encode with point compression
+
+
+ Sets the default ECMultiplier, unless already set.
+
+
+ Elliptic curve points over F2m
+
+
+ @param curve base curve
+ @param x x point
+ @param y y point
+
+
+ @param curve base curve
+ @param x x point
+ @param y y point
+ @param withCompression true if encode with point compression.
+
+
+ Constructor for point at infinity
+
+
+ Check, if two ECPoints can be added or subtracted.
+ @param a The first ECPoint to check.
+ @param b The second ECPoint to check.
+ @throws IllegalArgumentException if a and b
+ cannot be added.
+
+
+ Adds another ECPoints.F2m to this without
+ checking if both points are on the same curve. Used by multiplication
+ algorithms, because there all points are a multiple of the same point
+ and hence the checks can be omitted.
+ @param b The other ECPoints.F2m to add to
+ this.
+ @return this + b
+
+
+ Subtracts another ECPoints.F2m from this
+ without checking if both points are on the same curve. Used by
+ multiplication algorithms, because there all points are a multiple
+ of the same point and hence the checks can be omitted.
+ @param b The other ECPoints.F2m to subtract from
+ this.
+ @return this - b
+
+
+ Sets the appropriate ECMultiplier, unless already set.
+
+
+ Interface for classes encapsulating a point multiplication algorithm
+ for ECPoints.
+
+
+ Multiplies the ECPoint p by k, i.e.
+ p is added k times to itself.
+ @param p The ECPoint to be multiplied.
+ @param k The factor by which p i multiplied.
+ @return p multiplied by k.
+
+
+ Class implementing the NAF (Non-Adjacent Form) multiplication algorithm.
+
+
+ D.3.2 pg 101
+ @see org.bouncycastle.math.ec.multiplier.ECMultiplier#multiply(org.bouncycastle.math.ec.ECPoint, java.math.BigInteger)
+
+
+ Interface for classes storing precomputation data for multiplication
+ algorithms. Used as a Memento (see GOF patterns) for
+ WNafMultiplier.
+
+
+ Simple shift-and-add multiplication. Serves as reference implementation
+ to verify (possibly faster) implementations in
+ {@link org.bouncycastle.math.ec.ECPoint ECPoint}.
+
+ @param p The point to multiply.
+ @param k The factor by which to multiply.
+ @return The result of the point multiplication k * p.
+
+
+ Class implementing the WNAF (Window Non-Adjacent Form) multiplication
+ algorithm.
+
+
+ Computes the Window NAF (non-adjacent Form) of an integer.
+ @param width The width w of the Window NAF. The width is
+ defined as the minimal number w, such that for any
+ w consecutive digits in the resulting representation, at
+ most one is non-zero.
+ @param k The integer of which the Window NAF is computed.
+ @return The Window NAF of the given width, such that the following holds:
+ k = −i=0l-1 ki2i
+ , where the ki denote the elements of the
+ returned sbyte[].
+
+
+ Multiplies this by an integer k using the
+ Window NAF method.
+ @param k The integer by which this is multiplied.
+ @return A new ECPoint which equals this
+ multiplied by k.
+
+
+ Class holding precomputation data for the WNAF (Window Non-Adjacent Form)
+ algorithm.
+
+
+ Array holding the precomputed ECPoints used for the Window
+ NAF multiplication in
+ {@link org.bouncycastle.math.ec.multiplier.WNafMultiplier.multiply()
+ WNafMultiplier.multiply()}.
+
+
+ Holds an ECPoint representing twice(this). Used for the
+ Window NAF multiplication in
+ {@link org.bouncycastle.math.ec.multiplier.WNafMultiplier.multiply()
+ WNafMultiplier.multiply()}.
+
+
+ Class implementing the WTNAF (Window
+ τ-adic Non-Adjacent Form) algorithm.
+
+
+ Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint}
+ by k using the reduced τ-adic NAF (RTNAF)
+ method.
+ @param p The F2mPoint to multiply.
+ @param k The integer by which to multiply k.
+ @return p multiplied by k.
+
+
+ Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint}
+ by an element λ of Z[τ] using
+ the τ-adic NAF (TNAF) method.
+ @param p The F2mPoint to multiply.
+ @param lambda The element λ of
+ Z[τ] of which to compute the
+ [τ]-adic NAF.
+ @return p multiplied by λ.
+
+
+ Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint}
+ by an element λ of Z[τ]
+ using the window τ-adic NAF (TNAF) method, given the
+ WTNAF of λ.
+ @param p The F2mPoint to multiply.
+ @param u The the WTNAF of λ..
+ @return λ * p
+
+
+ Class holding precomputation data for the WTNAF (Window
+ τ-adic Non-Adjacent Form) algorithm.
+
+
+ Array holding the precomputed F2mPoints used for the
+ WTNAF multiplication in
+ {@link org.bouncycastle.math.ec.multiplier.WTauNafMultiplier.multiply()
+ WTauNafMultiplier.multiply()}.
+
+
+ Constructor for WTauNafPreCompInfo
+ @param preComp Array holding the precomputed F2mPoints
+ used for the WTNAF multiplication in
+ {@link org.bouncycastle.math.ec.multiplier.WTauNafMultiplier.multiply()
+ WTauNafMultiplier.multiply()}.
+
+
+ @return the array holding the precomputed F2mPoints
+ used for the WTNAF multiplication in
+ {@link org.bouncycastle.math.ec.multiplier.WTauNafMultiplier.multiply()
+ WTauNafMultiplier.multiply()}.
+
+
+
+
+ BasicOcspResponse ::= SEQUENCE {
+ tbsResponseData ResponseData,
+ signatureAlgorithm AlgorithmIdentifier,
+ signature BIT STRING,
+ certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL
+ }
+
+
+
+
+
+ Get all critical extension values, by oid
+
+ IDictionary with string (OID) keys and Asn1OctetString values
+
+
+
+ Get all non-critical extension values, by oid
+
+ IDictionary with string (OID) keys and Asn1OctetString values
+
+
+
+ Get non critical extensions.
+
+ A set of non critical extension oids.
+
+
+
+ Get any critical extensions.
+
+ A sorted list of critical entension.
+
+
+
+ Get the value of a given extension.
+
+ The object ID of the extension.
+ An Asn1OctetString object if that extension is found or null if not.
+
+
+ The DER encoding of the tbsResponseData field.
+ In the event of an encoding error.
+
+
+ The certificates, if any, associated with the response.
+ In the event of an encoding error.
+
+
+
+ Verify the signature against the tbsResponseData object we contain.
+
+
+
+ The ASN.1 encoded representation of this object.
+
+
+ Generator for basic OCSP response objects.
+
+
+ basic constructor
+
+
+ construct with the responderID to be the SHA-1 keyHash of the passed in public key.
+
+
+ Add a response for a particular Certificate ID.
+
+ @param certID certificate ID details
+ @param certStatus status of the certificate - null if okay
+
+
+ Add a response for a particular Certificate ID.
+
+ @param certID certificate ID details
+ @param certStatus status of the certificate - null if okay
+ @param singleExtensions optional extensions
+
+
+ Add a response for a particular Certificate ID.
+
+ @param certID certificate ID details
+ @param nextUpdate date when next update should be requested
+ @param certStatus status of the certificate - null if okay
+ @param singleExtensions optional extensions
+
+
+ Add a response for a particular Certificate ID.
+
+ @param certID certificate ID details
+ @param thisUpdate date this response was valid on
+ @param nextUpdate date when next update should be requested
+ @param certStatus status of the certificate - null if okay
+ @param singleExtensions optional extensions
+
+
+ Set the extensions for the response.
+
+ @param responseExtensions the extension object to carry.
+
+
+ Return an IEnumerable of the signature names supported by the generator.
+
+ @return an IEnumerable containing recognised names.
+
+
+ create from an issuer certificate and the serial number of the
+ certificate it signed.
+ @exception OcspException if any problems occur creating the id fields.
+
+
+ Create a new CertificateID for a new serial number derived from a previous one
+ calculated for the same CA certificate.
+
+ @param original the previously calculated CertificateID for the CA.
+ @param newSerialNumber the serial number for the new certificate of interest.
+
+ @return a new CertificateID for newSerialNumber
+
+
+ return the serial number for the certificate associated
+ with this request.
+
+
+
+
+
+ Return the DER encoding of the tbsRequest field.
+ @return DER encoding of tbsRequest
+ @throws OcspException in the event of an encoding error.
+
+
+ If the request is signed return a possibly empty CertStore containing the certificates in the
+ request. If the request is not signed the method returns null.
+
+ @return null if not signed, a CertStore otherwise
+ @throws OcspException
+
+
+ Verify the signature against the TBSRequest object we contain.
+
+
+ return the ASN.1 encoded representation of this object.
+
+
+ return the object identifier representing the signature algorithm
+
+
+ Return whether or not this request is signed.
+
+ @return true if signed false otherwise.
+
+
+ Add a request for the given CertificateID.
+
+ @param certId certificate ID of interest
+
+
+ Add a request with extensions
+
+ @param certId certificate ID of interest
+ @param singleRequestExtensions the extensions to attach to the request
+
+
+ Set the requestor name to the passed in X509Principal
+
+ @param requestorName a X509Principal representing the requestor name.
+
+
+ Generate an unsigned request
+
+ @return the OcspReq
+ @throws OcspException
+
+
+ Return an IEnumerable of the signature names supported by the generator.
+
+ @return an IEnumerable containing recognised names.
+
+
+ return the ASN.1 encoded representation of this object.
+
+
+ base generator for an OCSP response - at the moment this only supports the
+ generation of responses containing BasicOCSP responses.
+
+
+ note 4 is not used.
+
+
+ Carrier for a ResponderID.
+
+
+ wrapper for the RevokedInfo object
+
+
+ return the revocation reason. Note: this field is optional, test for it
+ with hasRevocationReason() first.
+ @exception InvalidOperationException if a reason is asked for and none is avaliable
+
+
+ Return the status object for the response - null indicates good.
+
+ @return the status object for the response, null if it is good.
+
+
+ return the NextUpdate value - note: this is an optional field so may
+ be returned as null.
+
+ @return nextUpdate, or null if not present.
+
+
+ wrapper for the UnknownInfo object
+
+
+ Compressed data objects
+
+
+ Get the raw input stream contained in the object.
+
+
+ Return an uncompressed input stream which allows reading of the compressed data.
+
+
+ The algorithm used for compression
+
+
+ Class for producing compressed data packets.
+
+
+
+
+ Return an output stream which will save the data being written to
+ the compressed object.
+
+
+ The stream created can be closed off by either calling Close()
+ on the stream or Close() on the generator. Closing the returned
+ stream does not close off the Stream parameter outStr.
+
+
+ Stream to be used for output.
+ A Stream for output of the compressed data.
+
+
+
+
+
+
+
+ Return an output stream which will compress the data as it is written to it.
+ The stream will be written out in chunks according to the size of the passed in buffer.
+
+
+ The stream created can be closed off by either calling Close()
+ on the stream or Close() on the generator. Closing the returned
+ stream does not close off the Stream parameter outStr.
+
+
+ Note: if the buffer is not a power of 2 in length only the largest power of 2
+ bytes worth of the buffer will be used.
+
+
+ Note: using this may break compatibility with RFC 1991 compliant tools.
+ Only recent OpenPGP implementations are capable of accepting these streams.
+
+
+ Stream to be used for output.
+ The buffer to use.
+ A Stream for output of the compressed data.
+
+
+
+
+
+
+ Close the compressed object.summary>
+
+
+
+ Thrown if the IV at the start of a data stream indicates the wrong key is being used.
+
+
+
+ Generic exception class for PGP encoding/decoding problems.
+
+
+ Return the raw input stream for the data stream.
+
+
+ Return true if the message is integrity protected.
+ True, if there is a modification detection code namespace associated
+ with this stream.
+
+
+ Note: This can only be called after the message has been read.
+ True, if the message verifies, false otherwise
+
+
+ Generator for encrypted objects.
+
+
+ Existing SecureRandom constructor.
+ The symmetric algorithm to use.
+ Source of randomness.
+
+
+ Creates a cipher stream which will have an integrity packet associated with it.
+
+
+ Base constructor.
+ The symmetric algorithm to use.
+ Source of randomness.
+ PGP 2.6.x compatibility required.
+
+
+
+ Add a PBE encryption method to the encrypted object using the default algorithm (S2K_SHA1).
+
+
+
+ Add a PBE encryption method to the encrypted object.
+
+
+ Add a public key encrypted session key to the encrypted object.
+
+
+
+
+ If buffer is non null stream assumed to be partial, otherwise the length will be used
+ to output a fixed length packet.
+
+
+ The stream created can be closed off by either calling Close()
+ on the stream or Close() on the generator. Closing the returned
+ stream does not close off the Stream parameter outStr.
+
+
+
+
+
+
+ Return an output stream which will encrypt the data as it is written to it.
+
+
+ The stream created can be closed off by either calling Close()
+ on the stream or Close() on the generator. Closing the returned
+ stream does not close off the Stream parameter outStr.
+
+
+
+
+
+
+ Return an output stream which will encrypt the data as it is written to it.
+ The stream will be written out in chunks according to the size of the passed in buffer.
+
+
+ The stream created can be closed off by either calling Close()
+ on the stream or Close() on the generator. Closing the returned
+ stream does not close off the Stream parameter outStr.
+
+
+ Note: if the buffer is not a power of 2 in length only the largest power of 2
+ bytes worth of the buffer will be used.
+
+
+
+
+
+
+ Close off the encrypted object - this is equivalent to calling Close() on the stream
+ returned by the Open() method.
+
+
+ Note: This does not close the underlying output stream, only the stream on top of
+ it created by the Open() method.
+
+
+
+
+ A holder for a list of PGP encryption method packets.
+
+
+ Key flag values for the KeyFlags subpacket.
+
+
+
+ General class to handle JCA key pairs and convert them into OpenPGP ones.
+
+ A word for the unwary, the KeyId for an OpenPGP public key is calculated from
+ a hash that includes the time of creation, if you pass a different date to the
+ constructor below with the same public private key pair the KeyIs will not be the
+ same as for previous generations of the key, so ideally you only want to do
+ this once.
+
+
+
+
+ Create a key pair from a PgpPrivateKey and a PgpPublicKey.
+ The public key.
+ The private key.
+
+
+ The keyId associated with this key pair.
+
+
+
+ Generator for a PGP master and subkey ring.
+ This class will generate both the secret and public key rings
+
+
+
+
+ Create a new key ring generator using old style checksumming. It is recommended to use
+ SHA1 checksumming where possible.
+
+ The certification level for keys on this ring.
+ The master key pair.
+ The id to be associated with the ring.
+ The algorithm to be used to protect secret keys.
+ The passPhrase to be used to protect secret keys.
+ Packets to be included in the certification hash.
+ Packets to be attached unhashed to the certification.
+ input secured random.
+
+
+
+ Create a new key ring generator.
+
+ The certification level for keys on this ring.
+ The master key pair.
+ The id to be associated with the ring.
+ The algorithm to be used to protect secret keys.
+ The passPhrase to be used to protect secret keys.
+ Checksum the secret keys with SHA1 rather than the older 16 bit checksum.
+ Packets to be included in the certification hash.
+ Packets to be attached unhashed to the certification.
+ input secured random.
+
+
+ Add a subkey to the key ring to be generated with default certification.
+
+
+
+ Add a subkey with specific hashed and unhashed packets associated with it and
+ default certification.
+
+ Public/private key pair.
+ Hashed packet values to be included in certification.
+ Unhashed packets values to be included in certification.
+
+
+
+ Return the secret key ring.
+
+
+ Return the public key ring that corresponds to the secret key ring.
+
+
+
+ Thrown if the key checksum is invalid.
+
+
+
+ Class for processing literal data objects.
+
+
+ The special name indicating a "for your eyes only" packet.
+
+
+ Return the file name as an unintrepreted byte array.
+
+
+ The raw input stream for the data stream.
+
+
+ The input stream representing the data stream.
+
+
+ The format of the data stream - Binary or Text
+
+
+ The file name that's associated with the data stream.
+
+
+ The modification time for the file.
+
+
+ Class for producing literal data packets.
+
+
+ The special name indicating a "for your eyes only" packet.
+
+
+
+ Generates literal data objects in the old format.
+ This is important if you need compatibility with PGP 2.6.x.
+
+ If true, uses old format.
+
+
+
+
+ Open a literal data packet, returning a stream to store the data inside the packet.
+
+
+ The stream created can be closed off by either calling Close()
+ on the stream or Close() on the generator. Closing the returned
+ stream does not close off the Stream parameter outStr.
+
+
+ The stream we want the packet in.
+ The format we are using.
+ The name of the 'file'.
+ The length of the data we will write.
+ The time of last modification we want stored.
+
+
+
+
+ Open a literal data packet, returning a stream to store the data inside the packet,
+ as an indefinite length stream. The stream is written out as a series of partial
+ packets with a chunk size determined by the size of the passed in buffer.
+
+
+ The stream created can be closed off by either calling Close()
+ on the stream or Close() on the generator. Closing the returned
+ stream does not close off the Stream parameter outStr.
+
+
+ Note: if the buffer is not a power of 2 in length only the largest power of 2
+ bytes worth of the buffer will be used.
+
+ The stream we want the packet in.
+ The format we are using.
+ The name of the 'file'.
+ The time of last modification we want stored.
+ The buffer to use for collecting data to put into chunks.
+
+
+
+ Close the literal data packet - this is equivalent to calling Close()
+ on the stream returned by the Open() method.
+
+
+
+
+ A PGP marker packet - in general these should be ignored other than where
+ the idea is to preserve the original input stream.
+
+
+
+
+ General class for reading a PGP object stream.
+
+ Note: if this class finds a PgpPublicKey or a PgpSecretKey it
+ will create a PgpPublicKeyRing, or a PgpSecretKeyRing for each
+ key found. If all you are trying to do is read a key ring file use
+ either PgpPublicKeyRingBundle or PgpSecretKeyRingBundle.
+
+
+
+ Return the next object in the stream, or null if the end is reached.
+ On a parse error
+
+
+
+ Return all available objects in a list.
+
+ An IList containing all objects from this factory, in order.
+
+
+ A one pass signature object.
+
+
+ Initialise the signature object for verification.
+
+
+ Verify the calculated signature against the passed in PgpSignature.
+
+
+ Holder for a list of PgpOnePassSignature objects.
+
+
+ A password based encryption object.
+
+
+ Return the raw input stream for the data stream.
+
+
+ Return the decrypted input stream, using the passed in passphrase.
+
+
+ General class to contain a private key for use with other OpenPGP objects.
+
+
+
+ Create a PgpPrivateKey from a regular private key and the ID of its
+ associated public key.
+
+ Private key to use.
+ ID of the corresponding public key.
+
+
+ The keyId associated with the contained private key.
+
+
+ The contained private key.
+
+
+ General class to handle a PGP public key object.
+
+
+
+ Create a PgpPublicKey from the passed in lightweight one.
+
+
+ Note: the time passed in affects the value of the key's keyId, so you probably only want
+ to do this once for a lightweight key, or make sure you keep track of the time you used.
+
+ Asymmetric algorithm type representing the public key.
+ Actual public key to associate.
+ Date of creation.
+ If pubKey is not public.
+ On key creation problem.
+
+
+ Constructor for a sub-key.
+
+
+ Copy constructor.
+ The public key to copy.
+
+
+ Return the trust data associated with the public key, if present.
+ A byte array with trust data, null otherwise.
+
+
+ The number of valid seconds from creation time - zero means no expiry.
+
+
+ The fingerprint of the key
+
+
+ The public key contained in the object.
+ A lightweight public key.
+ If the key algorithm is not recognised.
+
+
+ Allows enumeration of any user IDs associated with the key.
+ An IEnumerable of string objects.
+
+
+ Allows enumeration of any user attribute vectors associated with the key.
+ An IEnumerable of PgpUserAttributeSubpacketVector objects.
+
+
+ Allows enumeration of any signatures associated with the passed in id.
+ The ID to be matched.
+ An IEnumerable of PgpSignature objects.
+
+
+ Allows enumeration of signatures associated with the passed in user attributes.
+ The vector of user attributes to be matched.
+ An IEnumerable of PgpSignature objects.
+
+
+ Allows enumeration of signatures of the passed in type that are on this key.
+ The type of the signature to be returned.
+ An IEnumerable of PgpSignature objects.
+
+
+ Allows enumeration of all signatures/certifications associated with this key.
+ An IEnumerable with all signatures/certifications.
+
+
+ Check whether this (sub)key has a revocation signature on it.
+ True, if this (sub)key has been revoked.
+
+
+ Add a certification for an id to the given public key.
+ The key the certification is to be added to.
+ The ID the certification is associated with.
+ The new certification.
+ The re-certified key.
+
+
+ Add a certification for the given UserAttributeSubpackets to the given public key.
+ The key the certification is to be added to.
+ The attributes the certification is associated with.
+ The new certification.
+ The re-certified key.
+
+
+
+ Remove any certifications associated with a user attribute subpacket on a key.
+
+ The key the certifications are to be removed from.
+ The attributes to be removed.
+
+ The re-certified key, or null if the user attribute subpacket was not found on the key.
+
+
+
+ Remove any certifications associated with a given ID on a key.
+ The key the certifications are to be removed from.
+ The ID that is to be removed.
+ The re-certified key, or null if the ID was not found on the key.
+
+
+ Remove a certification associated with a given ID on a key.
+ The key the certifications are to be removed from.
+ The ID that the certfication is to be removed from.
+ The certfication to be removed.
+ The re-certified key, or null if the certification was not found.
+
+
+ Remove a certification associated with a given user attributes on a key.
+ The key the certifications are to be removed from.
+ The user attributes that the certfication is to be removed from.
+ The certification to be removed.
+ The re-certified key, or null if the certification was not found.
+
+
+ Add a revocation or some other key certification to a key.
+ The key the revocation is to be added to.
+ The key signature to be added.
+ The new changed public key object.
+
+
+ Remove a certification from the key.
+ The key the certifications are to be removed from.
+ The certfication to be removed.
+ The modified key, null if the certification was not found.
+
+
+ The version of this key.
+
+
+ The creation time of this key.
+
+
+ The number of valid days from creation time - zero means no expiry.
+
+
+ The keyId associated with the public key.
+
+
+
+ Check if this key has an algorithm type that makes it suitable to use for encryption.
+
+
+ Note: with version 4 keys KeyFlags subpackets should also be considered when present for
+ determining the preferred use of the key.
+
+
+ true if this key algorithm is suitable for encryption.
+
+
+
+ True, if this is a master key.
+
+
+ The algorithm code associated with the public key.
+
+
+ The strength of the key in bits.
+
+
+ A public key encrypted data object.
+
+
+
+ Return the algorithm code for the symmetric algorithm used to encrypt the data.
+
+
+
+ Return the decrypted data stream for the packet.
+
+
+ The key ID for the key used to encrypt the data.
+
+
+
+ Class to hold a single master public key and its subkeys.
+
+ Often PGP keyring files consist of multiple master keys, if you are trying to process
+ or construct one of these you should use the PgpPublicKeyRingBundle class.
+
+
+
+
+ Return the first public key in the ring.
+
+
+ Return the public key referred to by the passed in key ID if it is present.
+
+
+ Allows enumeration of all the public keys.
+ An IEnumerable of PgpPublicKey objects.
+
+
+
+ Returns a new key ring with the public key passed in either added or
+ replacing an existing one.
+
+ The public key ring to be modified.
+ The public key to be inserted.
+ A new PgpPublicKeyRing
+
+
+ Returns a new key ring with the public key passed in removed from the key ring.
+ The public key ring to be modified.
+ The public key to be removed.
+ A new PgpPublicKeyRing, or null if pubKey is not found.
+
+
+
+ Often a PGP key ring file is made up of a succession of master/sub-key key rings.
+ If you want to read an entire public key file in one hit this is the class for you.
+
+
+
+ Build a PgpPublicKeyRingBundle from the passed in input stream.
+ Input stream containing data.
+ If a problem parsing the stream occurs.
+ If an object is encountered which isn't a PgpPublicKeyRing.
+
+
+ Allow enumeration of the public key rings making up this collection.
+
+
+ Allow enumeration of the key rings associated with the passed in userId.
+ The user ID to be matched.
+ An IEnumerable of key rings which matched (possibly none).
+
+
+ Allow enumeration of the key rings associated with the passed in userId.
+ The user ID to be matched.
+ If true, userId need only be a substring of an actual ID string to match.
+ An IEnumerable of key rings which matched (possibly none).
+
+
+ Allow enumeration of the key rings associated with the passed in userId.
+ The user ID to be matched.
+ If true, userId need only be a substring of an actual ID string to match.
+ If true, case is ignored in user ID comparisons.
+ An IEnumerable of key rings which matched (possibly none).
+
+
+ Return the PGP public key associated with the given key id.
+ The ID of the public key to return.
+
+
+ Return the public key ring which contains the key referred to by keyId
+ key ID to match against
+
+
+
+ Return true if a key matching the passed in key ID is present, false otherwise.
+
+ key ID to look for.
+
+
+
+ Return a new bundle containing the contents of the passed in bundle and
+ the passed in public key ring.
+
+ The PgpPublicKeyRingBundle the key ring is to be added to.
+ The key ring to be added.
+ A new PgpPublicKeyRingBundle merging the current one with the passed in key ring.
+ If the keyId for the passed in key ring is already present.
+
+
+
+ Return a new bundle containing the contents of the passed in bundle with
+ the passed in public key ring removed.
+
+ The PgpPublicKeyRingBundle the key ring is to be removed from.
+ The key ring to be removed.
+ A new PgpPublicKeyRingBundle not containing the passed in key ring.
+ If the keyId for the passed in key ring is not present.
+
+
+ Return the number of key rings in this collection.
+
+
+ General class to handle a PGP secret key object.
+
+
+ Extract a PgpPrivateKey from this secret key's encrypted contents.
+
+
+
+ Return a copy of the passed in secret key, encrypted using a new password
+ and the passed in algorithm.
+
+ The PgpSecretKey to be copied.
+ The current password for the key.
+ The new password for the key.
+ The algorithm to be used for the encryption.
+ Source of randomness.
+
+
+ Replace the passed the public key on the passed in secret key.
+ Secret key to change.
+ New public key.
+ A new secret key.
+ If KeyId's do not match.
+
+
+
+ Check if this key has an algorithm type that makes it suitable to use for signing.
+
+
+ Note: with version 4 keys KeyFlags subpackets should also be considered when present for
+ determining the preferred use of the key.
+
+
+ true if this key algorithm is suitable for use with signing.
+
+
+
+ True, if this is a master key.
+
+
+ The algorithm the key is encrypted with.
+
+
+ The key ID of the public key associated with this key.
+
+
+ The public key associated with this key.
+
+
+ Allows enumeration of any user IDs associated with the key.
+ An IEnumerable of string objects.
+
+
+ Allows enumeration of any user attribute vectors associated with the key.
+ An IEnumerable of string objects.
+
+
+
+ Class to hold a single master secret key and its subkeys.
+
+ Often PGP keyring files consist of multiple master keys, if you are trying to process
+ or construct one of these you should use the PgpSecretKeyRingBundle class.
+
+
+
+
+ Return the public key for the master key.
+
+
+ Return the master private key.
+
+
+ Allows enumeration of the secret keys.
+ An IEnumerable of PgpSecretKey objects.
+
+
+
+ Return an iterator of the public keys in the secret key ring that
+ have no matching private key. At the moment only personal certificate data
+ appears in this fashion.
+
+ An IEnumerable of unattached, or extra, public keys.
+
+
+
+ Replace the public key set on the secret ring with the corresponding key off the public ring.
+
+ Secret ring to be changed.
+ Public ring containing the new public key set.
+
+
+
+ Return a copy of the passed in secret key ring, with the master key and sub keys encrypted
+ using a new password and the passed in algorithm.
+
+ The PgpSecretKeyRing to be copied.
+ The current password for key.
+ The new password for the key.
+ The algorithm to be used for the encryption.
+ Source of randomness.
+
+
+
+ Returns a new key ring with the secret key passed in either added or
+ replacing an existing one with the same key ID.
+
+ The secret key ring to be modified.
+ The secret key to be inserted.
+ A new PgpSecretKeyRing
+
+
+ Returns a new key ring with the secret key passed in removed from the key ring.
+ The secret key ring to be modified.
+ The secret key to be removed.
+ A new PgpSecretKeyRing, or null if secKey is not found.
+
+
+
+ Often a PGP key ring file is made up of a succession of master/sub-key key rings.
+ If you want to read an entire secret key file in one hit this is the class for you.
+
+
+
+ Build a PgpSecretKeyRingBundle from the passed in input stream.
+ Input stream containing data.
+ If a problem parsing the stream occurs.
+ If an object is encountered which isn't a PgpSecretKeyRing.
+
+
+ Allow enumeration of the secret key rings making up this collection.
+
+
+ Allow enumeration of the key rings associated with the passed in userId.
+ The user ID to be matched.
+ An IEnumerable of key rings which matched (possibly none).
+
+
+ Allow enumeration of the key rings associated with the passed in userId.
+ The user ID to be matched.
+ If true, userId need only be a substring of an actual ID string to match.
+ An IEnumerable of key rings which matched (possibly none).
+
+
+ Allow enumeration of the key rings associated with the passed in userId.
+ The user ID to be matched.
+ If true, userId need only be a substring of an actual ID string to match.
+ If true, case is ignored in user ID comparisons.
+ An IEnumerable of key rings which matched (possibly none).
+
+
+ Return the PGP secret key associated with the given key id.
+ The ID of the secret key to return.
+
+
+ Return the secret key ring which contains the key referred to by keyId
+ The ID of the secret key
+
+
+
+ Return true if a key matching the passed in key ID is present, false otherwise.
+
+ key ID to look for.
+
+
+
+ Return a new bundle containing the contents of the passed in bundle and
+ the passed in secret key ring.
+
+ The PgpSecretKeyRingBundle the key ring is to be added to.
+ The key ring to be added.
+ A new PgpSecretKeyRingBundle merging the current one with the passed in key ring.
+ If the keyId for the passed in key ring is already present.
+
+
+
+ Return a new bundle containing the contents of the passed in bundle with
+ the passed in secret key ring removed.
+
+ The PgpSecretKeyRingBundle the key ring is to be removed from.
+ The key ring to be removed.
+ A new PgpSecretKeyRingBundle not containing the passed in key ring.
+ If the keyId for the passed in key ring is not present.
+
+
+ Return the number of rings in this collection.
+
+
+ A PGP signature object.
+
+
+
+ Verify the signature as certifying the passed in public key as associated
+ with the passed in user attributes.
+
+ User attributes the key was stored under.
+ The key to be verified.
+ True, if the signature matches, false otherwise.
+
+
+
+ Verify the signature as certifying the passed in public key as associated
+ with the passed in ID.
+
+ ID the key was stored under.
+ The key to be verified.
+ True, if the signature matches, false otherwise.
+
+
+ Verify a certification for the passed in key against the passed in master key.
+ The key we are verifying against.
+ The key we are verifying.
+ True, if the certification is valid, false otherwise.
+
+
+ Verify a key certification, such as revocation, for the passed in key.
+ The key we are checking.
+ True, if the certification is valid, false otherwise.
+
+
+ The OpenPGP version number for this signature.
+
+
+ The key algorithm associated with this signature.
+
+
+ The hash algorithm associated with this signature.
+
+
+ The ID of the key that created the signature.
+
+
+ The creation time of this signature.
+
+
+
+ Return true if the signature has either hashed or unhashed subpackets.
+
+
+
+ Generator for PGP signatures.
+
+
+ Create a generator for the passed in keyAlgorithm and hashAlgorithm codes.
+
+
+ Initialise the generator for signing.
+
+
+ Initialise the generator for signing.
+
+
+ Return the one pass header associated with the current signature.
+
+
+ Return a signature object containing the current signature state.
+
+
+ Generate a certification for the passed in ID and key.
+ The ID we are certifying against the public key.
+ The key we are certifying against the ID.
+ The certification.
+
+
+ Generate a certification for the passed in userAttributes.
+ The ID we are certifying against the public key.
+ The key we are certifying against the ID.
+ The certification.
+
+
+ Generate a certification for the passed in key against the passed in master key.
+ The key we are certifying against.
+ The key we are certifying.
+ The certification.
+
+
+ Generate a certification, such as a revocation, for the passed in key.
+ The key we are certifying.
+ The certification.
+
+
+ A list of PGP signatures - normally in the signature block after literal data.
+
+
+ Generator for signature subpackets.
+
+
+
+ Add a TrustSignature packet to the signature. The values for depth and trust are largely
+ installation dependent but there are some guidelines in RFC 4880 - 5.2.3.13.
+
+ true if the packet is critical.
+ depth level.
+ trust amount.
+
+
+
+ Set the number of seconds a key is valid for after the time of its creation.
+ A value of zero means the key never expires.
+
+ True, if should be treated as critical, false otherwise.
+ The number of seconds the key is valid, or zero if no expiry.
+
+
+
+ Set the number of seconds a signature is valid for after the time of its creation.
+ A value of zero means the signature never expires.
+
+ True, if should be treated as critical, false otherwise.
+ The number of seconds the signature is valid, or zero if no expiry.
+
+
+
+ Set the creation time for the signature.
+
+ Note: this overrides the generation of a creation time when the signature
+ is generated.
+
+
+
+
+ Sets revocation reason sub packet
+
+
+
+
+ Sets revocation key sub packet
+
+
+
+
+ Sets issuer key sub packet
+
+
+
+ Container for a list of signature subpackets.
+
+
+ Return true if a particular subpacket type exists.
+
+ @param type type to look for.
+ @return true if present, false otherwise.
+
+
+ Return all signature subpackets of the passed in type.
+ @param type subpacket type code
+ @return an array of zero or more matching subpackets.
+
+
+
+ Return the number of seconds a signature is valid for after its creation date.
+ A value of zero means the signature never expires.
+
+ Seconds a signature is valid for.
+
+
+
+ Return the number of seconds a key is valid for after its creation date.
+ A value of zero means the key never expires.
+
+ Seconds a signature is valid for.
+
+
+ Return the number of packets this vector contains.
+
+
+ Container for a list of user attribute subpackets.
+
+
+ Basic utility class.
+
+
+
+ Return either an ArmoredInputStream or a BcpgInputStream based on whether
+ the initial characters of the stream are binary PGP encodings or not.
+
+
+
+ Generator for old style PGP V3 Signatures.
+
+
+ Create a generator for the passed in keyAlgorithm and hashAlgorithm codes.
+
+
+ Initialise the generator for signing.
+
+
+ Initialise the generator for signing.
+
+
+ Return the one pass header associated with the current signature.
+
+
+ Return a V3 signature object containing the current signature state.
+
+
+ PEM generator for the original set of PEM objects used in Open SSL.
+
+
+
+ A
+
+
+
+
+ Class for reading OpenSSL PEM encoded streams containing
+ X509 certificates, PKCS8 encoded keys and PKCS7 objects.
+
+ In the case of PKCS7 objects the reader will return a CMS ContentInfo object. Keys and
+ Certificates will be returned using the appropriate java.security type.
+
+
+
+ A
+
+
+
+
+ Create a new PemReader
+
+ @param reader the Reader
+
+
+ Create a new PemReader with a password finder
+
+ @param reader the Reader
+ @param pFinder the password finder
+
+
+ Reads in a X509Certificate.
+
+ @return the X509Certificate
+ @throws IOException if an I/O error occured
+
+
+ Reads in a X509CRL.
+
+ @return the X509Certificate
+ @throws IOException if an I/O error occured
+
+
+ Reads in a PKCS10 certification request.
+
+ @return the certificate request.
+ @throws IOException if an I/O error occured
+
+
+ Reads in a X509 Attribute Certificate.
+
+ @return the X509 Attribute Certificate
+ @throws IOException if an I/O error occured
+
+
+ Reads in a PKCS7 object. This returns a ContentInfo object suitable for use with the CMS
+ API.
+
+ @return the X509Certificate
+ @throws IOException if an I/O error occured
+
+
+ Read a Key Pair
+
+
+ General purpose writer for OpenSSL PEM objects.
+
+
+ A generic PEM writer, based on RFC 1421
+
+
+ Base constructor.
+
+ @param out output stream to use.
+
+
+ Return the number of bytes or characters required to contain the
+ passed in object if it is PEM encoded.
+
+ @param obj pem object to be output
+ @return an estimate of the number of bytes
+
+
+ The TextWriter object to write the output to.
+
+
+ Constructor for an unencrypted private key PEM object.
+
+ @param key private key to be encoded.
+
+
+ Constructor for an encrypted private key PEM object.
+
+ @param key private key to be encoded
+ @param algorithm encryption algorithm to use
+ @param provider provider to use
+ @throws NoSuchAlgorithmException if algorithm/mode cannot be found
+
+
+
+ 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 Attr{{ IOSet }}
+
+ Attr { ATTRIBUTE:IOSet } ::= Sequence {
+ type ATTRIBUTE.&id({IOSet}),
+ values Set SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type})
+ }
+
+ see
+
+
+
+ Instantiate a Pkcs10CertificationRequest object with the necessary credentials.
+
+ Name of Sig Alg.
+ X509Name of subject eg OU="My unit." O="My Organisatioin" C="au"
+ Public Key to be included in cert reqest.
+ ASN1Set of Attributes.
+ Matching Private key for nominated (above) public key to be used to sign the request.
+
+
+
+ Get the public key.
+
+ The public key.
+
+
+
+ Verify Pkcs10 Cert Request is valid.
+
+ true = valid.
+
+
+
+ A class for creating and verifying Pkcs10 Certification requests (this is an extension on ).
+ The requests are made using delay signing. This is useful for situations where
+ the private key is in another environment and not directly accessible (e.g. HSM)
+ So the first step creates the request, then the signing is done outside this
+ object and the signature is then used to complete the request.
+
+
+ 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 Attr{{ IOSet }}
+
+ Attr { ATTRIBUTE:IOSet } ::= Sequence {
+ type ATTRIBUTE.&id({IOSet}),
+ values Set SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type})
+ }
+
+ see
+
+
+
+ Instantiate a Pkcs10CertificationRequest object with the necessary credentials.
+
+ Name of Sig Alg.
+ X509Name of subject eg OU="My unit." O="My Organisatioin" C="au"
+ Public Key to be included in cert reqest.
+ ASN1Set of Attributes.
+
+ After the object is constructed use the and finally the
+ SignRequest methods to finalize the request.
+
+
+
+ simply return the cert entry for the private key
+
+
+ Utility class for reencoding PKCS#12 files to definite length.
+
+
+ Just re-encode the outer layer of the PKCS#12 file to definite length encoding.
+
+ @param berPKCS12File - original PKCS#12 file
+ @return a byte array representing the DER encoding of the PFX structure
+ @throws IOException
+
+
+ Re-encode the PKCS#12 structure to definite length encoding at the inner layer
+ as well, recomputing the MAC accordingly.
+
+ @param berPKCS12File - original PKCS12 file.
+ @param provider - provider to use for MAC calculation.
+ @return a byte array representing the DER encoding of the PFX structure.
+ @throws IOException on parsing, encoding errors.
+
+
+
+ Returns the revocationDate.
+
+
+
+
+ Returns the certStatus.
+
+
+
+ Returns an immutable Set of X.509 attribute certificate
+ extensions that this PkixAttrCertChecker supports 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.
+
+
+ All X.509 attribute certificate extensions that a
+ PkixAttrCertChecker 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
+ PkixAttrCertChecker, or null if no
+ extensions are supported
+
+
+ Performs checks on the specified attribute certificate. Every handled
+ extension is rmeoved from the unresolvedCritExts
+ collection.
+
+ @param attrCert The attribute certificate to be checked.
+ @param certPath The certificate path which belongs to the attribute
+ certificate issuer public key certificate.
+ @param holderCertPath The certificate path which belongs to the holder
+ certificate.
+ @param unresolvedCritExts a Collection of OID strings
+ representing the current set of unresolved critical extensions
+ @throws CertPathValidatorException if the specified attribute certificate
+ does not pass the check.
+
+
+ Returns a clone of this object.
+
+ @return a copy of this PkixAttrCertChecker
+
+
+ Build and validate a CertPath using the given parameter.
+
+ @param params PKIXBuilderParameters object containing all information to
+ build the CertPath
+
+
+ CertPathValidatorSpi implementation for X.509 Attribute Certificates la RFC 3281.
+
+ @see org.bouncycastle.x509.ExtendedPkixParameters
+
+
+ Validates an attribute certificate with the given certificate path.
+
+
+ params must be an instance of
+ ExtendedPkixParameters.
+
+ The target constraints in the params must be an
+ X509AttrCertStoreSelector with at least the attribute
+ certificate criterion set. Obey that also target informations may be
+ necessary to correctly validate this attribute certificate.
+
+ The attribute certificate issuer must be added to the trusted attribute
+ issuers with {@link ExtendedPkixParameters#setTrustedACIssuers(Set)}.
+
+ @param certPath The certificate path which belongs to the attribute
+ certificate issuer public key certificate.
+ @param params The PKIX parameters.
+ @return A PKIXCertPathValidatorResult of the result of
+ validating the certPath.
+ @throws InvalidAlgorithmParameterException if params is
+ inappropriate for this validator.
+ @throws CertPathValidatorException if the verification fails.
+
+
+
+ Summary description for PkixBuilderParameters.
+
+
+
+
+ Summary description for PkixParameters.
+
+
+
+ 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.
+
+
+ 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.
+
+
+ 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
+
+
+ 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)
+
+
+ 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()
+
+
+ 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)
+
+
+ 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()
+
+
+ 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()
+
+
+ Returns the List of certification path checkers. Each PKIXCertPathChecker
+ in the returned IList is cloned to protect against subsequent modifications.
+
+ @return an immutable List of PKIXCertPathCheckers (may be empty, but not
+ null)
+
+ @see #setCertPathCheckers(java.util.List)
+
+
+ Adds a PKIXCertPathChecker to the list of certification
+ path checkers. See the {@link #setCertPathCheckers 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).
+
+
+ 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.
+
+
+ Sets the Bouncy Castle Stores for finding CRLs, certificates, attribute
+ certificates or cross certificates.
+
+ The IList is cloned.
+
+
+ @param stores A list of stores to use.
+ @see #getStores
+ @throws ClassCastException if an element of stores is not
+ a {@link Store}.
+
+
+ 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
+
+
+ Adds an 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()
+
+
+ Returns an IList of additional Bouncy Castle
+ Stores used for finding CRLs, certificates, attribute
+ certificates or cross certificates.
+
+ @return an immutable IList of additional Bouncy Castle
+ Stores. Never null.
+
+ @see #addAddionalStore(Store)
+
+
+ Returns an IList of Bouncy Castle
+ Stores used for finding CRLs, certificates, attribute
+ certificates or cross certificates.
+
+ @return an immutable IList of Bouncy Castle
+ Stores. Never null.
+
+ @see #setStores(IList)
+
+
+ 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.
+
+
+ Returns the required constraints on the target certificate or attribute
+ certificate. The constraints are returned as an instance of
+ IX509Selector. If null, no constraints are
+ defined.
+
+
+ The target certificate in a PKIX path may be a certificate or an
+ attribute certificate.
+
+ Note that the IX509Selector returned is cloned to protect
+ against subsequent modifications.
+
+ @return a IX509Selector specifying the constraints on the
+ target certificate or attribute certificate (or null)
+ @see #setTargetConstraints
+ @see X509CertStoreSelector
+ @see X509AttributeCertStoreSelector
+
+
+ Sets the required constraints on the target certificate or attribute
+ certificate. The constraints are specified as an instance of
+ IX509Selector. If null, no constraints are
+ defined.
+
+ The target certificate in a PKIX path may be a certificate or an
+ attribute certificate.
+
+ Note that the IX509Selector specified is cloned to protect
+ against subsequent modifications.
+
+
+ @param selector a IX509Selector specifying the constraints on
+ the target certificate or attribute certificate (or
+ null)
+ @see #getTargetConstraints
+ @see X509CertStoreSelector
+ @see X509AttributeCertStoreSelector
+
+
+ Returns the trusted attribute certificate issuers. If attribute
+ certificates is verified the trusted AC issuers must be set.
+
+ The returned ISet consists of TrustAnchors.
+
+ The returned ISet is immutable. Never null
+
+
+ @return Returns an immutable set of the trusted AC issuers.
+
+
+ Sets the trusted attribute certificate issuers. If attribute certificates
+ is verified the trusted AC issuers must be set.
+
+ The trustedACIssuers must be a ISet 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.
+
+
+ Returns the neccessary attributes which must be contained in an attribute
+ certificate.
+
+ The returned ISet is immutable and contains
+ Strings with the OIDs.
+
+
+ @return Returns the necessary AC attributes.
+
+
+ Sets the neccessary which must be contained in an attribute certificate.
+
+ The ISet 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.
+
+
+ Returns the attribute certificates which are not allowed.
+
+ The returned ISet is immutable and contains
+ Strings with the OIDs.
+
+
+ @return Returns the prohibited AC attributes. Is never null.
+
+
+ Sets the attribute certificates which are not allowed.
+
+ The ISet 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.
+
+
+ Returns the attribute certificate checker. The returned set contains
+ {@link PKIXAttrCertChecker}s and is immutable.
+
+ @return Returns the attribute certificate checker. Is never
+ null.
+
+
+ Sets the attribute certificate checkers.
+
+ All elements in the ISet 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.
+
+
+ Whether delta CRLs should be used for checking the revocation status.
+ Defaults to false.
+
+
+ The validity model.
+ @see #CHAIN_VALIDITY_MODEL
+ @see #PKIX_VALIDITY_MODEL
+
+
+ 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.
+
+
+ Returns an instance of PkixBuilderParameters.
+
+ 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 PkixBuilderParameters instance.
+
+
+
+ Excluded certificates are not used for building a certification path.
+
+ the excluded certificates.
+
+
+
+ Sets the excluded certificates which are not used for building a
+ certification path. If the ISet is null an
+ empty set is assumed.
+
+
+ The given set is cloned to protect it against subsequent modifications.
+
+ The excluded certificates to set.
+
+
+ Can alse handle ExtendedPKIXBuilderParameters and
+ PKIXBuilderParameters.
+
+ @param params Parameters to set.
+ @see org.bouncycastle.x509.ExtendedPKIXParameters#setParams(java.security.cert.PKIXParameters)
+
+
+ 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
+
+
+ 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
+
+ CertPath implementation for X.509 certificates.
+
+
+
+ @param certs
+
+
+ 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
+
+
+
+ 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
+
+
+
+ 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()
+
+
+ Returns the encoded form of this certification path, using
+ the default encoding.
+
+ @return the encoded bytes
+ @exception CertificateEncodingException if an encoding error occurs
+
+
+
+ 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
+
+
+
+ Return a DERObject containing the encoded certificate.
+
+ @param cert the X509Certificate object to be encoded
+
+ @return the DERObject
+
+
+
+ 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)
+
+
+
+
+ Returns the list of certificates in this certification
+ path.
+
+
+
+ Implements the PKIX CertPathBuilding algorithm for BouncyCastle.
+
+ @see CertPathBuilderSpi
+
+
+ Build and validate a CertPath using the given parameter.
+
+ @param params PKIXBuilderParameters object containing all information to
+ build the CertPath
+
+
+
+ Summary description for PkixCertPathBuilderException.
+
+
+
+
+ Summary description for PkixCertPathBuilderResult.
+
+
+
+
+ Summary description for PkixCertPathValidatorResult.
+
+
+
+ * 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
+ * PKIXCertPathCheckermust 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
+
+
+ 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
+
+
+ * 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
+
+
+ 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
+
+
+ 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
+
+
+ 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.
+
+ CertPathValidatorSpi implementation for X.509 Certificate validation a la RFC
+ 3280.
+
+
+
+ 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
+
+
+
+
+ Creates a PkixCertPathValidatorException with the given detail
+ message. A detail message is a String that describes this
+ particular exception.
+
+ the detail message
+
+
+
+ Creates a PkixCertPathValidatorException with the specified
+ detail message and cause.
+
+ the detail message
+ 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.)
+
+
+
+ Creates a PkixCertPathValidatorException with the specified
+ detail message, cause, certification path, and index.
+
+ the detail message (or null if none)
+ the cause (or null if none)
+ the certification path that was in the process of being
+ validated when the error was encountered
+ the index of the certificate in the certification path that *
+
+
+
+ Returns the detail message for this CertPathValidatorException.
+
+ the detail message, or null if neither the message nor cause were specified
+
+
+ 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)
+
+
+ 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
+
+
+
+ Summary description for PkixCertPathValidatorUtilities.
+
+
+
+
+ key usage bits
+
+
+
+
+ Search the given Set of TrustAnchor's for one that is the
+ issuer of the given X509 certificate.
+
+ the X509 certificate
+ a Set of TrustAnchor's
+ the TrustAnchor object if found or
+ null if not.
+
+ @exception
+
+
+
+ Returns the issuer of an attribute certificate or certificate.
+
+ The attribute certificate or certificate.
+ The issuer as X500Principal.
+
+
+ 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 Exception if DSA parameters cannot be inherited.
+
+
+
+ Return a Collection of all certificates or attribute certificates found
+ in the X509Store's that are matching the certSelect criteriums.
+
+ a {@link Selector} object that will be used to select
+ the certificates
+ a List containing only X509Store objects. These
+ are used to search for certificates.
+ a Collection of all found or
+ org.bouncycastle.x509.X509AttributeCertificate objects.
+ May be empty but never null.
+
+
+
+ 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 Exception if an exception occurs while processing.
+ @throws ClassCastException if issuerPrincipals does not
+ contain only X500Principals.
+
+
+ Fetches complete CRLs according to RFC 3280.
+
+ @param dp The distribution point for which the complete CRL
+ @param cert The X509Certificate or
+ {@link org.bouncycastle.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 Exception if an exception occurs while picking the CRLs
+ or no CRLs are found.
+
+
+ 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 Exception if an exception occurs while picking the delta
+ CRLs.
+
+
+ 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.
+
+ @exception Exception
+ if an error occurs.
+
+
+
+ Extract the value of the given extension, if it exists.
+
+ The extension object.
+ The object identifier to obtain.
+ Asn1Object
+ if the extension cannot be read.
+
+
+
+ crl checking
+ Return a Collection of all CRLs found in the X509Store's that are
+ matching the crlSelect criteriums.
+
+ a {@link X509CRLStoreSelector} object that will be used
+ to select the CRLs
+ a List containing only {@link org.bouncycastle.x509.X509Store
+ X509Store} objects. These are used to search for CRLs
+ a Collection of all found {@link X509CRL X509CRL} objects. May be
+ empty but never null.
+
+
+
+ Returns the intersection of the permitted IP ranges in
+ permitted with ip.
+
+ @param permitted A Set of permitted IP addresses with
+ their subnet mask as byte arrays.
+ @param ips The IP address with its subnet mask.
+ @return The Set of permitted IP ranges intersected with
+ ip.
+
+
+ Returns the union of the excluded IP ranges in excluded
+ with ip.
+
+ @param excluded A Set of excluded IP addresses with their
+ subnet mask as byte arrays.
+ @param ip The IP address with its subnet mask.
+ @return The Set of excluded IP ranges unified with
+ ip as byte arrays.
+
+
+ Calculates the union if two IP ranges.
+
+ @param ipWithSubmask1 The first IP address with its subnet mask.
+ @param ipWithSubmask2 The second IP address with its subnet mask.
+ @return A Set with the union of both addresses.
+
+
+ Calculates the interesction if two IP ranges.
+
+ @param ipWithSubmask1 The first IP address with its subnet mask.
+ @param ipWithSubmask2 The second IP address with its subnet mask.
+ @return A Set with the single IP address with its subnet
+ mask as a byte array or an empty Set.
+
+
+ Concatenates the IP address with its subnet mask.
+
+ @param ip The IP address.
+ @param subnetMask Its subnet mask.
+ @return The concatenated IP address with its subnet mask.
+
+
+ Splits the IP addresses and their subnet mask.
+
+ @param ipWithSubmask1 The first IP address with the subnet mask.
+ @param ipWithSubmask2 The second IP address with the subnet mask.
+ @return An array with two elements. Each element contains the IP address
+ and the subnet mask in this order.
+
+
+ Based on the two IP addresses and their subnet masks the IP range is
+ computed for each IP address - subnet mask pair and returned as the
+ minimum IP address and the maximum address of the range.
+
+ @param ip1 The first IP address.
+ @param subnetmask1 The subnet mask of the first IP address.
+ @param ip2 The second IP address.
+ @param subnetmask2 The subnet mask of the second IP address.
+ @return A array with two elements. The first/second element contains the
+ min and max IP address of the first/second IP address and its
+ subnet mask.
+
+
+ Checks if the IP ip is included in the permitted ISet
+ permitted.
+
+ @param permitted A Set of permitted IP addresses with
+ their subnet mask as byte arrays.
+ @param ip The IP address.
+ @throws PkixNameConstraintValidatorException
+ if the IP is not permitted.
+
+
+ Checks if the IP ip is included in the excluded ISet
+ excluded.
+
+ @param excluded A Set of excluded IP addresses with their
+ subnet mask as byte arrays.
+ @param ip The IP address.
+ @throws PkixNameConstraintValidatorException
+ if the IP is excluded.
+
+
+ Checks if the IP address ip is constrained by
+ constraint.
+
+ @param ip The IP address.
+ @param constraint The constraint. This is an IP address concatenated with
+ its subnetmask.
+ @return true if constrained, false
+ otherwise.
+
+
+ The common part of email1 and email2 is
+ added to the union union. If email1 and
+ email2 have nothing in common they are added both.
+
+ @param email1 Email address constraint 1.
+ @param email2 Email address constraint 2.
+ @param union The union.
+
+
+ The most restricting part from email1 and
+ email2 is added to the intersection intersect.
+
+ @param email1 Email address constraint 1.
+ @param email2 Email address constraint 2.
+ @param intersect The intersection.
+
+
+ Checks if the given GeneralName is in the permitted ISet.
+
+ @param name The GeneralName
+ @throws PkixNameConstraintValidatorException
+ If the name
+
+
+ Check if the given GeneralName is contained in the excluded ISet.
+
+ @param name The GeneralName.
+ @throws PkixNameConstraintValidatorException
+ If the name is
+ excluded.
+
+
+ Updates the permitted ISet of these name constraints with the intersection
+ with the given subtree.
+
+ @param permitted The permitted subtrees
+
+
+ Adds a subtree to the excluded ISet of these name constraints.
+
+ @param subtree A subtree with an excluded GeneralName.
+
+
+ Returns the maximum IP address.
+
+ @param ip1 The first IP address.
+ @param ip2 The second IP address.
+ @return The maximum IP address.
+
+
+ Returns the minimum IP address.
+
+ @param ip1 The first IP address.
+ @param ip2 The second IP address.
+ @return The minimum IP address.
+
+
+ Compares IP address ip1 with ip2. If ip1
+ is equal to ip2 0 is returned. If ip1 is bigger 1 is returned, -1
+ otherwise.
+
+ @param ip1 The first IP address.
+ @param ip2 The second IP address.
+ @return 0 if ip1 is equal to ip2, 1 if ip1 is bigger, -1 otherwise.
+
+
+ Returns the logical OR of the IP addresses ip1 and
+ ip2.
+
+ @param ip1 The first IP address.
+ @param ip2 The second IP address.
+ @return The OR of ip1 and ip2.
+
+
+ Stringifies an IPv4 or v6 address with subnet mask.
+
+ @param ip The IP with subnet mask.
+ @return The stringified IP address.
+
+
+
+ Summary description for PkixPolicyNode.
+
+
+
+ Constructors
+
+
+
+ This class helps to handle CRL revocation reasons mask. Each CRL handles a
+ certain set of revocation reasons.
+
+
+
+
+ Constructs are reason mask with the reasons.
+
+ The reasons.
+
+
+
+ A reason mask with no reason.
+
+
+
+
+ A mask with all revocation reasons.
+
+
+
+ Adds all reasons from the reasons mask to this mask.
+
+ @param mask The reasons mask to add.
+
+
+
+ Intersects this mask with the given reasons mask.
+
+ mask The mask to intersect with.
+ The intersection of this and teh given mask.
+
+
+
+ Returns true if the passed reasons mask has new reasons.
+
+ The reasons mask which should be tested for new reasons.
+ true if the passed reasons mask has new reasons.
+
+
+
+ Returns true if this reasons mask contains all possible
+ reasons.
+
+ true if this reasons mask contains all possible reasons.
+
+
+
+
+ Returns the reasons in this mask.
+
+
+
+ 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.
+
+
+ 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
+ g 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.
+
+
+ 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.
+
+
+ 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.
+
+
+ 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.
+
+
+ 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.
+
+
+ Checks if an attribute certificate is revoked.
+
+ @param attrCert Attribute certificate to check if it is revoked.
+ @param paramsPKIX PKIX parameters.
+ @param issuerCert The issuer certificate of the attribute certificate
+ attrCert.
+ @param validDate The date when the certificate revocation status should
+ be checked.
+ @param certPathCerts The certificates of the certification path to be
+ checked.
+
+ @throws CertPathValidatorException if the certificate is revoked or the
+ status cannot be checked or some error occurs.
+
+
+ Searches for a holder public key certificate and verifies its
+ certification path.
+
+ @param attrCert the attribute certificate.
+ @param pkixParams The PKIX parameters.
+ @return The certificate path of the holder certificate.
+ @throws Exception if
+
+
no public key certificate can be found although holder
+ information is given by an entity name or a base certificate
+ ID
+
support classes cannot be created
+
no certification path for the public key certificate can
+ be built
+
+
+
+
+ Checks a distribution point for revocation information for the
+ certificate attrCert.
+
+ @param dp The distribution point to consider.
+ @param attrCert The attribute certificate which should be checked.
+ @param paramsPKIX PKIX parameters.
+ @param validDate The date when the certificate revocation status should
+ be checked.
+ @param issuerCert Certificate to check if it is revoked.
+ @param reasonMask The reasons mask which is already checked.
+ @param certPathCerts The certificates of the certification path to be
+ checked.
+ @throws Exception if the certificate is revoked or the status
+ cannot be checked or some error occurs.
+
+
+
+ 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.
+
+
+
+
+ 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.
+
+
+
+ Note that the name constraints byte array supplied is cloned to protect
+ against subsequent modifications.
+
+ a trusted X509Certificate
+ 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.
+ if the specified X509Certificate is null
+
+
+
+ Creates an instance of TrustAnchor where the
+ most-trusted CA is specified as an X500Principal 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 the other constructors.
+
+ Note that the name constraints byte array supplied here is cloned to
+ protect against subsequent modifications.
+
+
+ the name of the most-trusted CA as X509Name
+ the public key of the most-trusted CA
+
+ 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.
+
+
+ if caPrincipal or pubKey is null
+
+
+
+
+ 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 X.500 distinguished name of the most-trusted CA in RFC
+ 2253 string format
+ the public key of the most-trusted CA
+ 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.
+ throws NullPointerException, IllegalArgumentException
+
+
+
+ Decode the name constraints and clone them if not null.
+
+
+
+
+ Returns a formatted string describing the TrustAnchor.
+
+ a formatted string describing the TrustAnchor
+
+
+
+ Returns the most-trusted CA certificate.
+
+
+
+
+ Returns the name of the most-trusted CA as an X509Name.
+
+
+
+
+ Returns the name of the most-trusted CA in RFC 2253 string format.
+
+
+
+
+ Returns the public key of the most-trusted CA.
+
+
+
+
+ Utility class for creating IBasicAgreement objects from their names/Oids
+
+
+
+
+ Cipher Utility class contains methods that can not be specifically grouped into other classes.
+
+
+
+
+ Returns a ObjectIdentifier for a give encoding.
+
+ A string representation of the encoding.
+ A DerObjectIdentifier, null if the Oid is not available.
+
+
+
+ Utility class for creating IDigest objects from their names/Oids
+
+
+
+
+ Returns a ObjectIdentifier for a given digest mechanism.
+
+ A string representation of the digest meanism.
+ A DerObjectIdentifier, null if the Oid is not available.
+
+
+
+ Utility class for creating HMac object from their names/Oids
+
+
+
+
+
+
+
+
+
+ Returns a ObjectIdentifier for a give encoding.
+
+ A string representation of the encoding.
+ A DerObjectIdentifier, null if the Oid is not available.
+
+
+ Use the specified instance of IRandomGenerator as random source.
+
+ This constructor performs no seeding of either the IRandomGenerator or the
+ constructed SecureRandom. It is the responsibility of the client to provide
+ proper seed material as necessary/appropriate for the given IRandomGenerator
+ implementation.
+
+ The source to generate all random bytes from.
+
+
+ base constructor.
+
+
+ create a SecurityUtilityException with the given message.
+
+ @param message the message to be carried with the exception.
+
+
+
+ Signer Utility class contains methods that can not be specifically grouped into other classes.
+
+
+
+
+ Returns a ObjectIdentifier for a give encoding.
+
+ A string representation of the encoding.
+ A DerObjectIdentifier, null if the Oid is not available.
+
+
+
+ Utility class for creating IWrapper objects from their names/Oids
+
+
+
+ Base class for an RFC 3161 Time Stamp Request.
+
+
+ Create a TimeStampRequest from the past in byte array.
+
+ @param req byte array containing the request.
+ @throws IOException if the request is malformed.
+
+
+ Create a TimeStampRequest from the past in input stream.
+
+ @param in input stream containing the request.
+ @throws IOException if the request is malformed.
+
+
+ Validate the timestamp request, checking the digest to see if it is of an
+ accepted type and whether it is of the correct length for the algorithm specified.
+
+ @param algorithms a set of string OIDS giving accepted algorithms.
+ @param policies if non-null a set of policies we are willing to sign under.
+ @param extensions if non-null a set of extensions we are willing to accept.
+ @throws TspException if the request is invalid, or processing fails.
+
+
+ return the ASN.1 encoded representation of this object.
+
+
+ Generator for RFC 3161 Time Stamp Request objects.
+
+
+ add a given extension field for the standard extensions tag (tag 3)
+ @throws IOException
+
+
+ add a given extension field for the standard extensions tag
+ The value parameter becomes the contents of the octet string associated
+ with the extension.
+
+
+ add a given extension field for the standard extensions tag (tag 3)
+ @throws IOException
+
+
+ add a given extension field for the standard extensions tag
+ The value parameter becomes the contents of the octet string associated
+ with the extension.
+
+
+ Base class for an RFC 3161 Time Stamp Response object.
+
+
+ Create a TimeStampResponse from a byte array containing an ASN.1 encoding.
+
+ @param resp the byte array containing the encoded response.
+ @throws TspException if the response is malformed.
+ @throws IOException if the byte array doesn't represent an ASN.1 encoding.
+
+
+ Create a TimeStampResponse from an input stream containing an ASN.1 encoding.
+
+ @param input the input stream containing the encoded response.
+ @throws TspException if the response is malformed.
+ @throws IOException if the stream doesn't represent an ASN.1 encoding.
+
+
+ Check this response against to see if it a well formed response for
+ the passed in request. Validation will include checking the time stamp
+ token if the response status is GRANTED or GRANTED_WITH_MODS.
+
+ @param request the request to be checked against
+ @throws TspException if the request can not match this response.
+
+
+ return the ASN.1 encoded representation of this object.
+
+
+ Generator for RFC 3161 Time Stamp Responses.
+
+
+ Return an appropriate TimeStampResponse.
+
+ If genTime is null a timeNotAvailable error response will be returned.
+
+ @param request the request this response is for.
+ @param serialNumber serial number for the response token.
+ @param genTime generation time for the response token.
+ @param provider provider to use for signature calculation.
+ @return
+ @throws NoSuchAlgorithmException
+ @throws NoSuchProviderException
+ @throws TSPException
+
+
+
+ Generate a TimeStampResponse with chosen status and FailInfoField.
+
+ @param status the PKIStatus to set.
+ @param failInfoField the FailInfoField to set.
+ @param statusString an optional string describing the failure.
+ @return a TimeStampResponse with a failInfoField and optional statusString
+ @throws TSPException in case the response could not be created
+
+
+ Validate the time stamp token.
+
+ To be valid the token must be signed by the passed in certificate and
+ the certificate must be the one referred to by the SigningCertificate
+ attribute included in the hashed attributes of the token. The
+ certificate must also have the ExtendedKeyUsageExtension with only
+ KeyPurposeID.IdKPTimeStamping and have been valid at the time the
+ timestamp was created.
+
+
+ A successful call to validate means all the above are true.
+
+
+
+ Return the underlying CmsSignedData object.
+
+ @return the underlying CMS structure.
+
+
+ Return a ASN.1 encoded byte stream representing the encoded object.
+
+ @throws IOException if encoding fails.
+
+
+ basic creation - only the default attributes will be included here.
+
+
+ create with a signer with extra signed/unsigned attributes.
+
+
+ @return the nonce value, null if there isn't one.
+
+
+ Recognised hash algorithms for the time stamp protocol.
+
+
+ Fetches the signature time-stamp attributes from a SignerInformation object.
+ Checks that the MessageImprint for each time-stamp matches the signature field.
+ (see RFC 3161 Appendix A).
+
+ @param signerInfo a SignerInformation to search for time-stamps
+ @return a collection of TimeStampToken objects
+ @throws TSPValidationException
+
+
+ Validate the passed in certificate as being of the correct type to be used
+ for time stamping. To be valid it must have an ExtendedKeyUsage extension
+ which has a key purpose identifier of id-kp-timeStamping.
+
+ @param cert the certificate of interest.
+ @throws TspValidationException if the certicate fails on one of the check points.
+
+
+
+ Return the digest algorithm using one of the standard JCA string
+ representations rather than the algorithm identifier (if possible).
+
+
+
+ Exception thrown if a TSP request or response fails to validate.
+
+ If a failure code is associated with the exception it can be retrieved using
+ the getFailureCode() method.
+
+
+ Return the failure code associated with this exception - if one is set.
+
+ @return the failure code if set, -1 otherwise.
+
+
+ General array utilities.
+
+
+
+ Are two arrays equal.
+
+ Left side.
+ Right side.
+ True if equal.
+
+
+
+ A constant time equals comparison - does not terminate early if
+ test will fail.
+
+ first array
+ second array
+ true if arrays equal, false otherwise.
+
+
+ BigInteger utilities.
+
+
+ Return the passed in value as an unsigned byte array.
+
+ @param value value to be converted.
+ @return a byte array without a leading zero byte if present in the signed encoding.
+
+
+ Return a random BigInteger not less than 'min' and not greater than 'max'
+
+ @param min the least value that may be generated
+ @param max the greatest value that may be generated
+ @param random the source of randomness
+ @return a random BigInteger value in the range [min,max]
+
+
+
+ Return the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC) for a given DateTime value.
+
+ A UTC DateTime value not before epoch.
+ Number of whole milliseconds after epoch.
+ 'dateTime' is before epoch.
+
+
+
+ Create a DateTime value from the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC).
+
+ Number of milliseconds since the epoch.
+ A UTC DateTime value
+
+
+
+ Return the current number of milliseconds since the Unix epoch (1 Jan., 1970 UTC).
+
+
+
+ encode the input data producing a base 64 encoded byte array.
+
+ @return a byte array containing the base 64 encoded data.
+
+
+ Encode the byte data to base 64 writing it to the given output stream.
+
+ @return the number of bytes produced.
+
+
+ Encode the byte data to base 64 writing it to the given output stream.
+
+ @return the number of bytes produced.
+
+
+ decode the base 64 encoded input data. It is assumed the input data is valid.
+
+ @return a byte array representing the decoded data.
+
+
+ decode the base 64 encoded string data - whitespace will be ignored.
+
+ @return a byte array representing the decoded data.
+
+
+ decode the base 64 encoded string data writing it to the given output stream,
+ whitespace characters will be ignored.
+
+ @return the number of bytes produced.
+
+
+ Encode and decode byte arrays (typically from binary to 7-bit ASCII
+ encodings).
+
+
+ encode the input data producing a base 64 output stream.
+
+ @return the number of bytes produced.
+
+
+ decode the base 64 encoded byte data writing it to the given output stream,
+ whitespace characters will be ignored.
+
+ @return the number of bytes produced.
+
+
+ decode the base 64 encoded string data writing it to the given output stream,
+ whitespace characters will be ignored.
+
+ @return the number of bytes produced.
+
+
+
+ A buffering class to allow translation from one format to another to
+ be done in discrete chunks.
+
+
+
+
+ Create a buffered Decoder.
+
+ The translater to use.
+ The size of the buffer.
+
+
+
+ Process one byte of data.
+
+ Data in.
+ Byte array for the output.
+ The offset in the output byte array to start writing from.
+ The amount of output bytes.
+
+
+
+ Process data from a byte array.
+
+ The input data.
+ Start position within input data array.
+ Amount of data to process from input data array.
+ Array to store output.
+ Position in output array to start writing from.
+ The amount of output bytes.
+
+
+
+ A class that allows encoding of data using a specific encoder to be processed in chunks.
+
+
+
+
+ Create.
+
+ The translator to use.
+ Size of the chunks.
+
+
+
+ Process one byte of data.
+
+ The byte.
+ An array to store output in.
+ Offset within output array to start writing from.
+
+
+
+
+ Process data from a byte array.
+
+ Input data Byte array containing data to be processed.
+ Start position within input data array.
+ Amount of input data to be processed.
+ Output data array.
+ Offset within output data array to start writing to.
+ The amount of data written.
+
+
+
+ Class to decode and encode Hex.
+
+
+
+ encode the input data producing a Hex encoded byte array.
+
+ @return a byte array containing the Hex encoded data.
+
+
+ encode the input data producing a Hex encoded byte array.
+
+ @return a byte array containing the Hex encoded data.
+
+
+ Hex encode the byte data writing it to the given output stream.
+
+ @return the number of bytes produced.
+
+
+ Hex encode the byte data writing it to the given output stream.
+
+ @return the number of bytes produced.
+
+
+ decode the Hex encoded input data. It is assumed the input data is valid.
+
+ @return a byte array representing the decoded data.
+
+
+ decode the Hex encoded string data - whitespace will be ignored.
+
+ @return a byte array representing the decoded data.
+
+
+ decode the Hex encoded string data writing it to the given output stream,
+ whitespace characters will be ignored.
+
+ @return the number of bytes produced.
+
+
+ encode the input data producing a Hex output stream.
+
+ @return the number of bytes produced.
+
+
+ decode the Hex encoded byte data writing it to the given output stream,
+ whitespace characters will be ignored.
+
+ @return the number of bytes produced.
+
+
+ decode the Hex encoded string data writing it to the given output stream,
+ whitespace characters will be ignored.
+
+ @return the number of bytes produced.
+
+
+
+ A hex translator.
+
+
+
+
+ Translator interface.
+
+
+
+
+ Return encoded block size.
+
+ 2
+
+
+
+ Encode some data.
+
+ Input data array.
+ Start position within input data array.
+ The amount of data to process.
+ The output data array.
+ The offset within the output data array to start writing from.
+ Amount of data encoded.
+
+
+
+ Returns the decoded block size.
+
+ 1
+
+
+
+ Decode data from a byte array.
+
+ The input data array.
+ Start position within input data array.
+ The amounty of data to process.
+ The output data array.
+ The position within the output data array to start writing from.
+ The amount of data written.
+
+
+ Convert binary data to and from UrlBase64 encoding. This is identical to
+ Base64 encoding, except that the padding character is "." and the other
+ non-alphanumeric characters are "-" and "_" instead of "+" and "/".
+
+ The purpose of UrlBase64 encoding is to provide a compact encoding of binary
+ data that is safe for use as an URL parameter. Base64 encoding does not
+ produce encoded values that are safe for use in URLs, since "/" can be
+ interpreted as a path delimiter; "+" is the encoded form of a space; and
+ "=" is used to separate a name from the corresponding value in an URL
+ parameter.
+
+
+
+ Encode the input data producing a URL safe base 64 encoded byte array.
+
+ @return a byte array containing the URL safe base 64 encoded data.
+
+
+ Encode the byte data writing it to the given output stream.
+
+ @return the number of bytes produced.
+
+
+ Decode the URL safe base 64 encoded input data - white space will be ignored.
+
+ @return a byte array representing the decoded data.
+
+
+ decode the URL safe base 64 encoded byte data writing it to the given output stream,
+ whitespace characters will be ignored.
+
+ @return the number of bytes produced.
+
+
+ decode the URL safe base 64 encoded string data - whitespace will be ignored.
+
+ @return a byte array representing the decoded data.
+
+
+ Decode the URL safe base 64 encoded string data writing it to the given output stream,
+ whitespace characters will be ignored.
+
+ @return the number of bytes produced.
+
+
+ Convert binary data to and from UrlBase64 encoding. This is identical to
+ Base64 encoding, except that the padding character is "." and the other
+ non-alphanumeric characters are "-" and "_" instead of "+" and "/".
+
+ The purpose of UrlBase64 encoding is to provide a compact encoding of binary
+ data that is safe for use as an URL parameter. Base64 encoding does not
+ produce encoded values that are safe for use in URLs, since "/" can be
+ interpreted as a path delimiter; "+" is the encoded form of a space; and
+ "=" is used to separate a name from the corresponding value in an URL
+ parameter.
+
+
+
+
+ A
+
+
+ A
+
+
+
+
+
+ Pipe all bytes from inStr to outStr, throwing StreamFlowException if greater
+ than limit bytes in inStr.
+
+
+ A
+
+
+ A
+
+
+ A
+
+ The number of bytes actually transferred, if not greater than limit
+
+
+
+ Validate the given IPv4 or IPv6 address.
+
+ @param address the IP address as a string.
+
+ @return true if a valid address, false otherwise
+
+
+ Validate the given IPv4 or IPv6 address and netmask.
+
+ @param address the IP address as a string.
+
+ @return true if a valid address with netmask, false otherwise
+
+
+ Validate the given IPv4 address.
+
+ @param address the IP address as a string.
+
+ @return true if a valid IPv4 address, false otherwise
+
+
+ Validate the given IPv6 address.
+
+ @param address the IP address as a string.
+
+ @return true if a valid IPv4 address, false otherwise
+
+
+ General string utilities.
+
+
+
+ Summary description for DeflaterOutputStream.
+
+
+
+
+ Summary description for DeflaterOutputStream.
+
+
+
+
+ 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
+ }
+
+
+
+
+ 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.
+
+
+ Returns the hash if an object digest info is used.
+
+ @return The hash or null if no object digest info is set.
+
+
+ Return any principal objects inside the attribute certificate holder entity names field.
+
+ @return an array of IPrincipal objects (usually X509Name), null if no entity names field is set.
+
+
+ Return the principals associated with the issuer attached to this holder
+
+ @return an array of principals, null if no BaseCertificateID is set.
+
+
+ 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.
+
+
+ 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.
+
+
+ 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.
+
+
+ Return the serial number associated with the issuer attached to this holder.
+
+ @return the certificate serial number, null if no BaseCertificateID is set.
+
+
+ Carrying class for an attribute certificate issuer.
+
+
+ Set the issuer directly with the ASN.1 structure.
+
+ @param issuer The issuer
+
+
+ Return any principal objects inside the attribute certificate issuer object.
+ An array of IPrincipal objects (usually X509Principal).
+
+
+ A high level authority key identifier.
+
+
+ Constructor which will take the byte[] returned from getExtensionValue()
+
+ @param encodedValue a DER octet encoded string with the extension structure in it.
+ @throws IOException on parsing errors.
+
+
+ Create an AuthorityKeyIdentifier using the passed in certificate's public
+ key, issuer and serial number.
+
+ @param certificate the certificate providing the information.
+ @throws CertificateParsingException if there is a problem processing the certificate
+
+
+ Create an AuthorityKeyIdentifier using just the hash of the
+ public key.
+
+ @param pubKey the key to generate the hash from.
+ @throws InvalidKeyException if there is a problem using the key.
+
+
+ A high level subject key identifier.
+
+
+ Constructor which will take the byte[] returned from getExtensionValue()
+
+ @param encodedValue a DER octet encoded string with the extension structure in it.
+ @throws IOException on parsing errors.
+
+
+ Interface for an X.509 Attribute Certificate.
+
+
+ Return the attributes contained in the attribute block in the certificate.
+ An array of attributes.
+
+
+ Return the attributes with the same type as the passed in oid.
+ The object identifier we wish to match.
+ An array of matched attributes, null if there is no match.
+
+
+ Return an ASN.1 encoded byte array representing the attribute certificate.
+ An ASN.1 encoded byte array.
+ If the certificate cannot be encoded.
+
+
+ The version number for the certificate.
+
+
+ The serial number for the certificate.
+
+
+ The UTC DateTime before which the certificate is not valid.
+
+
+ The UTC DateTime after which the certificate is not valid.
+
+
+ The holder of the certificate.
+
+
+ The issuer details for the certificate.
+
+
+
+ A utility class that will extract X509Principal objects from X.509 certificates.
+
+ Use this in preference to trying to recreate a principal from a string, not all
+ DNs are what they should be, so it's best to leave them encoded where they
+ can be.
+
+
+
+ Return the issuer of the given cert as an X509Principal.
+
+
+ Return the subject of the given cert as an X509Principal.
+
+
+ Return the issuer of the given CRL as an X509Principal.
+
+
+ This class is an Selector like implementation to select
+ attribute certificates from a given set of criteria.
+
+ @see org.bouncycastle.x509.X509AttributeCertificate
+ @see org.bouncycastle.x509.X509Store
+
+
+
+ Decides if the given attribute certificate should be selected.
+
+ The attribute certificate to be checked.
+ true if the object matches this selector.
+
+
+ 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)
+
+
+ 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.
+
+
+ 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)
+
+
+ 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)
+
+
+ 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)
+
+
+ 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.
+
+
+ Adds a collection with target groups criteria. If null is
+ given any will do.
+
+ The collection consists of GeneralName objects or byte[]
+ representing DER encoded GeneralNames.
+
+
+ @param names A collection of target groups.
+ @throws IOException if a parsing error occurs.
+ @see #AddTargetGroup(byte[])
+ @see #AddTargetGroup(GeneralName)
+
+
+ Gets the target groups. 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 groups.
+ @see #setTargetGroups(Collection)
+
+
+ The attribute certificate which must be matched.
+ If null is given, any will do.
+
+
+ The criteria for validity
+ If null is given any will do.
+
+
+ The holder.
+ If null is given any will do.
+
+
+ The issuer.
+ If null is given any will do.
+
+
+ The serial number.
+ If null is given any will do.
+
+
+
+ This class is an IX509Selector implementation to select
+ certificate pairs, which are e.g. used for cross certificates. The set of
+ criteria is given from two X509CertStoreSelector objects,
+ each of which, if present, must match the respective component of a pair.
+
+
+
+
+ Decides if the given certificate pair should be selected. If
+ obj is not a X509CertificatePair, this method
+ returns false.
+
+ The X509CertificatePair to be tested.
+ true if the object matches this selector.
+
+
+ The certificate pair which is used for testing on equality.
+
+
+ The certificate selector for the forward part.
+
+
+ The certificate selector for the reverse part.
+
+
+ A simple collection backed store.
+
+
+ Basic constructor.
+
+ @param collection - initial contents for the store, this is copied.
+
+
+ Return the matches in the collection for the passed in selector.
+
+ @param selector the selector to match against.
+ @return a possibly empty collection of matching objects.
+
+
+ This class contains a collection for collection based X509Stores.
+
+
+
+ Constructor.
+
+ The collection is copied.
+
+
+ The collection containing X.509 object types.
+ If collection is null.
+
+
+ Returns a copy of the ICollection.
+
+
+ Returns a formatted string describing the parameters.
+
+
+
+ An ICollection of X509Name objects
+
+
+
+ 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 IX509AttributeCertificate being checked (or
+ null)
+ @see #getAttrCertificateChecking()
+
+
+ If true only complete CRLs are returned. Defaults to
+ false.
+
+ @return true if only complete CRLs are returned.
+
+
+ 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.
+
+
+ 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(bool)}.
+
+ @param issuingDistributionPoint The issuing distribution point to set.
+ This is the DER encoded OCTET STRING extension value.
+ @see #getIssuingDistributionPoint()
+
+
+ Whether 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.
+
+
+ The maximum base CRL number. Defaults to null.
+
+ @return Returns the maximum base CRL number.
+ @see #setMaxBaseCRLNumber(BigInteger)
+
+
+
+ A factory to produce Public Key Info Objects.
+
+
+
+
+ Create a Subject Public Key Info object for a given public key.
+
+ One of ElGammalPublicKeyParameters, DSAPublicKeyParameter, DHPublicKeyParameters, RsaKeyParameters or ECPublicKeyParameters
+ A subject public key info object.
+ Throw exception if object provided is not one of the above.
+
+
+
+ Create loading data from byte array.
+
+
+
+
+
+ Create loading data from byte array.
+
+
+
+
+ Generates a certificate object and initializes it with the data
+ read from the input stream inStream.
+
+
+ Returns a (possibly empty) collection view of the certificates
+ read from the given input stream inStream.
+
+
+ Class for carrying the values in an X.509 Attribute.
+
+
+ @param at an object representing an attribute.
+
+
+ Create an X.509 Attribute with the type given by the passed in oid and
+ the value represented by an ASN.1 Set containing value.
+
+ @param oid type of the attribute
+ @param value value object to go into the atribute's value set.
+
+
+ Create an X.59 Attribute with the type given by the passed in oid and the
+ value represented by an ASN.1 Set containing the objects in value.
+
+ @param oid type of the attribute
+ @param value vector of values to go in the attribute's value set.
+
+
+
+ An Object representing an X509 Certificate.
+ Has static methods for loading Certificates encoded in many forms that return X509Certificate Objects.
+
+
+
+
+ Return true if the nominated time is within the start and end times nominated on the certificate.
+
+ The time to test validity against.
+ True if certificate is valid for nominated time.
+
+
+
+ Checks if the current date is within certificate's validity period.
+
+
+
+
+ Checks if the given date is within certificate's validity period.
+
+ if the certificate is expired by given date
+ if the certificate is not yet valid on given date
+
+
+
+ Return the Der encoded TbsCertificate data.
+ This is the certificate component less the signature.
+ To Get the whole certificate call the GetEncoded() member.
+
+ A byte array containing the Der encoded Certificate component.
+
+
+
+ The signature.
+
+ A byte array containg the signature of the certificate.
+
+
+
+ Get the signature algorithms parameters. (EG DSA Parameters)
+
+ A byte array containing the Der encoded version of the parameters or null if there are none.
+
+
+
+ Get a key usage guidlines.
+
+
+
+
+ Get the public key of the subject of the certificate.
+
+ The public key parameters.
+
+
+
+ Return a Der encoded version of this certificate.
+
+ A byte array.
+
+
+
+ Verify the certificate's signature using the nominated public key.
+
+ An appropriate public key parameter object, RsaPublicKeyParameters, DsaPublicKeyParameters or ECDsaPublicKeyParameters
+ True if the signature is valid.
+ If key submitted is not of the above nominated types.
+
+
+
+ Return true if the current time is within the start and end times nominated on the certificate.
+
+ true id certificate is valid for the current time.
+
+
+
+ Return the certificate's version.
+
+ An integer whose value Equals the version of the cerficate.
+
+
+
+ Return a BigInteger containing the serial number.
+
+ The Serial number.
+
+
+
+ Get the Issuer Distinguished Name. (Who signed the certificate.)
+
+ And X509Object containing name and value pairs.
+
+
+
+ Get the subject of this certificate.
+
+ An X509Name object containing name and value pairs.
+
+
+
+ The time that this certificate is valid from.
+
+ A DateTime object representing that time in the local time zone.
+
+
+
+ The time that this certificate is valid up to.
+
+ A DateTime object representing that time in the local time zone.
+
+
+
+ A meaningful version of the Signature Algorithm. (EG SHA1WITHRSA)
+
+ A sting representing the signature algorithm.
+
+
+
+ Get the Signature Algorithms Object ID.
+
+ A string containg a '.' separated object id.
+
+
+
+ Get the issuers UID.
+
+ A DerBitString.
+
+
+
+ Get the subjects UID.
+
+ A DerBitString.
+
+
+
+ This class contains a cross certificate pair. Cross certificates pairs may
+ contain two cross signed certificates from two CAs. A certificate from the
+ other CA to this CA is contained in the forward certificate, the certificate
+ from this CA to the other CA is contained in the reverse certificate.
+
+
+
+ Constructor
+ Certificate from the other CA to this CA.
+ Certificate from this CA to the other CA.
+
+
+ Constructor from a ASN.1 CertificatePair structure.
+ The CertificatePair ASN.1 object.
+
+
+ Returns the certificate from the other CA to this CA.
+
+
+ Returns the certificate from this CA to the other CA.
+
+
+ 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.
+
+
+
+ Create loading data from byte array.
+
+
+
+
+
+ Create loading data from byte array.
+
+
+
+
+ Generates a certificate object and initializes it with the data
+ read from the input stream inStream.
+
+
+ Returns a (possibly empty) collection view of the certificates
+ read from the given input stream inStream.
+
+
+
+ Create loading data from byte array.
+
+
+
+
+
+ Create loading data from byte array.
+
+
+
+
+ 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)
+
+
+ Returns a string representation of this CRL.
+
+ @return a string representation of this CRL.
+
+
+ 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.
+
+
+ The following extensions are listed in RFC 2459 as relevant to CRL Entries
+
+ ReasonCode Hode Instruction Code Invalidity Date Certificate Issuer
+ (critical)
+
+
+ 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
+ TbsCertificateList.CrlEntry object.
+ @param isIndirect
+ true if the corresponding CRL is a indirect
+ CRL.
+ @param previousCertificateIssuer
+ Certificate issuer of the previous CrlEntry.
+
+
+
+ Create loading data from byte array.
+
+
+
+
+
+ Create loading data from byte array.
+
+
+
+
+ Generates a certificate revocation list (CRL) object and initializes
+ it with the data read from the input stream inStream.
+
+
+ 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 significant field being crls. In particular the signature
+ and the contents are ignored.
+
+
+ A holding class for constructing an X509 Key Usage extension.
+
+
+
+
+ Basic constructor.
+
+ @param usage - the bitwise OR of the Key Usage flags giving the
+ allowed uses for the key.
+ e.g. (X509KeyUsage.keyEncipherment | X509KeyUsage.dataEncipherment)
+
+
+ Return the digest algorithm using one of the standard JCA string
+ representations rather than the algorithm identifier (if possible).
+
+
+
+ Class to Generate X509V1 Certificates.
+
+
+
+
+ Default Constructor.
+
+
+
+
+ Reset the generator.
+
+
+
+
+ Set the certificate's serial number.
+
+ Make serial numbers long, if you have no serial number policy make sure the number is at least 16 bytes of secure random data.
+ You will be surprised how ugly a serial number collision can get.
+ The serial number.
+
+
+
+ Set the issuer distinguished name.
+ The issuer is the entity whose private key is used to sign the certificate.
+
+ The issuers DN.
+
+
+
+ Set the date that this certificate is to be valid from.
+
+
+
+
+
+ Set the date after which this certificate will no longer be valid.
+
+
+
+
+
+ Set the subject distinguished name.
+ The subject describes the entity associated with the public key.
+
+
+
+
+
+ Set the public key that this certificate identifies.
+
+
+
+
+
+ Set the signature algorithm that will be used to sign this certificate.
+ This can be either a name or an OID, names are treated as case insensitive.
+
+ string representation of the algorithm name
+
+
+
+ Generate a new X509Certificate.
+
+ The private key of the issuer used to sign this certificate.
+ An X509Certificate.
+
+
+
+ Generate a new X509Certificate specifying a SecureRandom instance that you would like to use.
+
+ The private key of the issuer used to sign this certificate.
+ The Secure Random you want to use.
+ An X509Certificate.
+
+
+
+ Allows enumeration of the signature names supported by the generator.
+
+
+
+ An implementation of a version 2 X.509 Attribute Certificate.
+
+
+ Class to produce an X.509 Version 2 AttributeCertificate.
+
+
+ Reset the generator
+
+
+ Set the Holder of this Attribute Certificate.
+
+
+ Set the issuer.
+
+
+ Set the serial number for the certificate.
+
+
+
+ Set the signature algorithm. This can be either a name or an OID, names
+ are treated as case insensitive.
+
+ The algorithm name.
+
+
+ Add an attribute.
+
+
+ Add a given extension field for the standard extensions tag.
+
+
+
+ Add a given extension field for the standard extensions tag.
+ The value parameter becomes the contents of the octet string associated
+ with the extension.
+
+
+
+
+ Generate an X509 certificate, based on the current issuer and subject.
+
+
+
+
+ Generate an X509 certificate, based on the current issuer and subject,
+ using the supplied source of randomness, if required.
+
+
+
+
+ Allows enumeration of the signature names supported by the generator.
+
+
+
+ class to produce an X.509 Version 2 CRL.
+
+
+ reset the generator
+
+
+ Set the issuer distinguished name - the issuer is the entity whose private key is used to sign the
+ certificate.
+
+
+ Reason being as indicated by CrlReason, i.e. CrlReason.KeyCompromise
+ or 0 if CrlReason is not to be used
+
+
+
+ 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
+
+
+
+ Add a CRL entry with extensions.
+
+
+
+ Add the CRLEntry objects contained in a previous CRL.
+
+ @param other the X509Crl to source the other entries from.
+
+
+ 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.
+
+
+ add a given extension field for the standard extensions tag (tag 0)
+
+
+ add a given extension field for the standard extensions tag (tag 0)
+
+
+ add a given extension field for the standard extensions tag (tag 0)
+
+
+ add a given extension field for the standard extensions tag (tag 0)
+
+
+ Generate an X509 CRL, based on the current issuer and subject.
+ The key used for signing.
+
+
+ Generate an X509 CRL, based on the current issuer and subject.
+ The key used for signing.
+ A user-defined source of randomness.
+
+
+
+ Allows enumeration of the signature names supported by the generator.
+
+
+
+
+ A class to Generate Version 3 X509Certificates.
+
+
+
+
+ Reset the Generator.
+
+
+
+
+ Set the certificate's serial number.
+
+ Make serial numbers long, if you have no serial number policy make sure the number is at least 16 bytes of secure random data.
+ You will be surprised how ugly a serial number collision can Get.
+ The serial number.
+
+
+
+ Set the distinguished name of the issuer.
+ The issuer is the entity which is signing the certificate.
+
+ The issuer's DN.
+
+
+
+ Set the date that this certificate is to be valid from.
+
+
+
+
+
+ Set the date after which this certificate will no longer be valid.
+
+
+
+
+
+ Set the DN of the entity that this certificate is about.
+
+
+
+
+
+ Set the public key that this certificate identifies.
+
+
+
+
+
+ Set the signature algorithm that will be used to sign this certificate.
+
+
+
+
+
+ Set the subject unique ID - note: it is very rare that it is correct to do this.
+
+
+
+
+
+ Set the issuer unique ID - note: it is very rare that it is correct to do this.
+
+
+
+
+
+ Add a given extension field for the standard extensions tag (tag 3).
+
+ string containing a dotted decimal Object Identifier.
+ Is it critical.
+ The value.
+
+
+
+ Add an extension to this certificate.
+
+ Its Object Identifier.
+ Is it critical.
+ The value.
+
+
+
+ Add an extension using a string with a dotted decimal OID.
+
+ string containing a dotted decimal Object Identifier.
+ Is it critical.
+ byte[] containing the value of this extension.
+
+
+
+ Add an extension to this certificate.
+
+ Its Object Identifier.
+ Is it critical.
+ byte[] containing the value of this extension.
+
+
+
+ Add a given extension field for the standard extensions tag (tag 3),
+ copying the extension value from another certificate.
+
+
+
+ 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.
+
+
+
+ Generate an X509Certificate.
+
+ The private key of the issuer that is signing this certificate.
+ An X509Certificate.
+
+
+
+ Generate an X509Certificate using your own SecureRandom.
+
+ The private key of the issuer that is signing this certificate.
+ You Secure Random instance.
+ An X509Certificate.
+
+
+
+ Allows enumeration of the signature names supported by the generator.
+
+
+
+
diff --git a/Crypto/src/AssemblyInfo.cs b/Crypto/src/AssemblyInfo.cs
new file mode 100644
index 000000000..7064bf82e
--- /dev/null
+++ b/Crypto/src/AssemblyInfo.cs
@@ -0,0 +1,82 @@
+using System;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+//using System.Security.Permissions;
+
+//
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+//
+#if INCLUDE_IDEA
+[assembly: AssemblyTitle("BouncyCastle.CryptoExt")]
+[assembly: AssemblyDescription("Bouncy Castle Cryptography API (Extended)")]
+#else
+[assembly: AssemblyTitle("BouncyCastle.Crypto")]
+[assembly: AssemblyDescription("Bouncy Castle Cryptography API")]
+#endif
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("The Legion of the Bouncy Castle")]
+[assembly: AssemblyProduct("Bouncy Castle for .NET")]
+[assembly: AssemblyCopyright("Copyright (C) 2000-2011")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+//
+// Version information for an assembly consists of the following four values:
+//
+// Major Version
+// Minor Version
+// Build Number
+// Revision
+
+[assembly: AssemblyVersion(AssemblyInfo.Version)]
+
+//
+// In order to sign your assembly you must specify a key to use. Refer to the
+// Microsoft .NET Framework documentation for more information on assembly signing.
+//
+// Use the attributes below to control which key is used for signing.
+//
+// Notes:
+// (*) If no key is specified, the assembly is not signed.
+// (*) KeyName refers to a key that has been installed in the Crypto Service
+// Provider (CSP) on your machine. KeyFile refers to a file which contains
+// a key.
+// (*) If the KeyFile and the KeyName values are both specified, the
+// following processing occurs:
+// (1) If the KeyName can be found in the CSP, that key is used.
+// (2) If the KeyName does not exist and the KeyFile does exist, the key
+// in the KeyFile is installed into the CSP and used.
+// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
+// When specifying the KeyFile, the location of the KeyFile should be
+// relative to the project output directory which is
+// %Project Directory%\obj\. For example, if your KeyFile is
+// located in the project directory, you would specify the AssemblyKeyFile
+// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
+// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
+// documentation for more information on this.
+//
+[assembly: AssemblyDelaySign(false)]
+#if STRONG_NAME
+[assembly: AssemblyKeyFile(@"../BouncyCastle.snk")]
+#else
+[assembly: AssemblyKeyFile("")]
+#endif
+[assembly: AssemblyKeyName("")]
+
+[assembly: CLSCompliant(true)]
+
+// Start with no permissions
+//[assembly: PermissionSet(SecurityAction.RequestOptional, Unrestricted=false)]
+//...and explicitly add those we need
+
+// see Org.BouncyCastle.Crypto.Encodings.Pkcs1Encoding.StrictLengthEnabledProperty
+//[assembly: EnvironmentPermission(SecurityAction.RequestOptional, Read="Org.BouncyCastle.Pkcs1.Strict")]
+
+internal class AssemblyInfo
+{
+ public const string Version = @"1.7.0.0";
+}
+
diff --git a/Crypto/src/asn1/ASN1Generator.cs b/Crypto/src/asn1/ASN1Generator.cs
new file mode 100644
index 000000000..e56051736
--- /dev/null
+++ b/Crypto/src/asn1/ASN1Generator.cs
@@ -0,0 +1,27 @@
+using System.Collections;
+using System.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public abstract class Asn1Generator
+ {
+ private Stream _out;
+
+ protected Asn1Generator(
+ Stream outStream)
+ {
+ _out = outStream;
+ }
+
+ protected Stream Out
+ {
+ get { return _out; }
+ }
+
+ public abstract void AddObject(Asn1Encodable obj);
+
+ public abstract Stream GetRawOutputStream();
+
+ public abstract void Close();
+ }
+}
diff --git a/Crypto/src/asn1/ASN1OctetStringParser.cs b/Crypto/src/asn1/ASN1OctetStringParser.cs
new file mode 100644
index 000000000..5815aa42f
--- /dev/null
+++ b/Crypto/src/asn1/ASN1OctetStringParser.cs
@@ -0,0 +1,10 @@
+using System.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public interface Asn1OctetStringParser
+ : IAsn1Convertible
+ {
+ Stream GetOctetStream();
+ }
+}
diff --git a/Crypto/src/asn1/ASN1SequenceParser.cs b/Crypto/src/asn1/ASN1SequenceParser.cs
new file mode 100644
index 000000000..9e88ac788
--- /dev/null
+++ b/Crypto/src/asn1/ASN1SequenceParser.cs
@@ -0,0 +1,8 @@
+namespace Org.BouncyCastle.Asn1
+{
+ public interface Asn1SequenceParser
+ : IAsn1Convertible
+ {
+ IAsn1Convertible ReadObject();
+ }
+}
diff --git a/Crypto/src/asn1/ASN1SetParser.cs b/Crypto/src/asn1/ASN1SetParser.cs
new file mode 100644
index 000000000..d1b9c64e2
--- /dev/null
+++ b/Crypto/src/asn1/ASN1SetParser.cs
@@ -0,0 +1,8 @@
+namespace Org.BouncyCastle.Asn1
+{
+ public interface Asn1SetParser
+ : IAsn1Convertible
+ {
+ IAsn1Convertible ReadObject();
+ }
+}
diff --git a/Crypto/src/asn1/ASN1StreamParser.cs b/Crypto/src/asn1/ASN1StreamParser.cs
new file mode 100644
index 000000000..6c256db53
--- /dev/null
+++ b/Crypto/src/asn1/ASN1StreamParser.cs
@@ -0,0 +1,232 @@
+using System;
+using System.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class Asn1StreamParser
+ {
+ private readonly Stream _in;
+ private readonly int _limit;
+
+ public Asn1StreamParser(
+ Stream inStream)
+ : this(inStream, Asn1InputStream.FindLimit(inStream))
+ {
+ }
+
+ public Asn1StreamParser(
+ Stream inStream,
+ int limit)
+ {
+ if (!inStream.CanRead)
+ throw new ArgumentException("Expected stream to be readable", "inStream");
+
+ this._in = inStream;
+ this._limit = limit;
+ }
+
+ public Asn1StreamParser(
+ byte[] encoding)
+ : this(new MemoryStream(encoding, false), encoding.Length)
+ {
+ }
+
+ internal IAsn1Convertible ReadIndef(int tagValue)
+ {
+ // Note: INDEF => CONSTRUCTED
+
+ // TODO There are other tags that may be constructed (e.g. BIT_STRING)
+ switch (tagValue)
+ {
+ case Asn1Tags.External:
+ return new DerExternalParser(this);
+ case Asn1Tags.OctetString:
+ return new BerOctetStringParser(this);
+ case Asn1Tags.Sequence:
+ return new BerSequenceParser(this);
+ case Asn1Tags.Set:
+ return new BerSetParser(this);
+ default:
+ throw new Asn1Exception("unknown BER object encountered: 0x" + tagValue.ToString("X"));
+ }
+ }
+
+ internal IAsn1Convertible ReadImplicit(bool constructed, int tag)
+ {
+ if (_in is IndefiniteLengthInputStream)
+ {
+ if (!constructed)
+ throw new IOException("indefinite length primitive encoding encountered");
+
+ return ReadIndef(tag);
+ }
+
+ if (constructed)
+ {
+ switch (tag)
+ {
+ case Asn1Tags.Set:
+ return new DerSetParser(this);
+ case Asn1Tags.Sequence:
+ return new DerSequenceParser(this);
+ case Asn1Tags.OctetString:
+ return new BerOctetStringParser(this);
+ }
+ }
+ else
+ {
+ switch (tag)
+ {
+ case Asn1Tags.Set:
+ throw new Asn1Exception("sequences must use constructed encoding (see X.690 8.9.1/8.10.1)");
+ case Asn1Tags.Sequence:
+ throw new Asn1Exception("sets must use constructed encoding (see X.690 8.11.1/8.12.1)");
+ case Asn1Tags.OctetString:
+ return new DerOctetStringParser((DefiniteLengthInputStream)_in);
+ }
+ }
+
+ throw new Asn1Exception("implicit tagging not implemented");
+ }
+
+ internal Asn1Object ReadTaggedObject(bool constructed, int tag)
+ {
+ if (!constructed)
+ {
+ // Note: !CONSTRUCTED => IMPLICIT
+ DefiniteLengthInputStream defIn = (DefiniteLengthInputStream)_in;
+ return new DerTaggedObject(false, tag, new DerOctetString(defIn.ToArray()));
+ }
+
+ Asn1EncodableVector v = ReadVector();
+
+ if (_in is IndefiniteLengthInputStream)
+ {
+ return v.Count == 1
+ ? new BerTaggedObject(true, tag, v[0])
+ : new BerTaggedObject(false, tag, BerSequence.FromVector(v));
+ }
+
+ return v.Count == 1
+ ? new DerTaggedObject(true, tag, v[0])
+ : new DerTaggedObject(false, tag, DerSequence.FromVector(v));
+ }
+
+ public virtual IAsn1Convertible ReadObject()
+ {
+ int tag = _in.ReadByte();
+ 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);
+
+ bool isConstructed = (tag & Asn1Tags.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 & Asn1Tags.Application) != 0)
+ {
+ return new BerApplicationSpecificParser(tagNo, sp);
+ }
+
+ if ((tag & Asn1Tags.Tagged) != 0)
+ {
+ return new BerTaggedObjectParser(true, tagNo, sp);
+ }
+
+ return sp.ReadIndef(tagNo);
+ }
+ else
+ {
+ DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(_in, length);
+
+ if ((tag & Asn1Tags.Application) != 0)
+ {
+ return new DerApplicationSpecific(isConstructed, tagNo, defIn.ToArray());
+ }
+
+ if ((tag & Asn1Tags.Tagged) != 0)
+ {
+ return new BerTaggedObjectParser(isConstructed, tagNo, new Asn1StreamParser(defIn));
+ }
+
+ if (isConstructed)
+ {
+ // TODO There are other tags that may be constructed (e.g. BitString)
+ switch (tagNo)
+ {
+ case Asn1Tags.OctetString:
+ //
+ // yes, people actually do this...
+ //
+ return new BerOctetStringParser(new Asn1StreamParser(defIn));
+ case Asn1Tags.Sequence:
+ return new DerSequenceParser(new Asn1StreamParser(defIn));
+ case Asn1Tags.Set:
+ return new DerSetParser(new Asn1StreamParser(defIn));
+ case Asn1Tags.External:
+ return new DerExternalParser(new Asn1StreamParser(defIn));
+ default:
+ // TODO Add DerUnknownTagParser class?
+ return new DerUnknownTag(true, tagNo, defIn.ToArray());
+ }
+ }
+
+ // Some primitive encodings can be handled by parsers too...
+ switch (tagNo)
+ {
+ case Asn1Tags.OctetString:
+ return new DerOctetStringParser(defIn);
+ }
+
+ try
+ {
+ return Asn1InputStream.CreatePrimitiveDerObject(tagNo, defIn.ToArray());
+ }
+ catch (ArgumentException e)
+ {
+ throw new Asn1Exception("corrupted stream detected", e);
+ }
+ }
+ }
+
+ private void Set00Check(
+ bool enabled)
+ {
+ if (_in is IndefiniteLengthInputStream)
+ {
+ ((IndefiniteLengthInputStream) _in).SetEofOn00(enabled);
+ }
+ }
+
+ internal Asn1EncodableVector ReadVector()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+
+ IAsn1Convertible obj;
+ while ((obj = ReadObject()) != null)
+ {
+ v.Add(obj.ToAsn1Object());
+ }
+
+ return v;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/ASN1TaggedObjectParser.cs b/Crypto/src/asn1/ASN1TaggedObjectParser.cs
new file mode 100644
index 000000000..32327a269
--- /dev/null
+++ b/Crypto/src/asn1/ASN1TaggedObjectParser.cs
@@ -0,0 +1,10 @@
+namespace Org.BouncyCastle.Asn1
+{
+ public interface Asn1TaggedObjectParser
+ : IAsn1Convertible
+ {
+ int TagNo { get; }
+
+ IAsn1Convertible GetObjectParser(int tag, bool isExplicit);
+ }
+}
diff --git a/Crypto/src/asn1/Asn1Encodable.cs b/Crypto/src/asn1/Asn1Encodable.cs
new file mode 100644
index 000000000..e3dd9a14c
--- /dev/null
+++ b/Crypto/src/asn1/Asn1Encodable.cs
@@ -0,0 +1,78 @@
+using System.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public abstract class Asn1Encodable
+ : IAsn1Convertible
+ {
+ public const string Der = "DER";
+ public const string Ber = "BER";
+
+ public byte[] GetEncoded()
+ {
+ MemoryStream bOut = new MemoryStream();
+ Asn1OutputStream aOut = new Asn1OutputStream(bOut);
+
+ aOut.WriteObject(this);
+
+ return bOut.ToArray();
+ }
+
+ public byte[] GetEncoded(
+ string encoding)
+ {
+ if (encoding.Equals(Der))
+ {
+ MemoryStream bOut = new MemoryStream();
+ DerOutputStream dOut = new DerOutputStream(bOut);
+
+ dOut.WriteObject(this);
+
+ return bOut.ToArray();
+ }
+
+ return GetEncoded();
+ }
+
+ /**
+ * Return the DER encoding of the object, null if the DER encoding can not be made.
+ *
+ * @return a DER byte array, null otherwise.
+ */
+ public byte[] GetDerEncoded()
+ {
+ try
+ {
+ return GetEncoded(Der);
+ }
+ catch (IOException)
+ {
+ return null;
+ }
+ }
+
+ public sealed override int GetHashCode()
+ {
+ return ToAsn1Object().CallAsn1GetHashCode();
+ }
+
+ public sealed override bool Equals(
+ object obj)
+ {
+ if (obj == this)
+ return true;
+
+ IAsn1Convertible other = obj as IAsn1Convertible;
+
+ if (other == null)
+ return false;
+
+ Asn1Object o1 = ToAsn1Object();
+ Asn1Object o2 = other.ToAsn1Object();
+
+ return o1 == o2 || o1.CallAsn1Equals(o2);
+ }
+
+ public abstract Asn1Object ToAsn1Object();
+ }
+}
diff --git a/Crypto/src/asn1/Asn1EncodableVector.cs b/Crypto/src/asn1/Asn1EncodableVector.cs
new file mode 100644
index 000000000..49532fe57
--- /dev/null
+++ b/Crypto/src/asn1/Asn1EncodableVector.cs
@@ -0,0 +1,93 @@
+using System;
+using System.Collections;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class Asn1EncodableVector
+ : IEnumerable
+ {
+ private IList v = Platform.CreateArrayList();
+
+ public static Asn1EncodableVector FromEnumerable(
+ IEnumerable e)
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+ foreach (Asn1Encodable obj in e)
+ {
+ v.Add(obj);
+ }
+ return v;
+ }
+
+// public Asn1EncodableVector()
+// {
+// }
+
+ public Asn1EncodableVector(
+ params Asn1Encodable[] v)
+ {
+ Add(v);
+ }
+
+// public void Add(
+// Asn1Encodable obj)
+// {
+// v.Add(obj);
+// }
+
+ public void Add(
+ params Asn1Encodable[] objs)
+ {
+ foreach (Asn1Encodable obj in objs)
+ {
+ v.Add(obj);
+ }
+ }
+
+ public void AddOptional(
+ params Asn1Encodable[] objs)
+ {
+ if (objs != null)
+ {
+ foreach (Asn1Encodable obj in objs)
+ {
+ if (obj != null)
+ {
+ v.Add(obj);
+ }
+ }
+ }
+ }
+
+ public Asn1Encodable this[
+ int index]
+ {
+ get { return (Asn1Encodable) v[index]; }
+ }
+
+ [Obsolete("Use 'object[index]' syntax instead")]
+ public Asn1Encodable Get(
+ int index)
+ {
+ return this[index];
+ }
+
+ [Obsolete("Use 'Count' property instead")]
+ public int Size
+ {
+ get { return v.Count; }
+ }
+
+ public int Count
+ {
+ get { return v.Count; }
+ }
+
+ public IEnumerator GetEnumerator()
+ {
+ return v.GetEnumerator();
+ }
+ }
+}
diff --git a/Crypto/src/asn1/Asn1Exception.cs b/Crypto/src/asn1/Asn1Exception.cs
new file mode 100644
index 000000000..dfc1641a4
--- /dev/null
+++ b/Crypto/src/asn1/Asn1Exception.cs
@@ -0,0 +1,27 @@
+using System;
+using System.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class Asn1Exception
+ : IOException
+ {
+ public Asn1Exception()
+ : base()
+ {
+ }
+
+ public Asn1Exception(
+ string message)
+ : base(message)
+ {
+ }
+
+ public Asn1Exception(
+ string message,
+ Exception exception)
+ : base(message, exception)
+ {
+ }
+ }
+}
diff --git a/Crypto/src/asn1/Asn1InputStream.cs b/Crypto/src/asn1/Asn1InputStream.cs
new file mode 100644
index 000000000..9a9761653
--- /dev/null
+++ b/Crypto/src/asn1/Asn1InputStream.cs
@@ -0,0 +1,339 @@
+using System;
+using System.Diagnostics;
+using System.IO;
+
+using Org.BouncyCastle.Asn1.Utilities;
+using Org.BouncyCastle.Utilities.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * 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
+ : FilterStream
+ {
+ private readonly int limit;
+
+ internal static int FindLimit(Stream input)
+ {
+ if (input is LimitedInputStream)
+ {
+ return ((LimitedInputStream)input).GetRemaining();
+ }
+ else if (input is MemoryStream)
+ {
+ MemoryStream mem = (MemoryStream)input;
+ return (int)(mem.Length - mem.Position);
+ }
+
+ return int.MaxValue;
+ }
+
+ public Asn1InputStream(
+ Stream inputStream)
+ : this(inputStream, FindLimit(inputStream))
+ {
+ }
+
+ /**
+ * 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(
+ Stream inputStream,
+ int limit)
+ : base(inputStream)
+ {
+ this.limit = limit;
+ }
+
+ /**
+ * 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 MemoryStream(input, false), input.Length)
+ {
+ }
+
+ /**
+ * build an object given its tag and the number of bytes to construct it from.
+ */
+ private Asn1Object BuildObject(
+ int tag,
+ int tagNo,
+ int length)
+ {
+ bool isConstructed = (tag & Asn1Tags.Constructed) != 0;
+
+ DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(this.s, length);
+
+ if ((tag & Asn1Tags.Application) != 0)
+ {
+ return new DerApplicationSpecific(isConstructed, tagNo, defIn.ToArray());
+ }
+
+ if ((tag & Asn1Tags.Tagged) != 0)
+ {
+ return new Asn1StreamParser(defIn).ReadTaggedObject(isConstructed, tagNo);
+ }
+
+ if (isConstructed)
+ {
+ // TODO There are other tags that may be constructed (e.g. BitString)
+ switch (tagNo)
+ {
+ case Asn1Tags.OctetString:
+ //
+ // yes, people actually do this...
+ //
+ return new BerOctetString(BuildDerEncodableVector(defIn));
+ case Asn1Tags.Sequence:
+ return CreateDerSequence(defIn);
+ case Asn1Tags.Set:
+ return CreateDerSet(defIn);
+ case Asn1Tags.External:
+ return new DerExternal(BuildDerEncodableVector(defIn));
+ default:
+ return new DerUnknownTag(true, tagNo, defIn.ToArray());
+ }
+ }
+
+ return CreatePrimitiveDerObject(tagNo, defIn.ToArray());
+ }
+
+ internal Asn1EncodableVector BuildEncodableVector()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+
+ Asn1Object o;
+ while ((o = ReadObject()) != null)
+ {
+ v.Add(o);
+ }
+
+ return v;
+ }
+
+ internal virtual Asn1EncodableVector BuildDerEncodableVector(
+ DefiniteLengthInputStream dIn)
+ {
+ return new Asn1InputStream(dIn).BuildEncodableVector();
+ }
+
+ internal virtual DerSequence CreateDerSequence(
+ DefiniteLengthInputStream dIn)
+ {
+ return DerSequence.FromVector(BuildDerEncodableVector(dIn));
+ }
+
+ internal virtual DerSet CreateDerSet(
+ DefiniteLengthInputStream dIn)
+ {
+ return DerSet.FromVector(BuildDerEncodableVector(dIn), false);
+ }
+
+ public Asn1Object ReadObject()
+ {
+ int tag = ReadByte();
+ if (tag <= 0)
+ {
+ if (tag == 0)
+ throw new IOException("unexpected end-of-contents marker");
+
+ return null;
+ }
+
+ //
+ // calculate tag number
+ //
+ int tagNo = ReadTagNumber(this.s, tag);
+
+ bool isConstructed = (tag & Asn1Tags.Constructed) != 0;
+
+ //
+ // calculate length
+ //
+ int length = ReadLength(this.s, limit);
+
+ if (length < 0) // indefinite length method
+ {
+ if (!isConstructed)
+ throw new IOException("indefinite length primitive encoding encountered");
+
+ IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(this.s, limit);
+ Asn1StreamParser sp = new Asn1StreamParser(indIn, limit);
+
+ if ((tag & Asn1Tags.Application) != 0)
+ {
+ return new BerApplicationSpecificParser(tagNo, sp).ToAsn1Object();
+ }
+
+ if ((tag & Asn1Tags.Tagged) != 0)
+ {
+ return new BerTaggedObjectParser(true, tagNo, sp).ToAsn1Object();
+ }
+
+ // TODO There are other tags that may be constructed (e.g. BitString)
+ switch (tagNo)
+ {
+ case Asn1Tags.OctetString:
+ return new BerOctetStringParser(sp).ToAsn1Object();
+ case Asn1Tags.Sequence:
+ return new BerSequenceParser(sp).ToAsn1Object();
+ case Asn1Tags.Set:
+ return new BerSetParser(sp).ToAsn1Object();
+ case Asn1Tags.External:
+ return new DerExternalParser(sp).ToAsn1Object();
+ default:
+ throw new IOException("unknown BER object encountered");
+ }
+ }
+ else
+ {
+ try
+ {
+ return BuildObject(tag, tagNo, length);
+ }
+ catch (ArgumentException e)
+ {
+ throw new Asn1Exception("corrupted stream detected", e);
+ }
+ }
+ }
+
+ internal static int ReadTagNumber(
+ Stream s,
+ int tag)
+ {
+ 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.ReadByte();
+
+ // 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.ReadByte();
+ }
+
+ if (b < 0)
+ throw new EndOfStreamException("EOF found inside tag value.");
+
+ tagNo |= (b & 0x7f);
+ }
+
+ return tagNo;
+ }
+
+ internal static int ReadLength(
+ Stream s,
+ int limit)
+ {
+ int length = s.ReadByte();
+ if (length < 0)
+ throw new EndOfStreamException("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.ReadByte();
+
+ if (next < 0)
+ throw new EndOfStreamException("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;
+ }
+
+ internal static Asn1Object CreatePrimitiveDerObject(
+ int tagNo,
+ byte[] bytes)
+ {
+ switch (tagNo)
+ {
+ case Asn1Tags.BitString:
+ return DerBitString.FromAsn1Octets(bytes);
+ case Asn1Tags.BmpString:
+ return new DerBmpString(bytes);
+ case Asn1Tags.Boolean:
+ return new DerBoolean(bytes);
+ case Asn1Tags.Enumerated:
+ return new DerEnumerated(bytes);
+ case Asn1Tags.GeneralizedTime:
+ return new DerGeneralizedTime(bytes);
+ case Asn1Tags.GeneralString:
+ return new DerGeneralString(bytes);
+ case Asn1Tags.IA5String:
+ return new DerIA5String(bytes);
+ case Asn1Tags.Integer:
+ return new DerInteger(bytes);
+ case Asn1Tags.Null:
+ return DerNull.Instance; // actual content is ignored (enforce 0 length?)
+ case Asn1Tags.NumericString:
+ return new DerNumericString(bytes);
+ case Asn1Tags.ObjectIdentifier:
+ return new DerObjectIdentifier(bytes);
+ case Asn1Tags.OctetString:
+ return new DerOctetString(bytes);
+ case Asn1Tags.PrintableString:
+ return new DerPrintableString(bytes);
+ case Asn1Tags.T61String:
+ return new DerT61String(bytes);
+ case Asn1Tags.UniversalString:
+ return new DerUniversalString(bytes);
+ case Asn1Tags.UtcTime:
+ return new DerUtcTime(bytes);
+ case Asn1Tags.Utf8String:
+ return new DerUtf8String(bytes);
+ case Asn1Tags.VisibleString:
+ return new DerVisibleString(bytes);
+ default:
+ return new DerUnknownTag(false, tagNo, bytes);
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/Asn1Null.cs b/Crypto/src/asn1/Asn1Null.cs
new file mode 100644
index 000000000..d54019f67
--- /dev/null
+++ b/Crypto/src/asn1/Asn1Null.cs
@@ -0,0 +1,18 @@
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * A Null object.
+ */
+ public abstract class Asn1Null
+ : Asn1Object
+ {
+ internal Asn1Null()
+ {
+ }
+
+ public override string ToString()
+ {
+ return "NULL";
+ }
+ }
+}
diff --git a/Crypto/src/asn1/Asn1Object.cs b/Crypto/src/asn1/Asn1Object.cs
new file mode 100644
index 000000000..08bd599c1
--- /dev/null
+++ b/Crypto/src/asn1/Asn1Object.cs
@@ -0,0 +1,63 @@
+using System;
+using System.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public abstract class Asn1Object
+ : Asn1Encodable
+ {
+ /// Create a base ASN.1 object from a byte array.
+ /// The byte array to parse.
+ /// The base ASN.1 object represented by the byte array.
+ /// If there is a problem parsing the data.
+ public static Asn1Object FromByteArray(
+ byte[] data)
+ {
+ try
+ {
+ return new Asn1InputStream(data).ReadObject();
+ }
+ catch (InvalidCastException)
+ {
+ throw new IOException("cannot recognise object in stream");
+ }
+ }
+
+ /// Read a base ASN.1 object from a stream.
+ /// The stream to parse.
+ /// The base ASN.1 object represented by the byte array.
+ /// If there is a problem parsing the data.
+ public static Asn1Object FromStream(
+ Stream inStr)
+ {
+ try
+ {
+ return new Asn1InputStream(inStr).ReadObject();
+ }
+ catch (InvalidCastException)
+ {
+ throw new IOException("cannot recognise object in stream");
+ }
+ }
+
+ public sealed override Asn1Object ToAsn1Object()
+ {
+ return this;
+ }
+
+ internal abstract void Encode(DerOutputStream derOut);
+
+ protected abstract bool Asn1Equals(Asn1Object asn1Object);
+ protected abstract int Asn1GetHashCode();
+
+ internal bool CallAsn1Equals(Asn1Object obj)
+ {
+ return Asn1Equals(obj);
+ }
+
+ internal int CallAsn1GetHashCode()
+ {
+ return Asn1GetHashCode();
+ }
+ }
+}
diff --git a/Crypto/src/asn1/Asn1OctetString.cs b/Crypto/src/asn1/Asn1OctetString.cs
new file mode 100644
index 000000000..9c738a8f2
--- /dev/null
+++ b/Crypto/src/asn1/Asn1OctetString.cs
@@ -0,0 +1,119 @@
+using System;
+using System.Collections;
+using System.IO;
+
+using Org.BouncyCastle.Utilities;
+using Org.BouncyCastle.Utilities.Encoders;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public abstract class Asn1OctetString
+ : Asn1Object, Asn1OctetStringParser
+ {
+ internal byte[] str;
+
+ /**
+ * return an Octet string from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want.
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static Asn1OctetString GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is Asn1OctetString)
+ {
+ return GetInstance(o);
+ }
+
+ return BerOctetString.FromSequence(Asn1Sequence.GetInstance(o));
+ }
+
+ /**
+ * return an Octet string from the given object.
+ *
+ * @param obj the object we want converted.
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static Asn1OctetString GetInstance(object obj)
+ {
+ if (obj == null || obj is Asn1OctetString)
+ {
+ return (Asn1OctetString)obj;
+ }
+
+ // TODO: this needs to be deleted in V2
+ if (obj is Asn1TaggedObject)
+ return GetInstance(((Asn1TaggedObject)obj).GetObject());
+
+ throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name);
+ }
+
+ /**
+ * @param string the octets making up the octet string.
+ */
+ internal Asn1OctetString(
+ byte[] str)
+ {
+ if (str == null)
+ throw new ArgumentNullException("str");
+
+ this.str = str;
+ }
+
+ internal Asn1OctetString(
+ Asn1Encodable obj)
+ {
+ try
+ {
+ this.str = obj.GetEncoded(Asn1Encodable.Der);
+ }
+ catch (IOException e)
+ {
+ throw new ArgumentException("Error processing object : " + e.ToString());
+ }
+ }
+
+ public Stream GetOctetStream()
+ {
+ return new MemoryStream(str, false);
+ }
+
+ public Asn1OctetStringParser Parser
+ {
+ get { return this; }
+ }
+
+ public virtual byte[] GetOctets()
+ {
+ return str;
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return Arrays.GetHashCode(GetOctets());
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerOctetString other = asn1Object as DerOctetString;
+
+ if (other == null)
+ return false;
+
+ return Arrays.AreEqual(GetOctets(), other.GetOctets());
+ }
+
+ public override string ToString()
+ {
+ return "#" + Hex.ToHexString(str);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/Asn1OutputStream.cs b/Crypto/src/asn1/Asn1OutputStream.cs
new file mode 100644
index 000000000..39c8b1e5e
--- /dev/null
+++ b/Crypto/src/asn1/Asn1OutputStream.cs
@@ -0,0 +1,35 @@
+using System;
+using System.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class Asn1OutputStream
+ : DerOutputStream
+ {
+ public Asn1OutputStream(Stream os) : base(os)
+ {
+ }
+
+ [Obsolete("Use version taking an Asn1Encodable arg instead")]
+ public override void WriteObject(
+ object obj)
+ {
+ if (obj == null)
+ {
+ WriteNull();
+ }
+ else if (obj is Asn1Object)
+ {
+ ((Asn1Object)obj).Encode(this);
+ }
+ else if (obj is Asn1Encodable)
+ {
+ ((Asn1Encodable)obj).ToAsn1Object().Encode(this);
+ }
+ else
+ {
+ throw new IOException("object not Asn1Encodable");
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/Asn1ParsingException.cs b/Crypto/src/asn1/Asn1ParsingException.cs
new file mode 100644
index 000000000..8827d8329
--- /dev/null
+++ b/Crypto/src/asn1/Asn1ParsingException.cs
@@ -0,0 +1,26 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class Asn1ParsingException
+ : InvalidOperationException
+ {
+ public Asn1ParsingException()
+ : base()
+ {
+ }
+
+ public Asn1ParsingException(
+ string message)
+ : base(message)
+ {
+ }
+
+ public Asn1ParsingException(
+ string message,
+ Exception exception)
+ : base(message, exception)
+ {
+ }
+ }
+}
diff --git a/Crypto/src/asn1/Asn1Sequence.cs b/Crypto/src/asn1/Asn1Sequence.cs
new file mode 100644
index 000000000..3131ead84
--- /dev/null
+++ b/Crypto/src/asn1/Asn1Sequence.cs
@@ -0,0 +1,255 @@
+using System;
+using System.Collections;
+using System.IO;
+
+using Org.BouncyCastle.Utilities;
+using Org.BouncyCastle.Utilities.Collections;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public abstract class Asn1Sequence
+ : Asn1Object, IEnumerable
+ {
+ private readonly IList seq;
+
+ /**
+ * return an Asn1Sequence from the given object.
+ *
+ * @param obj the object we want converted.
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static Asn1Sequence GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is Asn1Sequence)
+ {
+ return (Asn1Sequence)obj;
+ }
+ else if (obj is byte[])
+ {
+ try
+ {
+ return Asn1Sequence.GetInstance(Asn1Object.FromByteArray((byte[])obj));
+ }
+ catch (IOException e)
+ {
+ throw new ArgumentException("Failed to construct sequence from byte[]", e);
+ }
+ }
+
+ throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj");
+ }
+
+ /**
+ * Return an ASN1 sequence from a tagged object. There is a special
+ * case here, if an object appears to have been explicitly tagged on
+ * reading but we were expecting it to be implicitly tagged in the
+ * normal course of events it indicates that we lost the surrounding
+ * sequence - so we need to add it back (this will happen if the tagged
+ * object is a sequence that contains other sequences). If you are
+ * dealing with implicitly tagged sequences you really should
+ * be using this method.
+ *
+ * @param obj the tagged object.
+ * @param explicitly true if the object is meant to be explicitly tagged,
+ * false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static Asn1Sequence GetInstance(
+ Asn1TaggedObject obj,
+ bool explicitly)
+ {
+ Asn1Object inner = obj.GetObject();
+
+ if (explicitly)
+ {
+ if (!obj.IsExplicit())
+ throw new ArgumentException("object implicit - explicit expected.");
+
+ return (Asn1Sequence) inner;
+ }
+
+ //
+ // constructed object which appears to be explicitly tagged
+ // when it should be implicit means we have to add the
+ // surrounding sequence.
+ //
+ if (obj.IsExplicit())
+ {
+ if (obj is BerTaggedObject)
+ {
+ return new BerSequence(inner);
+ }
+
+ return new DerSequence(inner);
+ }
+
+ if (inner is Asn1Sequence)
+ {
+ return (Asn1Sequence) inner;
+ }
+
+ throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj");
+ }
+
+ protected internal Asn1Sequence(
+ int capacity)
+ {
+ seq = Platform.CreateArrayList(capacity);
+ }
+
+ public virtual IEnumerator GetEnumerator()
+ {
+ return seq.GetEnumerator();
+ }
+
+ [Obsolete("Use GetEnumerator() instead")]
+ public IEnumerator GetObjects()
+ {
+ return GetEnumerator();
+ }
+
+ private class Asn1SequenceParserImpl
+ : Asn1SequenceParser
+ {
+ private readonly Asn1Sequence outer;
+ private readonly int max;
+ private int index;
+
+ public Asn1SequenceParserImpl(
+ Asn1Sequence outer)
+ {
+ this.outer = outer;
+ this.max = outer.Count;
+ }
+
+ public IAsn1Convertible ReadObject()
+ {
+ if (index == max)
+ return null;
+
+ Asn1Encodable obj = outer[index++];
+
+ if (obj is Asn1Sequence)
+ return ((Asn1Sequence)obj).Parser;
+
+ if (obj is Asn1Set)
+ return ((Asn1Set)obj).Parser;
+
+ // NB: Asn1OctetString implements Asn1OctetStringParser directly
+// if (obj is Asn1OctetString)
+// return ((Asn1OctetString)obj).Parser;
+
+ return obj;
+ }
+
+ public Asn1Object ToAsn1Object()
+ {
+ return outer;
+ }
+ }
+
+ public virtual Asn1SequenceParser Parser
+ {
+ get { return new Asn1SequenceParserImpl(this); }
+ }
+
+ /**
+ * return the object at the sequence position indicated by index.
+ *
+ * @param index the sequence number (starting at zero) of the object
+ * @return the object at the sequence position indicated by index.
+ */
+ public virtual Asn1Encodable this[int index]
+ {
+ get { return (Asn1Encodable) seq[index]; }
+ }
+
+ [Obsolete("Use 'object[index]' syntax instead")]
+ public Asn1Encodable GetObjectAt(
+ int index)
+ {
+ return this[index];
+ }
+
+ [Obsolete("Use 'Count' property instead")]
+ public int Size
+ {
+ get { return Count; }
+ }
+
+ public virtual int Count
+ {
+ get { return seq.Count; }
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ int hc = Count;
+
+ foreach (object o in this)
+ {
+ hc *= 17;
+ if (o == null)
+ {
+ hc ^= DerNull.Instance.GetHashCode();
+ }
+ else
+ {
+ hc ^= o.GetHashCode();
+ }
+ }
+
+ return hc;
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ Asn1Sequence other = asn1Object as Asn1Sequence;
+
+ if (other == null)
+ return false;
+
+ if (Count != other.Count)
+ return false;
+
+ IEnumerator s1 = GetEnumerator();
+ IEnumerator s2 = other.GetEnumerator();
+
+ while (s1.MoveNext() && s2.MoveNext())
+ {
+ Asn1Object o1 = GetCurrent(s1).ToAsn1Object();
+ Asn1Object o2 = GetCurrent(s2).ToAsn1Object();
+
+ if (!o1.Equals(o2))
+ return false;
+ }
+
+ return true;
+ }
+
+ private Asn1Encodable GetCurrent(IEnumerator e)
+ {
+ Asn1Encodable encObj = (Asn1Encodable)e.Current;
+
+ // unfortunately null was allowed as a substitute for DER null
+ if (encObj == null)
+ return DerNull.Instance;
+
+ return encObj;
+ }
+
+ protected internal void AddObject(
+ Asn1Encodable obj)
+ {
+ seq.Add(obj);
+ }
+
+ public override string ToString()
+ {
+ return CollectionUtilities.ToString(seq);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/Asn1Set.cs b/Crypto/src/asn1/Asn1Set.cs
new file mode 100644
index 000000000..f5b66495c
--- /dev/null
+++ b/Crypto/src/asn1/Asn1Set.cs
@@ -0,0 +1,326 @@
+using System;
+using System.Collections;
+
+using Org.BouncyCastle.Utilities;
+using Org.BouncyCastle.Utilities.Collections;
+
+namespace Org.BouncyCastle.Asn1
+{
+ abstract public class Asn1Set
+ : Asn1Object, IEnumerable
+ {
+ private readonly IList _set;
+
+ /**
+ * return an ASN1Set from the given object.
+ *
+ * @param obj the object we want converted.
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static Asn1Set GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is Asn1Set)
+ {
+ return (Asn1Set)obj;
+ }
+
+ throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj");
+ }
+
+ /**
+ * Return an ASN1 set from a tagged object. There is a special
+ * case here, if an object appears to have been explicitly tagged on
+ * reading but we were expecting it to be implicitly tagged in the
+ * normal course of events it indicates that we lost the surrounding
+ * set - so we need to add it back (this will happen if the tagged
+ * object is a sequence that contains other sequences). If you are
+ * dealing with implicitly tagged sets you really should
+ * be using this method.
+ *
+ * @param obj the tagged object.
+ * @param explicitly true if the object is meant to be explicitly tagged
+ * false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static Asn1Set GetInstance(
+ Asn1TaggedObject obj,
+ bool explicitly)
+ {
+ Asn1Object inner = obj.GetObject();
+
+ if (explicitly)
+ {
+ if (!obj.IsExplicit())
+ throw new ArgumentException("object implicit - explicit expected.");
+
+ return (Asn1Set) inner;
+ }
+
+ //
+ // constructed object which appears to be explicitly tagged
+ // and it's really implicit means we have to add the
+ // surrounding sequence.
+ //
+ if (obj.IsExplicit())
+ {
+ return new DerSet(inner);
+ }
+
+ if (inner is Asn1Set)
+ {
+ return (Asn1Set) inner;
+ }
+
+ //
+ // in this case the parser returns a sequence, convert it
+ // into a set.
+ //
+ if (inner is Asn1Sequence)
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+ Asn1Sequence s = (Asn1Sequence) inner;
+
+ foreach (Asn1Encodable ae in s)
+ {
+ v.Add(ae);
+ }
+
+ // TODO Should be able to construct set directly from sequence?
+ return new DerSet(v, false);
+ }
+
+ throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj");
+ }
+
+ protected internal Asn1Set(
+ int capacity)
+ {
+ _set = Platform.CreateArrayList(capacity);
+ }
+
+ public virtual IEnumerator GetEnumerator()
+ {
+ return _set.GetEnumerator();
+ }
+
+ [Obsolete("Use GetEnumerator() instead")]
+ public IEnumerator GetObjects()
+ {
+ return GetEnumerator();
+ }
+
+ /**
+ * return the object at the set position indicated by index.
+ *
+ * @param index the set number (starting at zero) of the object
+ * @return the object at the set position indicated by index.
+ */
+ public virtual Asn1Encodable this[int index]
+ {
+ get { return (Asn1Encodable) _set[index]; }
+ }
+
+ [Obsolete("Use 'object[index]' syntax instead")]
+ public Asn1Encodable GetObjectAt(
+ int index)
+ {
+ return this[index];
+ }
+
+ [Obsolete("Use 'Count' property instead")]
+ public int Size
+ {
+ get { return Count; }
+ }
+
+ public virtual int Count
+ {
+ get { return _set.Count; }
+ }
+
+ public virtual Asn1Encodable[] ToArray()
+ {
+ Asn1Encodable[] values = new Asn1Encodable[this.Count];
+ for (int i = 0; i < this.Count; ++i)
+ {
+ values[i] = this[i];
+ }
+ return values;
+ }
+
+ private class Asn1SetParserImpl
+ : Asn1SetParser
+ {
+ private readonly Asn1Set outer;
+ private readonly int max;
+ private int index;
+
+ public Asn1SetParserImpl(
+ Asn1Set outer)
+ {
+ this.outer = outer;
+ this.max = outer.Count;
+ }
+
+ public IAsn1Convertible ReadObject()
+ {
+ if (index == max)
+ return null;
+
+ Asn1Encodable obj = outer[index++];
+ if (obj is Asn1Sequence)
+ return ((Asn1Sequence)obj).Parser;
+
+ if (obj is Asn1Set)
+ return ((Asn1Set)obj).Parser;
+
+ // NB: Asn1OctetString implements Asn1OctetStringParser directly
+// if (obj is Asn1OctetString)
+// return ((Asn1OctetString)obj).Parser;
+
+ return obj;
+ }
+
+ public virtual Asn1Object ToAsn1Object()
+ {
+ return outer;
+ }
+ }
+
+ public Asn1SetParser Parser
+ {
+ get { return new Asn1SetParserImpl(this); }
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ int hc = Count;
+
+ foreach (object o in this)
+ {
+ hc *= 17;
+ if (o == null)
+ {
+ hc ^= DerNull.Instance.GetHashCode();
+ }
+ else
+ {
+ hc ^= o.GetHashCode();
+ }
+ }
+
+ return hc;
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ Asn1Set other = asn1Object as Asn1Set;
+
+ if (other == null)
+ return false;
+
+ if (Count != other.Count)
+ {
+ return false;
+ }
+
+ IEnumerator s1 = GetEnumerator();
+ IEnumerator s2 = other.GetEnumerator();
+
+ while (s1.MoveNext() && s2.MoveNext())
+ {
+ Asn1Object o1 = GetCurrent(s1).ToAsn1Object();
+ Asn1Object o2 = GetCurrent(s2).ToAsn1Object();
+
+ if (!o1.Equals(o2))
+ return false;
+ }
+
+ return true;
+ }
+
+ private Asn1Encodable GetCurrent(IEnumerator e)
+ {
+ Asn1Encodable encObj = (Asn1Encodable)e.Current;
+
+ // unfortunately null was allowed as a substitute for DER null
+ if (encObj == null)
+ return DerNull.Instance;
+
+ return encObj;
+ }
+
+ /**
+ * return true if a <= b (arrays are assumed padded with zeros).
+ */
+ private bool LessThanOrEqual(
+ byte[] a,
+ byte[] b)
+ {
+ int len = System.Math.Min(a.Length, b.Length);
+ for (int i = 0; i != len; ++i)
+ {
+ if (a[i] != b[i])
+ {
+ return a[i] < b[i];
+ }
+ }
+ return len == a.Length;
+ }
+
+ protected internal void Sort()
+ {
+ if (_set.Count > 1)
+ {
+ bool swapped = true;
+ int lastSwap = _set.Count - 1;
+
+ while (swapped)
+ {
+ int index = 0;
+ int swapIndex = 0;
+ byte[] a = ((Asn1Encodable) _set[0]).GetEncoded();
+
+ swapped = false;
+
+ while (index != lastSwap)
+ {
+ byte[] b = ((Asn1Encodable) _set[index + 1]).GetEncoded();
+
+ if (LessThanOrEqual(a, b))
+ {
+ a = b;
+ }
+ else
+ {
+ object o = _set[index];
+ _set[index] = _set[index + 1];
+ _set[index + 1] = o;
+
+ swapped = true;
+ swapIndex = index;
+ }
+
+ index++;
+ }
+
+ lastSwap = swapIndex;
+ }
+ }
+ }
+
+ protected internal void AddObject(
+ Asn1Encodable obj)
+ {
+ _set.Add(obj);
+ }
+
+ public override string ToString()
+ {
+ return CollectionUtilities.ToString(_set);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/Asn1TaggedObject.cs b/Crypto/src/asn1/Asn1TaggedObject.cs
new file mode 100644
index 000000000..2e480738a
--- /dev/null
+++ b/Crypto/src/asn1/Asn1TaggedObject.cs
@@ -0,0 +1,178 @@
+using System;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * ASN.1 TaggedObject - in ASN.1 notation this is any object preceded by
+ * a [n] where n is some number - these are assumed to follow the construction
+ * rules (as with sequences).
+ */
+ public abstract class Asn1TaggedObject
+ : Asn1Object, Asn1TaggedObjectParser
+ {
+ internal int tagNo;
+// internal bool empty;
+ internal bool explicitly = true;
+ internal Asn1Encodable obj;
+
+ static public Asn1TaggedObject GetInstance(
+ Asn1TaggedObject obj,
+ bool explicitly)
+ {
+ if (explicitly)
+ {
+ return (Asn1TaggedObject) obj.GetObject();
+ }
+
+ throw new ArgumentException("implicitly tagged tagged object");
+ }
+
+ static public Asn1TaggedObject GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is Asn1TaggedObject)
+ {
+ return (Asn1TaggedObject) obj;
+ }
+
+ throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj");
+ }
+
+ /**
+ * @param tagNo the tag number for this object.
+ * @param obj the tagged object.
+ */
+ protected Asn1TaggedObject(
+ int tagNo,
+ Asn1Encodable obj)
+ {
+ this.explicitly = true;
+ this.tagNo = tagNo;
+ this.obj = obj;
+ }
+
+ /**
+ * @param explicitly true if the object is explicitly tagged.
+ * @param tagNo the tag number for this object.
+ * @param obj the tagged object.
+ */
+ protected Asn1TaggedObject(
+ bool explicitly,
+ int tagNo,
+ Asn1Encodable obj)
+ {
+ // IAsn1Choice marker interface 'insists' on explicit tagging
+ this.explicitly = explicitly || (obj is IAsn1Choice);
+ this.tagNo = tagNo;
+ this.obj = obj;
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ Asn1TaggedObject other = asn1Object as Asn1TaggedObject;
+
+ if (other == null)
+ return false;
+
+ return this.tagNo == other.tagNo
+// && this.empty == other.empty
+ && this.explicitly == other.explicitly // TODO Should this be part of equality?
+ && Platform.Equals(GetObject(), other.GetObject());
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ int code = tagNo.GetHashCode();
+
+ // TODO: actually this is wrong - the problem is that a re-encoded
+ // object may end up with a different hashCode due to implicit
+ // tagging. As implicit tagging is ambiguous if a sequence is involved
+ // it seems the only correct method for both equals and hashCode is to
+ // compare the encodings...
+// code ^= explicitly.GetHashCode();
+
+ if (obj != null)
+ {
+ code ^= obj.GetHashCode();
+ }
+
+ return code;
+ }
+
+ public int TagNo
+ {
+ get { return tagNo; }
+ }
+
+ /**
+ * return whether or not the object may be explicitly tagged.
+ *
+ * Note: if the object has been read from an input stream, the only
+ * time you can be sure if isExplicit is returning the true state of
+ * affairs is if it returns false. An implicitly tagged object may appear
+ * to be explicitly tagged, so you need to understand the context under
+ * which the reading was done as well, see GetObject below.
+ */
+ public bool IsExplicit()
+ {
+ return explicitly;
+ }
+
+ public bool IsEmpty()
+ {
+ return false; //empty;
+ }
+
+ /**
+ * return whatever was following the tag.
+ *
+ * Note: tagged objects are generally context dependent if you're
+ * trying to extract a tagged object you should be going via the
+ * appropriate GetInstance method.
+ */
+ public Asn1Object GetObject()
+ {
+ if (obj != null)
+ {
+ return obj.ToAsn1Object();
+ }
+
+ return null;
+ }
+
+ /**
+ * Return the object held in this tagged object as a parser assuming it has
+ * the type of the passed in tag. If the object doesn't have a parser
+ * associated with it, the base object is returned.
+ */
+ public IAsn1Convertible GetObjectParser(
+ int tag,
+ bool isExplicit)
+ {
+ switch (tag)
+ {
+ case Asn1Tags.Set:
+ return Asn1Set.GetInstance(this, isExplicit).Parser;
+ case Asn1Tags.Sequence:
+ return Asn1Sequence.GetInstance(this, isExplicit).Parser;
+ case Asn1Tags.OctetString:
+ return Asn1OctetString.GetInstance(this, isExplicit).Parser;
+ }
+
+ if (isExplicit)
+ {
+ return GetObject();
+ }
+
+ throw Platform.CreateNotImplementedException("implicit tagging for tag: " + tag);
+ }
+
+ public override string ToString()
+ {
+ return "[" + tagNo + "]" + obj;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/Asn1Tags.cs b/Crypto/src/asn1/Asn1Tags.cs
new file mode 100644
index 000000000..32ac6bc6c
--- /dev/null
+++ b/Crypto/src/asn1/Asn1Tags.cs
@@ -0,0 +1,36 @@
+namespace Org.BouncyCastle.Asn1
+{
+ public class Asn1Tags
+ {
+ public const int Boolean = 0x01;
+ public const int Integer = 0x02;
+ public const int BitString = 0x03;
+ public const int OctetString = 0x04;
+ public const int Null = 0x05;
+ public const int ObjectIdentifier = 0x06;
+ public const int External = 0x08;
+ public const int Enumerated = 0x0a;
+ public const int Sequence = 0x10;
+ public const int SequenceOf = 0x10; // for completeness
+ public const int Set = 0x11;
+ public const int SetOf = 0x11; // for completeness
+
+ public const int NumericString = 0x12;
+ public const int PrintableString = 0x13;
+ public const int T61String = 0x14;
+ public const int VideotexString = 0x15;
+ public const int IA5String = 0x16;
+ public const int UtcTime = 0x17;
+ public const int GeneralizedTime = 0x18;
+ public const int GraphicString = 0x19;
+ public const int VisibleString = 0x1a;
+ public const int GeneralString = 0x1b;
+ public const int UniversalString = 0x1c;
+ public const int BmpString = 0x1e;
+ public const int Utf8String = 0x0c;
+
+ public const int Constructed = 0x20;
+ public const int Application = 0x40;
+ public const int Tagged = 0x80;
+ }
+}
diff --git a/Crypto/src/asn1/BERGenerator.cs b/Crypto/src/asn1/BERGenerator.cs
new file mode 100644
index 000000000..271572c02
--- /dev/null
+++ b/Crypto/src/asn1/BERGenerator.cs
@@ -0,0 +1,102 @@
+using System.IO;
+
+using Org.BouncyCastle.Utilities.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class BerGenerator
+ : Asn1Generator
+ {
+ private bool _tagged = false;
+ private bool _isExplicit;
+ private int _tagNo;
+
+ protected BerGenerator(
+ Stream outStream)
+ : base(outStream)
+ {
+ }
+
+ public BerGenerator(
+ Stream outStream,
+ int tagNo,
+ bool isExplicit)
+ : base(outStream)
+ {
+ _tagged = true;
+ _isExplicit = isExplicit;
+ _tagNo = tagNo;
+ }
+
+ public override void AddObject(
+ Asn1Encodable obj)
+ {
+ new BerOutputStream(Out).WriteObject(obj);
+ }
+
+ public override Stream GetRawOutputStream()
+ {
+ return Out;
+ }
+
+ public override void Close()
+ {
+ WriteBerEnd();
+ }
+
+ private void WriteHdr(
+ int tag)
+ {
+ Out.WriteByte((byte) tag);
+ Out.WriteByte(0x80);
+ }
+
+ protected void WriteBerHeader(
+ int tag)
+ {
+ if (_tagged)
+ {
+ int tagNum = _tagNo | Asn1Tags.Tagged;
+
+ if (_isExplicit)
+ {
+ WriteHdr(tagNum | Asn1Tags.Constructed);
+ WriteHdr(tag);
+ }
+ else
+ {
+ if ((tag & Asn1Tags.Constructed) != 0)
+ {
+ WriteHdr(tagNum | Asn1Tags.Constructed);
+ }
+ else
+ {
+ WriteHdr(tagNum);
+ }
+ }
+ }
+ else
+ {
+ WriteHdr(tag);
+ }
+ }
+
+ protected void WriteBerBody(
+ Stream contentStream)
+ {
+ Streams.PipeAll(contentStream, Out);
+ }
+
+ protected void WriteBerEnd()
+ {
+ Out.WriteByte(0x00);
+ Out.WriteByte(0x00);
+
+ if (_tagged && _isExplicit) // write extra end for tag header
+ {
+ Out.WriteByte(0x00);
+ Out.WriteByte(0x00);
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/BEROctetStringGenerator.cs b/Crypto/src/asn1/BEROctetStringGenerator.cs
new file mode 100644
index 000000000..644060765
--- /dev/null
+++ b/Crypto/src/asn1/BEROctetStringGenerator.cs
@@ -0,0 +1,121 @@
+using System;
+using System.IO;
+
+using Org.BouncyCastle.Utilities.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class BerOctetStringGenerator
+ : BerGenerator
+ {
+ public BerOctetStringGenerator(Stream outStream)
+ : base(outStream)
+ {
+ WriteBerHeader(Asn1Tags.Constructed | Asn1Tags.OctetString);
+ }
+
+ public BerOctetStringGenerator(
+ Stream outStream,
+ int tagNo,
+ bool isExplicit)
+ : base(outStream, tagNo, isExplicit)
+ {
+ WriteBerHeader(Asn1Tags.Constructed | Asn1Tags.OctetString);
+ }
+
+ public Stream GetOctetOutputStream()
+ {
+ return GetOctetOutputStream(new byte[1000]); // limit for CER encoding.
+ }
+
+ public Stream GetOctetOutputStream(
+ int bufSize)
+ {
+ return bufSize < 1
+ ? GetOctetOutputStream()
+ : GetOctetOutputStream(new byte[bufSize]);
+ }
+
+ public Stream GetOctetOutputStream(
+ byte[] buf)
+ {
+ return new BufferedBerOctetStream(this, buf);
+ }
+
+ private class BufferedBerOctetStream
+ : BaseOutputStream
+ {
+ private byte[] _buf;
+ private int _off;
+ private readonly BerOctetStringGenerator _gen;
+ private readonly DerOutputStream _derOut;
+
+ internal BufferedBerOctetStream(
+ BerOctetStringGenerator gen,
+ byte[] buf)
+ {
+ _gen = gen;
+ _buf = buf;
+ _off = 0;
+ _derOut = new DerOutputStream(_gen.Out);
+ }
+
+ public override void WriteByte(
+ byte b)
+ {
+ _buf[_off++] = b;
+
+ if (_off == _buf.Length)
+ {
+ DerOctetString.Encode(_derOut, _buf, 0, _off);
+ _off = 0;
+ }
+ }
+
+ public override void Write(
+ byte[] buf,
+ int offset,
+ int len)
+ {
+ while (len > 0)
+ {
+ int numToCopy = System.Math.Min(len, _buf.Length - _off);
+
+ if (numToCopy == _buf.Length)
+ {
+ DerOctetString.Encode(_derOut, buf, offset, numToCopy);
+ }
+ else
+ {
+ Array.Copy(buf, offset, _buf, _off, numToCopy);
+
+ _off += numToCopy;
+ if (_off < _buf.Length)
+ break;
+
+ DerOctetString.Encode(_derOut, _buf, 0, _off);
+ _off = 0;
+ }
+
+ offset += numToCopy;
+ len -= numToCopy;
+ }
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ if (_off != 0)
+ {
+ DerOctetString.Encode(_derOut, _buf, 0, _off);
+ }
+
+ _gen.WriteBerEnd();
+ }
+
+ base.Dispose(disposing);
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/BEROctetStringParser.cs b/Crypto/src/asn1/BEROctetStringParser.cs
new file mode 100644
index 000000000..3bfd2a98d
--- /dev/null
+++ b/Crypto/src/asn1/BEROctetStringParser.cs
@@ -0,0 +1,36 @@
+using System;
+using System.IO;
+
+using Org.BouncyCastle.Utilities.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class BerOctetStringParser
+ : Asn1OctetStringParser
+ {
+ private readonly Asn1StreamParser _parser;
+
+ internal BerOctetStringParser(
+ Asn1StreamParser parser)
+ {
+ _parser = parser;
+ }
+
+ public Stream GetOctetStream()
+ {
+ return new ConstructedOctetStream(_parser);
+ }
+
+ public Asn1Object ToAsn1Object()
+ {
+ try
+ {
+ return new BerOctetString(Streams.ReadAll(GetOctetStream()));
+ }
+ catch (IOException e)
+ {
+ throw new Asn1ParsingException("IOException converting stream to byte array: " + e.Message, e);
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/BERSequenceGenerator.cs b/Crypto/src/asn1/BERSequenceGenerator.cs
new file mode 100644
index 000000000..5ea2c9b82
--- /dev/null
+++ b/Crypto/src/asn1/BERSequenceGenerator.cs
@@ -0,0 +1,24 @@
+using System.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class BerSequenceGenerator
+ : BerGenerator
+ {
+ public BerSequenceGenerator(
+ Stream outStream)
+ : base(outStream)
+ {
+ WriteBerHeader(Asn1Tags.Constructed | Asn1Tags.Sequence);
+ }
+
+ public BerSequenceGenerator(
+ Stream outStream,
+ int tagNo,
+ bool isExplicit)
+ : base(outStream, tagNo, isExplicit)
+ {
+ WriteBerHeader(Asn1Tags.Constructed | Asn1Tags.Sequence);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/BERSequenceParser.cs b/Crypto/src/asn1/BERSequenceParser.cs
new file mode 100644
index 000000000..8474b8d24
--- /dev/null
+++ b/Crypto/src/asn1/BERSequenceParser.cs
@@ -0,0 +1,24 @@
+namespace Org.BouncyCastle.Asn1
+{
+ public class BerSequenceParser
+ : Asn1SequenceParser
+ {
+ private readonly Asn1StreamParser _parser;
+
+ internal BerSequenceParser(
+ Asn1StreamParser parser)
+ {
+ this._parser = parser;
+ }
+
+ public IAsn1Convertible ReadObject()
+ {
+ return _parser.ReadObject();
+ }
+
+ public Asn1Object ToAsn1Object()
+ {
+ return new BerSequence(_parser.ReadVector());
+ }
+ }
+}
diff --git a/Crypto/src/asn1/BERSetGenerator.cs b/Crypto/src/asn1/BERSetGenerator.cs
new file mode 100644
index 000000000..72b1f903a
--- /dev/null
+++ b/Crypto/src/asn1/BERSetGenerator.cs
@@ -0,0 +1,24 @@
+using System.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class BerSetGenerator
+ : BerGenerator
+ {
+ public BerSetGenerator(
+ Stream outStream)
+ : base(outStream)
+ {
+ WriteBerHeader(Asn1Tags.Constructed | Asn1Tags.Set);
+ }
+
+ public BerSetGenerator(
+ Stream outStream,
+ int tagNo,
+ bool isExplicit)
+ : base(outStream, tagNo, isExplicit)
+ {
+ WriteBerHeader(Asn1Tags.Constructed | Asn1Tags.Set);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/BERSetParser.cs b/Crypto/src/asn1/BERSetParser.cs
new file mode 100644
index 000000000..aa9ccbc12
--- /dev/null
+++ b/Crypto/src/asn1/BERSetParser.cs
@@ -0,0 +1,24 @@
+namespace Org.BouncyCastle.Asn1
+{
+ public class BerSetParser
+ : Asn1SetParser
+ {
+ private readonly Asn1StreamParser _parser;
+
+ internal BerSetParser(
+ Asn1StreamParser parser)
+ {
+ this._parser = parser;
+ }
+
+ public IAsn1Convertible ReadObject()
+ {
+ return _parser.ReadObject();
+ }
+
+ public Asn1Object ToAsn1Object()
+ {
+ return new BerSet(_parser.ReadVector(), false);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/BERTaggedObjectParser.cs b/Crypto/src/asn1/BERTaggedObjectParser.cs
new file mode 100644
index 000000000..354437a6a
--- /dev/null
+++ b/Crypto/src/asn1/BERTaggedObjectParser.cs
@@ -0,0 +1,71 @@
+using System;
+using System.IO;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class BerTaggedObjectParser
+ : Asn1TaggedObjectParser
+ {
+ private bool _constructed;
+ private int _tagNumber;
+ private Asn1StreamParser _parser;
+
+ [Obsolete]
+ internal BerTaggedObjectParser(
+ int baseTag,
+ int tagNumber,
+ Stream contentStream)
+ : this((baseTag & Asn1Tags.Constructed) != 0, tagNumber, new Asn1StreamParser(contentStream))
+ {
+ }
+
+ internal BerTaggedObjectParser(
+ bool constructed,
+ int tagNumber,
+ Asn1StreamParser parser)
+ {
+ _constructed = constructed;
+ _tagNumber = tagNumber;
+ _parser = parser;
+ }
+
+ public bool IsConstructed
+ {
+ get { return _constructed; }
+ }
+
+ public int TagNo
+ {
+ get { return _tagNumber; }
+ }
+
+ public IAsn1Convertible GetObjectParser(
+ int tag,
+ bool isExplicit)
+ {
+ if (isExplicit)
+ {
+ if (!_constructed)
+ throw new IOException("Explicit tags must be constructed (see X.690 8.14.2)");
+
+ return _parser.ReadObject();
+ }
+
+ return _parser.ReadImplicit(_constructed, tag);
+ }
+
+ public Asn1Object ToAsn1Object()
+ {
+ try
+ {
+ return _parser.ReadTaggedObject(_constructed, _tagNumber);
+ }
+ catch (IOException e)
+ {
+ throw new Asn1ParsingException(e.Message);
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/BerApplicationSpecific.cs b/Crypto/src/asn1/BerApplicationSpecific.cs
new file mode 100644
index 000000000..65fbecbe1
--- /dev/null
+++ b/Crypto/src/asn1/BerApplicationSpecific.cs
@@ -0,0 +1,15 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class BerApplicationSpecific
+ : DerApplicationSpecific
+ {
+ public BerApplicationSpecific(
+ int tagNo,
+ Asn1EncodableVector vec)
+ : base(tagNo, vec)
+ {
+ }
+ }
+}
diff --git a/Crypto/src/asn1/BerApplicationSpecificParser.cs b/Crypto/src/asn1/BerApplicationSpecificParser.cs
new file mode 100644
index 000000000..7d2c4b3e8
--- /dev/null
+++ b/Crypto/src/asn1/BerApplicationSpecificParser.cs
@@ -0,0 +1,29 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class BerApplicationSpecificParser
+ : IAsn1ApplicationSpecificParser
+ {
+ private readonly int tag;
+ private readonly Asn1StreamParser parser;
+
+ internal BerApplicationSpecificParser(
+ int tag,
+ Asn1StreamParser parser)
+ {
+ this.tag = tag;
+ this.parser = parser;
+ }
+
+ public IAsn1Convertible ReadObject()
+ {
+ return parser.ReadObject();
+ }
+
+ public Asn1Object ToAsn1Object()
+ {
+ return new BerApplicationSpecific(tag, parser.ReadVector());
+ }
+ }
+}
diff --git a/Crypto/src/asn1/BerNull.cs b/Crypto/src/asn1/BerNull.cs
new file mode 100644
index 000000000..0751bbac3
--- /dev/null
+++ b/Crypto/src/asn1/BerNull.cs
@@ -0,0 +1,35 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * A BER Null object.
+ */
+ public class BerNull
+ : DerNull
+ {
+ public static new readonly BerNull Instance = new BerNull(0);
+
+ [Obsolete("Use static Instance object")]
+ public BerNull()
+ {
+ }
+
+ private BerNull(int dummy) : base(dummy)
+ {
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ if (derOut is Asn1OutputStream || derOut is BerOutputStream)
+ {
+ derOut.WriteByte(Asn1Tags.Null);
+ }
+ else
+ {
+ base.Encode(derOut);
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/BerOctetString.cs b/Crypto/src/asn1/BerOctetString.cs
new file mode 100644
index 000000000..a7c8ad33e
--- /dev/null
+++ b/Crypto/src/asn1/BerOctetString.cs
@@ -0,0 +1,135 @@
+using System;
+using System.Collections;
+using System.IO;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class BerOctetString
+ : DerOctetString, IEnumerable
+ {
+ public static BerOctetString FromSequence(Asn1Sequence seq)
+ {
+ IList v = Platform.CreateArrayList();
+
+ foreach (Asn1Encodable obj in seq)
+ {
+ v.Add(obj);
+ }
+
+ return new BerOctetString(v);
+ }
+
+ private const int MaxLength = 1000;
+
+ /**
+ * convert a vector of octet strings into a single byte string
+ */
+ private static byte[] ToBytes(
+ IEnumerable octs)
+ {
+ MemoryStream bOut = new MemoryStream();
+ foreach (DerOctetString o in octs)
+ {
+ byte[] octets = o.GetOctets();
+ bOut.Write(octets, 0, octets.Length);
+ }
+ return bOut.ToArray();
+ }
+
+ private readonly IEnumerable octs;
+
+ /// The octets making up the octet string.
+ public BerOctetString(
+ byte[] str)
+ : base(str)
+ {
+ }
+
+ public BerOctetString(
+ IEnumerable octets)
+ : base(ToBytes(octets))
+ {
+ this.octs = octets;
+ }
+
+ public BerOctetString(
+ Asn1Object obj)
+ : base(obj)
+ {
+ }
+
+ public BerOctetString(
+ Asn1Encodable obj)
+ : base(obj.ToAsn1Object())
+ {
+ }
+
+ public override byte[] GetOctets()
+ {
+ return str;
+ }
+
+ /**
+ * return the DER octets that make up this string.
+ */
+ public IEnumerator GetEnumerator()
+ {
+ if (octs == null)
+ {
+ return GenerateOcts().GetEnumerator();
+ }
+
+ return octs.GetEnumerator();
+ }
+
+ [Obsolete("Use GetEnumerator() instead")]
+ public IEnumerator GetObjects()
+ {
+ return GetEnumerator();
+ }
+
+ private IList GenerateOcts()
+ {
+ IList vec = Platform.CreateArrayList();
+ for (int i = 0; i < str.Length; i += MaxLength)
+ {
+ int end = System.Math.Min(str.Length, i + MaxLength);
+
+ byte[] nStr = new byte[end - i];
+
+ Array.Copy(str, i, nStr, 0, nStr.Length);
+
+ vec.Add(new DerOctetString(nStr));
+ }
+ return vec;
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ if (derOut is Asn1OutputStream || derOut is BerOutputStream)
+ {
+ derOut.WriteByte(Asn1Tags.Constructed | Asn1Tags.OctetString);
+
+ derOut.WriteByte(0x80);
+
+ //
+ // write out the octet array
+ //
+ foreach (DerOctetString oct in this)
+ {
+ derOut.WriteObject(oct);
+ }
+
+ derOut.WriteByte(0x00);
+ derOut.WriteByte(0x00);
+ }
+ else
+ {
+ base.Encode(derOut);
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/BerOutputStream.cs b/Crypto/src/asn1/BerOutputStream.cs
new file mode 100644
index 000000000..b3ece10d3
--- /dev/null
+++ b/Crypto/src/asn1/BerOutputStream.cs
@@ -0,0 +1,36 @@
+using System;
+using System.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ // TODO Make Obsolete in favour of Asn1OutputStream?
+ public class BerOutputStream
+ : DerOutputStream
+ {
+ public BerOutputStream(Stream os) : base(os)
+ {
+ }
+
+ [Obsolete("Use version taking an Asn1Encodable arg instead")]
+ public override void WriteObject(
+ object obj)
+ {
+ if (obj == null)
+ {
+ WriteNull();
+ }
+ else if (obj is Asn1Object)
+ {
+ ((Asn1Object)obj).Encode(this);
+ }
+ else if (obj is Asn1Encodable)
+ {
+ ((Asn1Encodable)obj).ToAsn1Object().Encode(this);
+ }
+ else
+ {
+ throw new IOException("object not BerEncodable");
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/BerSequence.cs b/Crypto/src/asn1/BerSequence.cs
new file mode 100644
index 000000000..70b43fc79
--- /dev/null
+++ b/Crypto/src/asn1/BerSequence.cs
@@ -0,0 +1,69 @@
+namespace Org.BouncyCastle.Asn1
+{
+ public class BerSequence
+ : DerSequence
+ {
+ public static new readonly BerSequence Empty = new BerSequence();
+
+ public static new BerSequence FromVector(
+ Asn1EncodableVector v)
+ {
+ return v.Count < 1 ? Empty : new BerSequence(v);
+ }
+
+ /**
+ * create an empty sequence
+ */
+ public BerSequence()
+ {
+ }
+
+ /**
+ * create a sequence containing one object
+ */
+ public BerSequence(
+ Asn1Encodable obj)
+ : base(obj)
+ {
+ }
+
+ public BerSequence(
+ params Asn1Encodable[] v)
+ : base(v)
+ {
+ }
+
+ /**
+ * create a sequence containing a vector of objects.
+ */
+ public BerSequence(
+ Asn1EncodableVector v)
+ : base(v)
+ {
+ }
+
+ /*
+ */
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ if (derOut is Asn1OutputStream || derOut is BerOutputStream)
+ {
+ derOut.WriteByte(Asn1Tags.Sequence | Asn1Tags.Constructed);
+ derOut.WriteByte(0x80);
+
+ foreach (Asn1Encodable o in this)
+ {
+ derOut.WriteObject(o);
+ }
+
+ derOut.WriteByte(0x00);
+ derOut.WriteByte(0x00);
+ }
+ else
+ {
+ base.Encode(derOut);
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/BerSet.cs b/Crypto/src/asn1/BerSet.cs
new file mode 100644
index 000000000..a181e172d
--- /dev/null
+++ b/Crypto/src/asn1/BerSet.cs
@@ -0,0 +1,70 @@
+namespace Org.BouncyCastle.Asn1
+{
+ public class BerSet
+ : DerSet
+ {
+ public static new readonly BerSet Empty = new BerSet();
+
+ public static new BerSet FromVector(
+ Asn1EncodableVector v)
+ {
+ return v.Count < 1 ? Empty : new BerSet(v);
+ }
+
+ internal static new BerSet FromVector(
+ Asn1EncodableVector v,
+ bool needsSorting)
+ {
+ return v.Count < 1 ? Empty : new BerSet(v, needsSorting);
+ }
+
+ /**
+ * create an empty sequence
+ */
+ public BerSet()
+ {
+ }
+
+ /**
+ * create a set containing one object
+ */
+ public BerSet(Asn1Encodable obj) : base(obj)
+ {
+ }
+
+ /**
+ * create a set containing a vector of objects.
+ */
+ public BerSet(Asn1EncodableVector v) : base(v, false)
+ {
+ }
+
+ internal BerSet(Asn1EncodableVector v, bool needsSorting) : base(v, needsSorting)
+ {
+ }
+
+ /*
+ */
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ if (derOut is Asn1OutputStream || derOut is BerOutputStream)
+ {
+ derOut.WriteByte(Asn1Tags.Set | Asn1Tags.Constructed);
+ derOut.WriteByte(0x80);
+
+ foreach (Asn1Encodable o in this)
+ {
+ derOut.WriteObject(o);
+ }
+
+ derOut.WriteByte(0x00);
+ derOut.WriteByte(0x00);
+ }
+ else
+ {
+ base.Encode(derOut);
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/BerTaggedObject.cs b/Crypto/src/asn1/BerTaggedObject.cs
new file mode 100644
index 000000000..228b136cb
--- /dev/null
+++ b/Crypto/src/asn1/BerTaggedObject.cs
@@ -0,0 +1,108 @@
+using System;
+using System.Collections;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * BER TaggedObject - in ASN.1 notation this is any object preceded by
+ * a [n] where n is some number - these are assumed to follow the construction
+ * rules (as with sequences).
+ */
+ public class BerTaggedObject
+ : DerTaggedObject
+ {
+ /**
+ * @param tagNo the tag number for this object.
+ * @param obj the tagged object.
+ */
+ public BerTaggedObject(
+ int tagNo,
+ Asn1Encodable obj)
+ : base(tagNo, obj)
+ {
+ }
+
+ /**
+ * @param explicitly true if an explicitly tagged object.
+ * @param tagNo the tag number for this object.
+ * @param obj the tagged object.
+ */
+ public BerTaggedObject(
+ bool explicitly,
+ int tagNo,
+ Asn1Encodable obj)
+ : base(explicitly, tagNo, obj)
+ {
+ }
+
+ /**
+ * create an implicitly tagged object that contains a zero
+ * length sequence.
+ */
+ public BerTaggedObject(
+ int tagNo)
+ : base(false, tagNo, BerSequence.Empty)
+ {
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ if (derOut is Asn1OutputStream || derOut is BerOutputStream)
+ {
+ derOut.WriteTag((byte)(Asn1Tags.Constructed | Asn1Tags.Tagged), tagNo);
+ derOut.WriteByte(0x80);
+
+ if (!IsEmpty())
+ {
+ if (!explicitly)
+ {
+ IEnumerable eObj;
+ if (obj is Asn1OctetString)
+ {
+ if (obj is BerOctetString)
+ {
+ eObj = (BerOctetString) obj;
+ }
+ else
+ {
+ Asn1OctetString octs = (Asn1OctetString)obj;
+ eObj = new BerOctetString(octs.GetOctets());
+ }
+ }
+ else if (obj is Asn1Sequence)
+ {
+ eObj = (Asn1Sequence) obj;
+ }
+ else if (obj is Asn1Set)
+ {
+ eObj = (Asn1Set) obj;
+ }
+ else
+ {
+ throw Platform.CreateNotImplementedException(obj.GetType().Name);
+ }
+
+ foreach (Asn1Encodable o in eObj)
+ {
+ derOut.WriteObject(o);
+ }
+ }
+ else
+ {
+ derOut.WriteObject(obj);
+ }
+ }
+
+ derOut.WriteByte(0x00);
+ derOut.WriteByte(0x00);
+ }
+ else
+ {
+ base.Encode(derOut);
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/ConstructedOctetStream.cs b/Crypto/src/asn1/ConstructedOctetStream.cs
new file mode 100644
index 000000000..1773b22cc
--- /dev/null
+++ b/Crypto/src/asn1/ConstructedOctetStream.cs
@@ -0,0 +1,102 @@
+using System.IO;
+
+using Org.BouncyCastle.Utilities.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ internal class ConstructedOctetStream
+ : BaseInputStream
+ {
+ private readonly Asn1StreamParser _parser;
+
+ private bool _first = true;
+ private Stream _currentStream;
+
+ internal ConstructedOctetStream(
+ Asn1StreamParser parser)
+ {
+ _parser = parser;
+ }
+
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ if (_currentStream == null)
+ {
+ if (!_first)
+ return 0;
+
+ Asn1OctetStringParser s = (Asn1OctetStringParser)_parser.ReadObject();
+
+ if (s == null)
+ return 0;
+
+ _first = false;
+ _currentStream = s.GetOctetStream();
+ }
+
+ int totalRead = 0;
+
+ for (;;)
+ {
+ int numRead = _currentStream.Read(buffer, offset + totalRead, count - totalRead);
+
+ if (numRead > 0)
+ {
+ totalRead += numRead;
+
+ if (totalRead == count)
+ return totalRead;
+ }
+ else
+ {
+ Asn1OctetStringParser aos = (Asn1OctetStringParser)_parser.ReadObject();
+
+ if (aos == null)
+ {
+ _currentStream = null;
+ return totalRead;
+ }
+
+ _currentStream = aos.GetOctetStream();
+ }
+ }
+ }
+
+ public override int ReadByte()
+ {
+ if (_currentStream == null)
+ {
+ if (!_first)
+ return 0;
+
+ Asn1OctetStringParser s = (Asn1OctetStringParser)_parser.ReadObject();
+
+ if (s == null)
+ return 0;
+
+ _first = false;
+ _currentStream = s.GetOctetStream();
+ }
+
+ for (;;)
+ {
+ int b = _currentStream.ReadByte();
+
+ if (b >= 0)
+ {
+ return b;
+ }
+
+ Asn1OctetStringParser aos = (Asn1OctetStringParser)_parser.ReadObject();
+
+ if (aos == null)
+ {
+ _currentStream = null;
+ return -1;
+ }
+
+ _currentStream = aos.GetOctetStream();
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DERExternal.cs b/Crypto/src/asn1/DERExternal.cs
new file mode 100644
index 000000000..a342d6520
--- /dev/null
+++ b/Crypto/src/asn1/DERExternal.cs
@@ -0,0 +1,207 @@
+using System;
+using System.IO;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * Class representing the DER-type External
+ */
+ public class DerExternal
+ : Asn1Object
+ {
+ private DerObjectIdentifier directReference;
+ private DerInteger indirectReference;
+ private Asn1Object dataValueDescriptor;
+ private int encoding;
+ private Asn1Object externalContent;
+
+ public DerExternal(
+ Asn1EncodableVector vector)
+ {
+ int offset = 0;
+ Asn1Object enc = GetObjFromVector(vector, offset);
+ if (enc is DerObjectIdentifier)
+ {
+ directReference = (DerObjectIdentifier)enc;
+ offset++;
+ enc = GetObjFromVector(vector, offset);
+ }
+ if (enc is DerInteger)
+ {
+ indirectReference = (DerInteger) enc;
+ offset++;
+ enc = GetObjFromVector(vector, offset);
+ }
+ if (!(enc is DerTaggedObject))
+ {
+ dataValueDescriptor = (Asn1Object) enc;
+ offset++;
+ enc = GetObjFromVector(vector, offset);
+ }
+ if (!(enc is DerTaggedObject))
+ {
+ throw new InvalidOperationException(
+ "No tagged object found in vector. Structure doesn't seem to be of type External");
+ }
+
+ if (vector.Count != offset + 1)
+ throw new ArgumentException("input vector too large", "vector");
+
+ if (!(enc is DerTaggedObject))
+ throw new ArgumentException("No tagged object found in vector. Structure doesn't seem to be of type External", "vector");
+
+ DerTaggedObject obj = (DerTaggedObject)enc;
+
+ // Use property accessor to include check on value
+ Encoding = obj.TagNo;
+
+ if (encoding < 0 || encoding > 2)
+ throw new InvalidOperationException("invalid encoding value");
+
+ externalContent = obj.GetObject();
+ }
+
+ /**
+ * Creates a new instance of DerExternal
+ * See X.690 for more informations about the meaning of these parameters
+ * @param directReference The direct reference or null if not set.
+ * @param indirectReference The indirect reference or null if not set.
+ * @param dataValueDescriptor The data value descriptor or null if not set.
+ * @param externalData The external data in its encoded form.
+ */
+ public DerExternal(DerObjectIdentifier directReference, DerInteger indirectReference, Asn1Object dataValueDescriptor, DerTaggedObject externalData)
+ : this(directReference, indirectReference, dataValueDescriptor, externalData.TagNo, externalData.ToAsn1Object())
+ {
+ }
+
+ /**
+ * Creates a new instance of DerExternal.
+ * See X.690 for more informations about the meaning of these parameters
+ * @param directReference The direct reference or null if not set.
+ * @param indirectReference The indirect reference or null if not set.
+ * @param dataValueDescriptor The data value descriptor or null if not set.
+ * @param encoding The encoding to be used for the external data
+ * @param externalData The external data
+ */
+ public DerExternal(DerObjectIdentifier directReference, DerInteger indirectReference, Asn1Object dataValueDescriptor, int encoding, Asn1Object externalData)
+ {
+ DirectReference = directReference;
+ IndirectReference = indirectReference;
+ DataValueDescriptor = dataValueDescriptor;
+ Encoding = encoding;
+ ExternalContent = externalData.ToAsn1Object();
+ }
+
+ internal override void Encode(DerOutputStream derOut)
+ {
+ MemoryStream ms = new MemoryStream();
+ WriteEncodable(ms, directReference);
+ WriteEncodable(ms, indirectReference);
+ WriteEncodable(ms, dataValueDescriptor);
+ WriteEncodable(ms, new DerTaggedObject(Asn1Tags.External, externalContent));
+
+ derOut.WriteEncoded(Asn1Tags.Constructed, Asn1Tags.External, ms.ToArray());
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ int ret = externalContent.GetHashCode();
+ if (directReference != null)
+ {
+ ret ^= directReference.GetHashCode();
+ }
+ if (indirectReference != null)
+ {
+ ret ^= indirectReference.GetHashCode();
+ }
+ if (dataValueDescriptor != null)
+ {
+ ret ^= dataValueDescriptor.GetHashCode();
+ }
+ return ret;
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ if (this == asn1Object)
+ return true;
+
+ DerExternal other = asn1Object as DerExternal;
+
+ if (other == null)
+ return false;
+
+ return Platform.Equals(directReference, other.directReference)
+ && Platform.Equals(indirectReference, other.indirectReference)
+ && Platform.Equals(dataValueDescriptor, other.dataValueDescriptor)
+ && externalContent.Equals(other.externalContent);
+ }
+
+ public Asn1Object DataValueDescriptor
+ {
+ get { return dataValueDescriptor; }
+ set { this.dataValueDescriptor = value; }
+ }
+
+ public DerObjectIdentifier DirectReference
+ {
+ get { return directReference; }
+ set { this.directReference = value; }
+ }
+
+ /**
+ * The encoding of the content. Valid values are
+ *
+ *
0 single-ASN1-type
+ *
1 OCTET STRING
+ *
2 BIT STRING
+ *
+ */
+ public int Encoding
+ {
+ get
+ {
+ return encoding;
+ }
+ set
+ {
+ if (encoding < 0 || encoding > 2)
+ throw new InvalidOperationException("invalid encoding value: " + encoding);
+
+ this.encoding = value;
+ }
+ }
+
+ public Asn1Object ExternalContent
+ {
+ get { return externalContent; }
+ set { this.externalContent = value; }
+ }
+
+ public DerInteger IndirectReference
+ {
+ get { return indirectReference; }
+ set { this.indirectReference = value; }
+ }
+
+ private static Asn1Object GetObjFromVector(Asn1EncodableVector v, int index)
+ {
+ if (v.Count <= index)
+ throw new ArgumentException("too few objects in input vector", "v");
+
+ return v[index].ToAsn1Object();
+ }
+
+ private static void WriteEncodable(MemoryStream ms, Asn1Encodable e)
+ {
+ if (e != null)
+ {
+ byte[] bs = e.GetDerEncoded();
+ ms.Write(bs, 0, bs.Length);
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DERExternalParser.cs b/Crypto/src/asn1/DERExternalParser.cs
new file mode 100644
index 000000000..70e426fed
--- /dev/null
+++ b/Crypto/src/asn1/DERExternalParser.cs
@@ -0,0 +1,26 @@
+using System;
+using System.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class DerExternalParser
+ : Asn1Encodable
+ {
+ private readonly Asn1StreamParser _parser;
+
+ public DerExternalParser(Asn1StreamParser parser)
+ {
+ this._parser = parser;
+ }
+
+ public IAsn1Convertible ReadObject()
+ {
+ return _parser.ReadObject();
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerExternal(_parser.ReadVector());
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DERGenerator.cs b/Crypto/src/asn1/DERGenerator.cs
new file mode 100644
index 000000000..aab40fefa
--- /dev/null
+++ b/Crypto/src/asn1/DERGenerator.cs
@@ -0,0 +1,107 @@
+using System.IO;
+
+using Org.BouncyCastle.Utilities.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public abstract class DerGenerator
+ : Asn1Generator
+ {
+ private bool _tagged = false;
+ private bool _isExplicit;
+ private int _tagNo;
+
+ protected DerGenerator(
+ Stream outStream)
+ : base(outStream)
+ {
+ }
+
+ protected DerGenerator(
+ Stream outStream,
+ int tagNo,
+ bool isExplicit)
+ : base(outStream)
+ {
+ _tagged = true;
+ _isExplicit = isExplicit;
+ _tagNo = tagNo;
+ }
+
+ private static void WriteLength(
+ Stream outStr,
+ int length)
+ {
+ if (length > 127)
+ {
+ int size = 1;
+ int val = length;
+
+ while ((val >>= 8) != 0)
+ {
+ size++;
+ }
+
+ outStr.WriteByte((byte)(size | 0x80));
+
+ for (int i = (size - 1) * 8; i >= 0; i -= 8)
+ {
+ outStr.WriteByte((byte)(length >> i));
+ }
+ }
+ else
+ {
+ outStr.WriteByte((byte)length);
+ }
+ }
+
+ internal static void WriteDerEncoded(
+ Stream outStream,
+ int tag,
+ byte[] bytes)
+ {
+ outStream.WriteByte((byte) tag);
+ WriteLength(outStream, bytes.Length);
+ outStream.Write(bytes, 0, bytes.Length);
+ }
+
+ internal void WriteDerEncoded(
+ int tag,
+ byte[] bytes)
+ {
+ if (_tagged)
+ {
+ int tagNum = _tagNo | Asn1Tags.Tagged;
+
+ if (_isExplicit)
+ {
+ int newTag = _tagNo | Asn1Tags.Constructed | Asn1Tags.Tagged;
+ MemoryStream bOut = new MemoryStream();
+ WriteDerEncoded(bOut, tag, bytes);
+ WriteDerEncoded(Out, newTag, bOut.ToArray());
+ }
+ else
+ {
+ if ((tag & Asn1Tags.Constructed) != 0)
+ {
+ tagNum |= Asn1Tags.Constructed;
+ }
+
+ WriteDerEncoded(Out, tagNum, bytes);
+ }
+ }
+ else
+ {
+ WriteDerEncoded(Out, tag, bytes);
+ }
+ }
+
+ internal static void WriteDerEncoded(
+ Stream outStr,
+ int tag,
+ Stream inStr)
+ {
+ WriteDerEncoded(outStr, tag, Streams.ReadAll(inStr));
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DEROctetStringParser.cs b/Crypto/src/asn1/DEROctetStringParser.cs
new file mode 100644
index 000000000..b0d3ad8cf
--- /dev/null
+++ b/Crypto/src/asn1/DEROctetStringParser.cs
@@ -0,0 +1,36 @@
+using System;
+using System.IO;
+
+using Org.BouncyCastle.Utilities.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class DerOctetStringParser
+ : Asn1OctetStringParser
+ {
+ private readonly DefiniteLengthInputStream stream;
+
+ internal DerOctetStringParser(
+ DefiniteLengthInputStream stream)
+ {
+ this.stream = stream;
+ }
+
+ public Stream GetOctetStream()
+ {
+ return stream;
+ }
+
+ public Asn1Object ToAsn1Object()
+ {
+ try
+ {
+ return new DerOctetString(stream.ToArray());
+ }
+ catch (IOException e)
+ {
+ throw new InvalidOperationException("IOException converting stream to byte array: " + e.Message, e);
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DERSequenceGenerator.cs b/Crypto/src/asn1/DERSequenceGenerator.cs
new file mode 100644
index 000000000..4c2bfd012
--- /dev/null
+++ b/Crypto/src/asn1/DERSequenceGenerator.cs
@@ -0,0 +1,40 @@
+using System.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class DerSequenceGenerator
+ : DerGenerator
+ {
+ private readonly MemoryStream _bOut = new MemoryStream();
+
+ public DerSequenceGenerator(
+ Stream outStream)
+ : base(outStream)
+ {
+ }
+
+ public DerSequenceGenerator(
+ Stream outStream,
+ int tagNo,
+ bool isExplicit)
+ : base(outStream, tagNo, isExplicit)
+ {
+ }
+
+ public override void AddObject(
+ Asn1Encodable obj)
+ {
+ new DerOutputStream(_bOut).WriteObject(obj);
+ }
+
+ public override Stream GetRawOutputStream()
+ {
+ return _bOut;
+ }
+
+ public override void Close()
+ {
+ WriteDerEncoded(Asn1Tags.Constructed | Asn1Tags.Sequence, _bOut.ToArray());
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DERSequenceParser.cs b/Crypto/src/asn1/DERSequenceParser.cs
new file mode 100644
index 000000000..69c2b9b2d
--- /dev/null
+++ b/Crypto/src/asn1/DERSequenceParser.cs
@@ -0,0 +1,24 @@
+namespace Org.BouncyCastle.Asn1
+{
+ public class DerSequenceParser
+ : Asn1SequenceParser
+ {
+ private readonly Asn1StreamParser _parser;
+
+ internal DerSequenceParser(
+ Asn1StreamParser parser)
+ {
+ this._parser = parser;
+ }
+
+ public IAsn1Convertible ReadObject()
+ {
+ return _parser.ReadObject();
+ }
+
+ public Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(_parser.ReadVector());
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DERSetGenerator.cs b/Crypto/src/asn1/DERSetGenerator.cs
new file mode 100644
index 000000000..455ca88ac
--- /dev/null
+++ b/Crypto/src/asn1/DERSetGenerator.cs
@@ -0,0 +1,40 @@
+using System.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class DerSetGenerator
+ : DerGenerator
+ {
+ private readonly MemoryStream _bOut = new MemoryStream();
+
+ public DerSetGenerator(
+ Stream outStream)
+ : base(outStream)
+ {
+ }
+
+ public DerSetGenerator(
+ Stream outStream,
+ int tagNo,
+ bool isExplicit)
+ : base(outStream, tagNo, isExplicit)
+ {
+ }
+
+ public override void AddObject(
+ Asn1Encodable obj)
+ {
+ new DerOutputStream(_bOut).WriteObject(obj);
+ }
+
+ public override Stream GetRawOutputStream()
+ {
+ return _bOut;
+ }
+
+ public override void Close()
+ {
+ WriteDerEncoded(Asn1Tags.Constructed | Asn1Tags.Set, _bOut.ToArray());
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DERSetParser.cs b/Crypto/src/asn1/DERSetParser.cs
new file mode 100644
index 000000000..d67f135be
--- /dev/null
+++ b/Crypto/src/asn1/DERSetParser.cs
@@ -0,0 +1,24 @@
+namespace Org.BouncyCastle.Asn1
+{
+ public class DerSetParser
+ : Asn1SetParser
+ {
+ private readonly Asn1StreamParser _parser;
+
+ internal DerSetParser(
+ Asn1StreamParser parser)
+ {
+ this._parser = parser;
+ }
+
+ public IAsn1Convertible ReadObject()
+ {
+ return _parser.ReadObject();
+ }
+
+ public Asn1Object ToAsn1Object()
+ {
+ return new DerSet(_parser.ReadVector(), false);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DefiniteLengthInputStream.cs b/Crypto/src/asn1/DefiniteLengthInputStream.cs
new file mode 100644
index 000000000..cfea89f21
--- /dev/null
+++ b/Crypto/src/asn1/DefiniteLengthInputStream.cs
@@ -0,0 +1,90 @@
+using System;
+using System.IO;
+
+using Org.BouncyCastle.Utilities.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ class DefiniteLengthInputStream
+ : LimitedInputStream
+ {
+ private static readonly byte[] EmptyBytes = new byte[0];
+
+ private readonly int _originalLength;
+ private int _remaining;
+
+ internal DefiniteLengthInputStream(
+ Stream inStream,
+ int length)
+ : base(inStream, length)
+ {
+ if (length < 0)
+ throw new ArgumentException("negative lengths not allowed", "length");
+
+ this._originalLength = length;
+ this._remaining = length;
+
+ if (length == 0)
+ {
+ SetParentEofDetect(true);
+ }
+ }
+
+ internal int Remaining
+ {
+ get { return _remaining; }
+ }
+
+ public override int ReadByte()
+ {
+ if (_remaining == 0)
+ return -1;
+
+ int b = _in.ReadByte();
+
+ if (b < 0)
+ throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining);
+
+ if (--_remaining == 0)
+ {
+ SetParentEofDetect(true);
+ }
+
+ return b;
+ }
+
+ public override int Read(
+ byte[] buf,
+ int off,
+ int len)
+ {
+ if (_remaining == 0)
+ return 0;
+
+ int toRead = System.Math.Min(len, _remaining);
+ int numRead = _in.Read(buf, off, toRead);
+
+ if (numRead < 1)
+ throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining);
+
+ if ((_remaining -= numRead) == 0)
+ {
+ SetParentEofDetect(true);
+ }
+
+ return numRead;
+ }
+
+ internal byte[] ToArray()
+ {
+ if (_remaining == 0)
+ return EmptyBytes;
+
+ byte[] bytes = new byte[_remaining];
+ if ((_remaining -= Streams.ReadFully(_in, bytes)) != 0)
+ throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining);
+ SetParentEofDetect(true);
+ return bytes;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerApplicationSpecific.cs b/Crypto/src/asn1/DerApplicationSpecific.cs
new file mode 100644
index 000000000..394c7431e
--- /dev/null
+++ b/Crypto/src/asn1/DerApplicationSpecific.cs
@@ -0,0 +1,237 @@
+using System;
+using System.IO;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * Base class for an application specific object
+ */
+ public class DerApplicationSpecific
+ : Asn1Object
+ {
+ private readonly bool isConstructed;
+ private readonly int tag;
+ private readonly byte[] octets;
+
+ internal DerApplicationSpecific(
+ bool 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 obj)
+ : this(true, tag, obj)
+ {
+ }
+
+ public DerApplicationSpecific(
+ bool isExplicit,
+ int tag,
+ Asn1Encodable obj)
+ {
+ Asn1Object asn1Obj = obj.ToAsn1Object();
+
+ byte[] data = asn1Obj.GetDerEncoded();
+
+ this.isConstructed = isExplicit || asn1Obj is Asn1Set || asn1Obj is Asn1Sequence;
+ this.tag = tag;
+
+ if (isExplicit)
+ {
+ this.octets = data;
+ }
+ else
+ {
+ int lenBytes = GetLengthOfHeader(data);
+ byte[] tmp = new byte[data.Length - lenBytes];
+ Array.Copy(data, lenBytes, tmp, 0, tmp.Length);
+ this.octets = tmp;
+ }
+ }
+
+ public DerApplicationSpecific(
+ int tagNo,
+ Asn1EncodableVector vec)
+ {
+ this.tag = tagNo;
+ this.isConstructed = true;
+ MemoryStream bOut = new MemoryStream();
+
+ for (int i = 0; i != vec.Count; i++)
+ {
+ try
+ {
+ byte[] bs = vec[i].GetDerEncoded();
+ bOut.Write(bs, 0, bs.Length);
+ }
+ catch (IOException e)
+ {
+ throw new InvalidOperationException("malformed object", e);
+ }
+ }
+ this.octets = bOut.ToArray();
+ }
+
+ private int GetLengthOfHeader(
+ byte[] data)
+ {
+ int length = data[1]; // 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 InvalidOperationException("DER length more than 4 bytes: " + size);
+ }
+
+ return size + 2;
+ }
+
+ return 2;
+ }
+
+ public bool IsConstructed()
+ {
+ return isConstructed;
+ }
+
+ public byte[] GetContents()
+ {
+ return octets;
+ }
+
+ public int ApplicationTag
+ {
+ get { return tag; }
+ }
+
+ /**
+ * Return the enclosed object assuming explicit tagging.
+ *
+ * @return the resulting object
+ * @throws IOException if reconstruction fails.
+ */
+ public Asn1Object GetObject()
+ {
+ return FromByteArray(GetContents());
+ }
+
+ /**
+ * 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 Asn1Object GetObject(
+ int derTagNo)
+ {
+ if (derTagNo >= 0x1f)
+ throw new IOException("unsupported tag number");
+
+ byte[] orig = this.GetEncoded();
+ byte[] tmp = ReplaceTagNumber(derTagNo, orig);
+
+ if ((orig[0] & Asn1Tags.Constructed) != 0)
+ {
+ tmp[0] |= Asn1Tags.Constructed;
+ }
+
+ return FromByteArray(tmp);;
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ int classBits = Asn1Tags.Application;
+ if (isConstructed)
+ {
+ classBits |= Asn1Tags.Constructed;
+ }
+
+ derOut.WriteEncoded(classBits, tag, octets);
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerApplicationSpecific other = asn1Object as DerApplicationSpecific;
+
+ if (other == null)
+ return false;
+
+ return this.isConstructed == other.isConstructed
+ && this.tag == other.tag
+ && Arrays.AreEqual(this.octets, other.octets);
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return isConstructed.GetHashCode() ^ tag.GetHashCode() ^ Arrays.GetHashCode(octets);
+ }
+
+ private byte[] ReplaceTagNumber(
+ int newTag,
+ byte[] input)
+ {
+ 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 InvalidOperationException("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];
+
+ Array.Copy(input, index, tmp, 1, tmp.Length - 1);
+
+ tmp[0] = (byte)newTag;
+
+ return tmp;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerBMPString.cs b/Crypto/src/asn1/DerBMPString.cs
new file mode 100644
index 000000000..4f7e0a635
--- /dev/null
+++ b/Crypto/src/asn1/DerBMPString.cs
@@ -0,0 +1,115 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * Der BMPString object.
+ */
+ public class DerBmpString
+ : DerStringBase
+ {
+ private readonly string str;
+
+ /**
+ * return a BMP string from the given object.
+ *
+ * @param obj the object we want converted.
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerBmpString GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerBmpString)
+ {
+ return (DerBmpString)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name);
+ }
+
+ /**
+ * return a BMP string from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerBmpString GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerBmpString)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerBmpString(Asn1OctetString.GetInstance(o).GetOctets());
+ }
+
+ /**
+ * basic constructor - byte encoded string.
+ */
+ public DerBmpString(
+ byte[] str)
+ {
+ if (str == null)
+ throw new ArgumentNullException("str");
+
+ char[] cs = new char[str.Length / 2];
+
+ for (int i = 0; i != cs.Length; i++)
+ {
+ cs[i] = (char)((str[2 * i] << 8) | (str[2 * i + 1] & 0xff));
+ }
+
+ this.str = new string(cs);
+ }
+
+ /**
+ * basic constructor
+ */
+ public DerBmpString(
+ string str)
+ {
+ if (str == null)
+ throw new ArgumentNullException("str");
+
+ this.str = str;
+ }
+
+ public override string GetString()
+ {
+ return str;
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerBmpString other = asn1Object as DerBmpString;
+
+ if (other == null)
+ return false;
+
+ return this.str.Equals(other.str);
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ char[] c = str.ToCharArray();
+ byte[] b = new byte[c.Length * 2];
+
+ for (int i = 0; i != c.Length; i++)
+ {
+ b[2 * i] = (byte)(c[i] >> 8);
+ b[2 * i + 1] = (byte)c[i];
+ }
+
+ derOut.WriteEncoded(Asn1Tags.BmpString, b);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerBitString.cs b/Crypto/src/asn1/DerBitString.cs
new file mode 100644
index 000000000..d5cb872bc
--- /dev/null
+++ b/Crypto/src/asn1/DerBitString.cs
@@ -0,0 +1,248 @@
+using System;
+using System.Text;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class DerBitString
+ : DerStringBase
+ {
+ private static readonly char[] table
+ = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+
+ private readonly byte[] data;
+ private readonly int padBits;
+
+ /**
+ * return the correct number of pad bits for a bit string defined in
+ * a 32 bit constant
+ */
+ static internal int GetPadBits(
+ int bitString)
+ {
+ int val = 0;
+ for (int i = 3; i >= 0; i--)
+ {
+ //
+ // this may look a little odd, but if it isn't done like this pre jdk1.2
+ // JVM's break!
+ //
+ if (i != 0)
+ {
+ if ((bitString >> (i * 8)) != 0)
+ {
+ val = (bitString >> (i * 8)) & 0xFF;
+ break;
+ }
+ }
+ else
+ {
+ if (bitString != 0)
+ {
+ val = bitString & 0xFF;
+ break;
+ }
+ }
+ }
+
+ if (val == 0)
+ {
+ return 7;
+ }
+
+ int bits = 1;
+
+ while (((val <<= 1) & 0xFF) != 0)
+ {
+ bits++;
+ }
+
+ return 8 - bits;
+ }
+
+ /**
+ * return the correct number of bytes for a bit string defined in
+ * a 32 bit constant
+ */
+ static internal byte[] GetBytes(
+ int bitString)
+ {
+ int bytes = 4;
+ for (int i = 3; i >= 1; i--)
+ {
+ if ((bitString & (0xFF << (i * 8))) != 0)
+ {
+ break;
+ }
+ bytes--;
+ }
+
+ byte[] result = new byte[bytes];
+ for (int i = 0; i < bytes; i++)
+ {
+ result[i] = (byte) ((bitString >> (i * 8)) & 0xFF);
+ }
+
+ return result;
+ }
+
+ /**
+ * return a Bit string from the passed in object
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerBitString GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerBitString)
+ {
+ return (DerBitString) obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name);
+ }
+
+ /**
+ * return a Bit string from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerBitString GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerBitString)
+ {
+ return GetInstance(o);
+ }
+
+ return FromAsn1Octets(((Asn1OctetString)o).GetOctets());
+ }
+
+ internal DerBitString(
+ byte data,
+ int padBits)
+ {
+ this.data = new byte[]{ data };
+ this.padBits = padBits;
+ }
+
+ /**
+ * @param data the octets making up the bit string.
+ * @param padBits the number of extra bits at the end of the string.
+ */
+ public DerBitString(
+ byte[] data,
+ int padBits)
+ {
+ // TODO Deep copy?
+ this.data = data;
+ this.padBits = padBits;
+ }
+
+ public DerBitString(
+ byte[] data)
+ {
+ // TODO Deep copy?
+ this.data = data;
+ }
+
+ public DerBitString(
+ Asn1Encodable obj)
+ {
+ this.data = obj.GetDerEncoded();
+ //this.padBits = 0;
+ }
+
+ public byte[] GetBytes()
+ {
+ return data;
+ }
+
+ public int PadBits
+ {
+ get { return padBits; }
+ }
+
+ /**
+ * @return the value of the bit string as an int (truncating if necessary)
+ */
+ public int IntValue
+ {
+ get
+ {
+ int value = 0;
+
+ for (int i = 0; i != data.Length && i != 4; i++)
+ {
+ value |= (data[i] & 0xff) << (8 * i);
+ }
+
+ return value;
+ }
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ byte[] bytes = new byte[GetBytes().Length + 1];
+
+ bytes[0] = (byte) PadBits;
+ Array.Copy(GetBytes(), 0, bytes, 1, bytes.Length - 1);
+
+ derOut.WriteEncoded(Asn1Tags.BitString, bytes);
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return padBits.GetHashCode() ^ Arrays.GetHashCode(data);
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerBitString other = asn1Object as DerBitString;
+
+ if (other == null)
+ return false;
+
+ return this.padBits == other.padBits
+ && Arrays.AreEqual(this.data, other.data);
+ }
+
+ public override string GetString()
+ {
+ StringBuilder buffer = new StringBuilder("#");
+
+ byte[] str = GetDerEncoded();
+
+ for (int i = 0; i != str.Length; i++)
+ {
+ uint ubyte = str[i];
+ buffer.Append(table[(ubyte >> 4) & 0xf]);
+ buffer.Append(table[str[i] & 0xf]);
+ }
+
+ return buffer.ToString();
+ }
+
+ internal static DerBitString FromAsn1Octets(byte[] octets)
+ {
+ if (octets.Length < 1)
+ throw new ArgumentException("truncated BIT STRING detected");
+
+ int padBits = octets[0];
+ byte[] data = new byte[octets.Length - 1];
+ Array.Copy(octets, 1, data, 0, data.Length);
+ return new DerBitString(data, padBits);
+ }
+ }
+}
+
diff --git a/Crypto/src/asn1/DerBoolean.cs b/Crypto/src/asn1/DerBoolean.cs
new file mode 100644
index 000000000..41ccae8a1
--- /dev/null
+++ b/Crypto/src/asn1/DerBoolean.cs
@@ -0,0 +1,110 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class DerBoolean
+ : Asn1Object
+ {
+ private readonly byte value;
+
+ public static readonly DerBoolean False = new DerBoolean(false);
+ public static readonly DerBoolean True = new DerBoolean(true);
+
+ /**
+ * return a bool from the passed in object.
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerBoolean GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerBoolean)
+ {
+ return (DerBoolean) obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name);
+ }
+
+ /**
+ * return a DerBoolean from the passed in bool.
+ */
+ public static DerBoolean GetInstance(
+ bool value)
+ {
+ return value ? True : False;
+ }
+
+ /**
+ * return a Boolean from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerBoolean GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerBoolean)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerBoolean(((Asn1OctetString)o).GetOctets());
+ }
+
+ public DerBoolean(
+ byte[] val)
+ {
+ if (val.Length != 1)
+ throw new ArgumentException("byte value should have 1 byte in it", "val");
+
+ // TODO Are there any constraints on the possible byte values?
+ this.value = val[0];
+ }
+
+ private DerBoolean(
+ bool value)
+ {
+ this.value = value ? (byte)0xff : (byte)0;
+ }
+
+ public bool IsTrue
+ {
+ get { return value != 0; }
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ // TODO Should we make sure the byte value is one of '0' or '0xff' here?
+ derOut.WriteEncoded(Asn1Tags.Boolean, new byte[]{ value });
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerBoolean other = asn1Object as DerBoolean;
+
+ if (other == null)
+ return false;
+
+ return IsTrue == other.IsTrue;
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return IsTrue.GetHashCode();
+ }
+
+ public override string ToString()
+ {
+ return IsTrue ? "TRUE" : "FALSE";
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerEnumerated.cs b/Crypto/src/asn1/DerEnumerated.cs
new file mode 100644
index 000000000..0e67e6dbe
--- /dev/null
+++ b/Crypto/src/asn1/DerEnumerated.cs
@@ -0,0 +1,100 @@
+using System;
+
+using Org.BouncyCastle.Math;
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class DerEnumerated
+ : Asn1Object
+ {
+ private readonly byte[] bytes;
+
+ /**
+ * return an integer from the passed in object
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerEnumerated GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerEnumerated)
+ {
+ return (DerEnumerated)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name);
+ }
+
+ /**
+ * return an Enumerated from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerEnumerated GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerEnumerated)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerEnumerated(((Asn1OctetString)o).GetOctets());
+ }
+
+ public DerEnumerated(
+ int val)
+ {
+ bytes = BigInteger.ValueOf(val).ToByteArray();
+ }
+
+ public DerEnumerated(
+ BigInteger val)
+ {
+ bytes = val.ToByteArray();
+ }
+
+ public DerEnumerated(
+ byte[] bytes)
+ {
+ this.bytes = bytes;
+ }
+
+ public BigInteger Value
+ {
+ get
+ {
+ return new BigInteger(bytes);
+ }
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.Enumerated, bytes);
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerEnumerated other = asn1Object as DerEnumerated;
+
+ if (other == null)
+ return false;
+
+ return Arrays.AreEqual(this.bytes, other.bytes);
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return Arrays.GetHashCode(bytes);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerGeneralString.cs b/Crypto/src/asn1/DerGeneralString.cs
new file mode 100644
index 000000000..0e20b53bd
--- /dev/null
+++ b/Crypto/src/asn1/DerGeneralString.cs
@@ -0,0 +1,81 @@
+using System;
+using System.Text;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class DerGeneralString
+ : DerStringBase
+ {
+ private readonly string str;
+
+ public static DerGeneralString GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerGeneralString)
+ {
+ return (DerGeneralString) obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: "
+ + obj.GetType().Name);
+ }
+
+ public static DerGeneralString GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerGeneralString)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerGeneralString(((Asn1OctetString)o).GetOctets());
+ }
+
+ public DerGeneralString(
+ byte[] str)
+ : this(Strings.FromAsciiByteArray(str))
+ {
+ }
+
+ public DerGeneralString(
+ string str)
+ {
+ if (str == null)
+ throw new ArgumentNullException("str");
+
+ this.str = str;
+ }
+
+ public override string GetString()
+ {
+ return str;
+ }
+
+ public byte[] GetOctets()
+ {
+ return Strings.ToAsciiByteArray(str);
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.GeneralString, GetOctets());
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerGeneralString other = asn1Object as DerGeneralString;
+
+ if (other == null)
+ return false;
+
+ return this.str.Equals(other.str);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerGeneralizedTime.cs b/Crypto/src/asn1/DerGeneralizedTime.cs
new file mode 100644
index 000000000..0a0e6fd7c
--- /dev/null
+++ b/Crypto/src/asn1/DerGeneralizedTime.cs
@@ -0,0 +1,305 @@
+using System;
+using System.Globalization;
+using System.Text;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * Generalized time object.
+ */
+ public class DerGeneralizedTime
+ : Asn1Object
+ {
+ private readonly string time;
+
+ /**
+ * return a generalized time from the passed in object
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerGeneralizedTime GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerGeneralizedTime)
+ {
+ return (DerGeneralizedTime)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name, "obj");
+ }
+
+ /**
+ * return a Generalized Time object from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerGeneralizedTime GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerGeneralizedTime)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerGeneralizedTime(((Asn1OctetString)o).GetOctets());
+ }
+
+ /**
+ * The correct format for this is YYYYMMDDHHMMSS[.f]Z, or without the Z
+ * for local time, or Z+-HHMM on the end, for difference between local
+ * time and UTC time. The fractional second amount f must consist of at
+ * least one number with trailing zeroes removed.
+ *
+ * @param time the time string.
+ * @exception ArgumentException if string is an illegal format.
+ */
+ public DerGeneralizedTime(
+ string time)
+ {
+ this.time = time;
+
+ try
+ {
+ ToDateTime();
+ }
+ catch (FormatException e)
+ {
+ throw new ArgumentException("invalid date string: " + e.Message);
+ }
+ }
+
+ /**
+ * base constructor from a local time object
+ */
+ public DerGeneralizedTime(
+ DateTime time)
+ {
+ this.time = time.ToString(@"yyyyMMddHHmmss\Z");
+ }
+
+ internal DerGeneralizedTime(
+ byte[] bytes)
+ {
+ //
+ // explicitly convert to characters
+ //
+ this.time = Strings.FromAsciiByteArray(bytes);
+ }
+
+ /**
+ * Return the time.
+ * @return The time string as it appeared in the encoded object.
+ */
+ public string TimeString
+ {
+ get { return time; }
+ }
+
+ /**
+ * return the time - always in the form of
+ * YYYYMMDDhhmmssGMT(+hh:mm|-hh:mm).
+ *
+ * Normally in a certificate we would expect "Z" rather than "GMT",
+ * however adding the "GMT" means we can just use:
+ *
+ * dateF = new SimpleDateFormat("yyyyMMddHHmmssz");
+ *
+ * To read in the time and Get a date which is compatible with our local
+ * time zone.
+ */
+ public string GetTime()
+ {
+ //
+ // standardise the format.
+ //
+ if (time[time.Length - 1] == 'Z')
+ {
+ return time.Substring(0, time.Length - 1) + "GMT+00:00";
+ }
+ else
+ {
+ int signPos = time.Length - 5;
+ char sign = time[signPos];
+ if (sign == '-' || sign == '+')
+ {
+ return time.Substring(0, signPos)
+ + "GMT"
+ + time.Substring(signPos, 3)
+ + ":"
+ + time.Substring(signPos + 3);
+ }
+ else
+ {
+ signPos = time.Length - 3;
+ sign = time[signPos];
+ if (sign == '-' || sign == '+')
+ {
+ return time.Substring(0, signPos)
+ + "GMT"
+ + time.Substring(signPos)
+ + ":00";
+ }
+ }
+ }
+
+ return time + CalculateGmtOffset();
+ }
+
+ private string CalculateGmtOffset()
+ {
+ char sign = '+';
+ DateTime time = ToDateTime();
+
+#if (SILVERLIGHT || PORTABLE)
+ long offset = time.Ticks - time.ToUniversalTime().Ticks;
+ if (offset < 0)
+ {
+ sign = '-';
+ offset = -offset;
+ }
+ int hours = (int)(offset / TimeSpan.TicksPerHour);
+ int minutes = (int)(offset / TimeSpan.TicksPerMinute) % 60;
+#else
+ // Note: GetUtcOffset incorporates Daylight Savings offset
+ TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset(time);
+ if (offset.CompareTo(TimeSpan.Zero) < 0)
+ {
+ sign = '-';
+ offset = offset.Duration();
+ }
+ int hours = offset.Hours;
+ int minutes = offset.Minutes;
+#endif
+
+ return "GMT" + sign + Convert(hours) + ":" + Convert(minutes);
+ }
+
+ private static string Convert(
+ int time)
+ {
+ if (time < 10)
+ {
+ return "0" + time;
+ }
+
+ return time.ToString();
+ }
+
+ public DateTime ToDateTime()
+ {
+ string formatStr;
+ string d = time;
+ bool makeUniversal = false;
+
+ if (d.EndsWith("Z"))
+ {
+ if (HasFractionalSeconds)
+ {
+ int fCount = d.Length - d.IndexOf('.') - 2;
+ formatStr = @"yyyyMMddHHmmss." + FString(fCount) + @"\Z";
+ }
+ else
+ {
+ formatStr = @"yyyyMMddHHmmss\Z";
+ }
+ }
+ else if (time.IndexOf('-') > 0 || time.IndexOf('+') > 0)
+ {
+ d = GetTime();
+ makeUniversal = true;
+
+ if (HasFractionalSeconds)
+ {
+ int fCount = d.IndexOf("GMT") - 1 - d.IndexOf('.');
+ formatStr = @"yyyyMMddHHmmss." + FString(fCount) + @"'GMT'zzz";
+ }
+ else
+ {
+ formatStr = @"yyyyMMddHHmmss'GMT'zzz";
+ }
+ }
+ else
+ {
+ if (HasFractionalSeconds)
+ {
+ int fCount = d.Length - 1 - d.IndexOf('.');
+ formatStr = @"yyyyMMddHHmmss." + FString(fCount);
+ }
+ else
+ {
+ formatStr = @"yyyyMMddHHmmss";
+ }
+
+ // TODO?
+// dateF.setTimeZone(new SimpleTimeZone(0, TimeZone.getDefault().getID()));
+ }
+
+ return ParseDateString(d, formatStr, makeUniversal);
+ }
+
+ private string FString(
+ int count)
+ {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < count; ++i)
+ {
+ sb.Append('f');
+ }
+ return sb.ToString();
+ }
+
+ private DateTime ParseDateString(
+ string dateStr,
+ string formatStr,
+ bool makeUniversal)
+ {
+ DateTime dt = DateTime.ParseExact(
+ dateStr,
+ formatStr,
+ DateTimeFormatInfo.InvariantInfo);
+
+ return makeUniversal ? dt.ToUniversalTime() : dt;
+ }
+
+ private bool HasFractionalSeconds
+ {
+ get { return time.IndexOf('.') == 14; }
+ }
+
+ private byte[] GetOctets()
+ {
+ return Strings.ToAsciiByteArray(time);
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.GeneralizedTime, GetOctets());
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerGeneralizedTime other = asn1Object as DerGeneralizedTime;
+
+ if (other == null)
+ return false;
+
+ return this.time.Equals(other.time);
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return time.GetHashCode();
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerIA5String.cs b/Crypto/src/asn1/DerIA5String.cs
new file mode 100644
index 000000000..9fa2cba3c
--- /dev/null
+++ b/Crypto/src/asn1/DerIA5String.cs
@@ -0,0 +1,145 @@
+using System;
+using System.Text;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * Der IA5String object - this is an ascii string.
+ */
+ public class DerIA5String
+ : DerStringBase
+ {
+ private readonly string str;
+
+ /**
+ * return a IA5 string from the passed in object
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerIA5String GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerIA5String)
+ {
+ return (DerIA5String)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name);
+ }
+
+ /**
+ * return an IA5 string from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerIA5String GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerIA5String)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerIA5String(((Asn1OctetString)o).GetOctets());
+ }
+
+ /**
+ * basic constructor - with bytes.
+ */
+ public DerIA5String(
+ byte[] str)
+ : this(Strings.FromAsciiByteArray(str), false)
+ {
+ }
+
+ /**
+ * basic constructor - without validation.
+ */
+ public DerIA5String(
+ string str)
+ : this(str, false)
+ {
+ }
+
+ /**
+ * Constructor with optional validation.
+ *
+ * @param string the base string to wrap.
+ * @param validate whether or not to check the string.
+ * @throws ArgumentException if validate is true and the string
+ * contains characters that should not be in an IA5String.
+ */
+ public DerIA5String(
+ string str,
+ bool validate)
+ {
+ if (str == null)
+ throw new ArgumentNullException("str");
+ if (validate && !IsIA5String(str))
+ throw new ArgumentException("string contains illegal characters", "str");
+
+ this.str = str;
+ }
+
+ public override string GetString()
+ {
+ return str;
+ }
+
+ public byte[] GetOctets()
+ {
+ return Strings.ToAsciiByteArray(str);
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.IA5String, GetOctets());
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return this.str.GetHashCode();
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerIA5String other = asn1Object as DerIA5String;
+
+ if (other == null)
+ return false;
+
+ return this.str.Equals(other.str);
+ }
+
+ /**
+ * return true if the passed in String can be represented without
+ * loss as an IA5String, false otherwise.
+ *
+ * @return true if in printable set, false otherwise.
+ */
+ public static bool IsIA5String(
+ string str)
+ {
+ foreach (char ch in str)
+ {
+ if (ch > 0x007f)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerInteger.cs b/Crypto/src/asn1/DerInteger.cs
new file mode 100644
index 000000000..eb0614515
--- /dev/null
+++ b/Crypto/src/asn1/DerInteger.cs
@@ -0,0 +1,117 @@
+using System;
+
+using Org.BouncyCastle.Math;
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class DerInteger
+ : Asn1Object
+ {
+ private readonly byte[] bytes;
+
+ /**
+ * return an integer from the passed in object
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerInteger GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerInteger)
+ {
+ return (DerInteger)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name);
+ }
+
+ /**
+ * return an Integer from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param isExplicit true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerInteger GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ if (obj == null)
+ throw new ArgumentNullException("obj");
+
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerInteger)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerInteger(Asn1OctetString.GetInstance(o).GetOctets());
+ }
+
+ public DerInteger(
+ int value)
+ {
+ bytes = BigInteger.ValueOf(value).ToByteArray();
+ }
+
+ public DerInteger(
+ BigInteger value)
+ {
+ if (value == null)
+ throw new ArgumentNullException("value");
+
+ bytes = value.ToByteArray();
+ }
+
+ public DerInteger(
+ byte[] bytes)
+ {
+ this.bytes = bytes;
+ }
+
+ public BigInteger Value
+ {
+ get { return new BigInteger(bytes); }
+ }
+
+ /**
+ * in some cases positive values Get crammed into a space,
+ * that's not quite big enough...
+ */
+ public BigInteger PositiveValue
+ {
+ get { return new BigInteger(1, bytes); }
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.Integer, bytes);
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return Arrays.GetHashCode(bytes);
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerInteger other = asn1Object as DerInteger;
+
+ if (other == null)
+ return false;
+
+ return Arrays.AreEqual(this.bytes, other.bytes);
+ }
+
+ public override string ToString()
+ {
+ return Value.ToString();
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerNull.cs b/Crypto/src/asn1/DerNull.cs
new file mode 100644
index 000000000..a802f6486
--- /dev/null
+++ b/Crypto/src/asn1/DerNull.cs
@@ -0,0 +1,41 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * A Null object.
+ */
+ public class DerNull
+ : Asn1Null
+ {
+ public static readonly DerNull Instance = new DerNull(0);
+
+ byte[] zeroBytes = new byte[0];
+
+ [Obsolete("Use static Instance object")]
+ public DerNull()
+ {
+ }
+
+ protected internal DerNull(int dummy)
+ {
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.Null, zeroBytes);
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ return asn1Object is DerNull;
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return -1;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerNumericString.cs b/Crypto/src/asn1/DerNumericString.cs
new file mode 100644
index 000000000..6e2715a4d
--- /dev/null
+++ b/Crypto/src/asn1/DerNumericString.cs
@@ -0,0 +1,138 @@
+using System;
+using System.Text;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * Der NumericString object - this is an ascii string of characters {0,1,2,3,4,5,6,7,8,9, }.
+ */
+ public class DerNumericString
+ : DerStringBase
+ {
+ private readonly string str;
+
+ /**
+ * return a Numeric string from the passed in object
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerNumericString GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerNumericString)
+ {
+ return (DerNumericString)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name);
+ }
+
+ /**
+ * return an Numeric string from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerNumericString GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerNumericString)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerNumericString(Asn1OctetString.GetInstance(o).GetOctets());
+ }
+
+ /**
+ * basic constructor - with bytes.
+ */
+ public DerNumericString(
+ byte[] str)
+ : this(Strings.FromAsciiByteArray(str), false)
+ {
+ }
+
+ /**
+ * basic constructor - without validation..
+ */
+ public DerNumericString(
+ string str)
+ : this(str, false)
+ {
+ }
+
+ /**
+ * Constructor with optional validation.
+ *
+ * @param string the base string to wrap.
+ * @param validate whether or not to check the string.
+ * @throws ArgumentException if validate is true and the string
+ * contains characters that should not be in a NumericString.
+ */
+ public DerNumericString(
+ string str,
+ bool validate)
+ {
+ if (str == null)
+ throw new ArgumentNullException("str");
+ if (validate && !IsNumericString(str))
+ throw new ArgumentException("string contains illegal characters", "str");
+
+ this.str = str;
+ }
+
+ public override string GetString()
+ {
+ return str;
+ }
+
+ public byte[] GetOctets()
+ {
+ return Strings.ToAsciiByteArray(str);
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.NumericString, GetOctets());
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerNumericString other = asn1Object as DerNumericString;
+
+ if (other == null)
+ return false;
+
+ return this.str.Equals(other.str);
+ }
+
+ /**
+ * Return true if the string can be represented as a NumericString ('0'..'9', ' ')
+ *
+ * @param str string to validate.
+ * @return true if numeric, fale otherwise.
+ */
+ public static bool IsNumericString(
+ string str)
+ {
+ foreach (char ch in str)
+ {
+ if (ch > 0x007f || (ch != ' ' && !char.IsDigit(ch)))
+ return false;
+ }
+
+ return true;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerObjectIdentifier.cs b/Crypto/src/asn1/DerObjectIdentifier.cs
new file mode 100644
index 000000000..7dc963729
--- /dev/null
+++ b/Crypto/src/asn1/DerObjectIdentifier.cs
@@ -0,0 +1,242 @@
+using System;
+using System.IO;
+using System.Text;
+using System.Text.RegularExpressions;
+
+using Org.BouncyCastle.Math;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class DerObjectIdentifier
+ : Asn1Object
+ {
+ private static readonly Regex OidRegex = new Regex(@"\A[0-2](\.[0-9]+)+\z");
+
+ private readonly string identifier;
+
+ /**
+ * return an Oid from the passed in object
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerObjectIdentifier GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerObjectIdentifier)
+ {
+ return (DerObjectIdentifier) obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name, "obj");
+ }
+
+ /**
+ * return an object Identifier from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerObjectIdentifier GetInstance(
+ Asn1TaggedObject obj,
+ bool explicitly)
+ {
+ return GetInstance(obj.GetObject());
+ }
+
+ public DerObjectIdentifier(
+ string identifier)
+ {
+ if (identifier == null)
+ throw new ArgumentNullException("identifier");
+ if (!OidRegex.IsMatch(identifier))
+ throw new FormatException("string " + identifier + " not an OID");
+
+ this.identifier = identifier;
+ }
+
+ // TODO Change to ID?
+ public string Id
+ {
+ get { return identifier; }
+ }
+
+ public virtual DerObjectIdentifier Branch(string branchID)
+ {
+ return new DerObjectIdentifier(identifier + "." + branchID);
+ }
+
+ /**
+ * Return true if this oid is an extension of the passed in branch, stem.
+ * @param stem the arc or branch that is a possible parent.
+ * @return true if the branch is on the passed in stem, false otherwise.
+ */
+ public virtual bool On(DerObjectIdentifier stem)
+ {
+ string id = Id, stemId = stem.Id;
+ return id.Length > stemId.Length && id[stemId.Length] == '.' && id.StartsWith(stemId);
+ }
+
+ internal DerObjectIdentifier(
+ byte[] bytes)
+ : this(MakeOidStringFromBytes(bytes))
+ {
+ }
+
+ private void WriteField(
+ Stream outputStream,
+ long fieldValue)
+ {
+ byte[] result = new byte[9];
+ int pos = 8;
+ result[pos] = (byte)(fieldValue & 0x7f);
+ while (fieldValue >= (1L << 7))
+ {
+ fieldValue >>= 7;
+ result[--pos] = (byte)((fieldValue & 0x7f) | 0x80);
+ }
+ outputStream.Write(result, pos, 9 - pos);
+ }
+
+ private void WriteField(
+ Stream outputStream,
+ BigInteger fieldValue)
+ {
+ int byteCount = (fieldValue.BitLength + 6) / 7;
+ if (byteCount == 0)
+ {
+ outputStream.WriteByte(0);
+ }
+ else
+ {
+ BigInteger tmpValue = fieldValue;
+ byte[] tmp = new byte[byteCount];
+ for (int i = byteCount-1; i >= 0; i--)
+ {
+ tmp[i] = (byte) ((tmpValue.IntValue & 0x7f) | 0x80);
+ tmpValue = tmpValue.ShiftRight(7);
+ }
+ tmp[byteCount-1] &= 0x7f;
+ outputStream.Write(tmp, 0, tmp.Length);
+ }
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ OidTokenizer tok = new OidTokenizer(identifier);
+ MemoryStream bOut = new MemoryStream();
+ DerOutputStream dOut = new DerOutputStream(bOut);
+
+ string token = tok.NextToken();
+ int first = int.Parse(token);
+
+ token = tok.NextToken();
+ int second = int.Parse(token);
+
+ WriteField(bOut, first * 40 + second);
+
+ while (tok.HasMoreTokens)
+ {
+ token = tok.NextToken();
+ if (token.Length < 18)
+ {
+ WriteField(bOut, Int64.Parse(token));
+ }
+ else
+ {
+ WriteField(bOut, new BigInteger(token));
+ }
+ }
+
+ dOut.Dispose();
+
+ derOut.WriteEncoded(Asn1Tags.ObjectIdentifier, bOut.ToArray());
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return identifier.GetHashCode();
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerObjectIdentifier other = asn1Object as DerObjectIdentifier;
+
+ if (other == null)
+ return false;
+
+ return this.identifier.Equals(other.identifier);
+ }
+
+ public override string ToString()
+ {
+ return identifier;
+ }
+
+ private static string MakeOidStringFromBytes(
+ byte[] bytes)
+ {
+ StringBuilder objId = new StringBuilder();
+ long value = 0;
+ BigInteger bigValue = null;
+ bool first = true;
+
+ for (int i = 0; i != bytes.Length; i++)
+ {
+ int b = bytes[i];
+
+ if (value < 0x80000000000000L)
+ {
+ value = value * 128 + (b & 0x7f);
+ if ((b & 0x80) == 0) // end of number reached
+ {
+ if (first)
+ {
+ switch ((int)value / 40)
+ {
+ case 0:
+ objId.Append('0');
+ break;
+ case 1:
+ objId.Append('1');
+ value -= 40;
+ break;
+ default:
+ objId.Append('2');
+ value -= 80;
+ break;
+ }
+ first = false;
+ }
+
+ objId.Append('.');
+ objId.Append(value);
+ value = 0;
+ }
+ }
+ else
+ {
+ if (bigValue == null)
+ {
+ bigValue = BigInteger.ValueOf(value);
+ }
+ bigValue = bigValue.ShiftLeft(7);
+ bigValue = bigValue.Or(BigInteger.ValueOf(b & 0x7f));
+ if ((b & 0x80) == 0)
+ {
+ objId.Append('.');
+ objId.Append(bigValue);
+ bigValue = null;
+ value = 0;
+ }
+ }
+ }
+
+ return objId.ToString();
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerOctetString.cs b/Crypto/src/asn1/DerOctetString.cs
new file mode 100644
index 000000000..c046c9402
--- /dev/null
+++ b/Crypto/src/asn1/DerOctetString.cs
@@ -0,0 +1,34 @@
+namespace Org.BouncyCastle.Asn1
+{
+ public class DerOctetString
+ : Asn1OctetString
+ {
+ /// The octets making up the octet string.
+ public DerOctetString(
+ byte[] str)
+ : base(str)
+ {
+ }
+
+ public DerOctetString(
+ Asn1Encodable obj)
+ : base(obj)
+ {
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.OctetString, str);
+ }
+
+ internal static void Encode(
+ DerOutputStream derOut,
+ byte[] bytes,
+ int offset,
+ int length)
+ {
+ derOut.WriteEncoded(Asn1Tags.OctetString, bytes, offset, length);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerOutputStream.cs b/Crypto/src/asn1/DerOutputStream.cs
new file mode 100644
index 000000000..f95d123f9
--- /dev/null
+++ b/Crypto/src/asn1/DerOutputStream.cs
@@ -0,0 +1,160 @@
+using System;
+using System.IO;
+
+using Org.BouncyCastle.Asn1.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class DerOutputStream
+ : FilterStream
+ {
+ public DerOutputStream(Stream os)
+ : base(os)
+ {
+ }
+
+ private void WriteLength(
+ int length)
+ {
+ if (length > 127)
+ {
+ int size = 1;
+ uint val = (uint) length;
+
+ while ((val >>= 8) != 0)
+ {
+ size++;
+ }
+
+ WriteByte((byte)(size | 0x80));
+
+ for (int i = (size - 1) * 8; i >= 0; i -= 8)
+ {
+ WriteByte((byte)(length >> i));
+ }
+ }
+ else
+ {
+ WriteByte((byte)length);
+ }
+ }
+
+ internal void WriteEncoded(
+ int tag,
+ byte[] bytes)
+ {
+ WriteByte((byte) tag);
+ WriteLength(bytes.Length);
+ Write(bytes, 0, bytes.Length);
+ }
+
+ internal void WriteEncoded(
+ int tag,
+ byte[] bytes,
+ int offset,
+ int length)
+ {
+ WriteByte((byte) tag);
+ WriteLength(length);
+ Write(bytes, offset, length);
+ }
+
+ internal void WriteTag(
+ int flags,
+ int tagNo)
+ {
+ if (tagNo < 31)
+ {
+ WriteByte((byte)(flags | tagNo));
+ }
+ else
+ {
+ WriteByte((byte)(flags | 0x1f));
+ if (tagNo < 128)
+ {
+ WriteByte((byte)tagNo);
+ }
+ 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);
+
+ Write(stack, pos, stack.Length - pos);
+ }
+ }
+ }
+
+ internal void WriteEncoded(
+ int flags,
+ int tagNo,
+ byte[] bytes)
+ {
+ WriteTag(flags, tagNo);
+ WriteLength(bytes.Length);
+ Write(bytes, 0, bytes.Length);
+ }
+
+ protected void WriteNull()
+ {
+ WriteByte(Asn1Tags.Null);
+ WriteByte(0x00);
+ }
+
+ [Obsolete("Use version taking an Asn1Encodable arg instead")]
+ public virtual void WriteObject(
+ object obj)
+ {
+ if (obj == null)
+ {
+ WriteNull();
+ }
+ else if (obj is Asn1Object)
+ {
+ ((Asn1Object)obj).Encode(this);
+ }
+ else if (obj is Asn1Encodable)
+ {
+ ((Asn1Encodable)obj).ToAsn1Object().Encode(this);
+ }
+ else
+ {
+ throw new IOException("object not Asn1Object");
+ }
+ }
+
+ public virtual void WriteObject(
+ Asn1Encodable obj)
+ {
+ if (obj == null)
+ {
+ WriteNull();
+ }
+ else
+ {
+ obj.ToAsn1Object().Encode(this);
+ }
+ }
+
+ public virtual void WriteObject(
+ Asn1Object obj)
+ {
+ if (obj == null)
+ {
+ WriteNull();
+ }
+ else
+ {
+ obj.Encode(this);
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerPrintableString.cs b/Crypto/src/asn1/DerPrintableString.cs
new file mode 100644
index 000000000..cd2f46b48
--- /dev/null
+++ b/Crypto/src/asn1/DerPrintableString.cs
@@ -0,0 +1,163 @@
+using System;
+using System.Text;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * Der PrintableString object.
+ */
+ public class DerPrintableString
+ : DerStringBase
+ {
+ private readonly string str;
+
+ /**
+ * return a printable string from the passed in object.
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerPrintableString GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerPrintableString)
+ {
+ return (DerPrintableString)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name);
+ }
+
+ /**
+ * return a Printable string from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerPrintableString GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerPrintableString)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerPrintableString(Asn1OctetString.GetInstance(o).GetOctets());
+ }
+
+ /**
+ * basic constructor - byte encoded string.
+ */
+ public DerPrintableString(
+ byte[] str)
+ : this(Strings.FromAsciiByteArray(str), false)
+ {
+ }
+
+ /**
+ * basic constructor - this does not validate the string
+ */
+ public DerPrintableString(
+ string str)
+ : this(str, false)
+ {
+ }
+
+ /**
+ * Constructor with optional validation.
+ *
+ * @param string the base string to wrap.
+ * @param validate whether or not to check the string.
+ * @throws ArgumentException if validate is true and the string
+ * contains characters that should not be in a PrintableString.
+ */
+ public DerPrintableString(
+ string str,
+ bool validate)
+ {
+ if (str == null)
+ throw new ArgumentNullException("str");
+ if (validate && !IsPrintableString(str))
+ throw new ArgumentException("string contains illegal characters", "str");
+
+ this.str = str;
+ }
+
+ public override string GetString()
+ {
+ return str;
+ }
+
+ public byte[] GetOctets()
+ {
+ return Strings.ToAsciiByteArray(str);
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.PrintableString, GetOctets());
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerPrintableString other = asn1Object as DerPrintableString;
+
+ if (other == null)
+ return false;
+
+ return this.str.Equals(other.str);
+ }
+
+ /**
+ * return true if the passed in String can be represented without
+ * loss as a PrintableString, false otherwise.
+ *
+ * @return true if in printable set, false otherwise.
+ */
+ public static bool IsPrintableString(
+ string str)
+ {
+ foreach (char ch in str)
+ {
+ if (ch > 0x007f)
+ return false;
+
+ if (char.IsLetterOrDigit(ch))
+ continue;
+
+// if (char.IsPunctuation(ch))
+// continue;
+
+ switch (ch)
+ {
+ case ' ':
+ case '\'':
+ case '(':
+ case ')':
+ case '+':
+ case '-':
+ case '.':
+ case ':':
+ case '=':
+ case '?':
+ case '/':
+ case ',':
+ continue;
+ }
+
+ return false;
+ }
+
+ return true;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerSequence.cs b/Crypto/src/asn1/DerSequence.cs
new file mode 100644
index 000000000..dd67d2fed
--- /dev/null
+++ b/Crypto/src/asn1/DerSequence.cs
@@ -0,0 +1,85 @@
+using System.Collections;
+using System.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class DerSequence
+ : Asn1Sequence
+ {
+ public static readonly DerSequence Empty = new DerSequence();
+
+ public static DerSequence FromVector(
+ Asn1EncodableVector v)
+ {
+ return v.Count < 1 ? Empty : new DerSequence(v);
+ }
+
+ /**
+ * create an empty sequence
+ */
+ public DerSequence()
+ : base(0)
+ {
+ }
+
+ /**
+ * create a sequence containing one object
+ */
+ public DerSequence(
+ Asn1Encodable obj)
+ : base(1)
+ {
+ AddObject(obj);
+ }
+
+ public DerSequence(
+ params Asn1Encodable[] v)
+ : base(v.Length)
+ {
+ foreach (Asn1Encodable ae in v)
+ {
+ AddObject(ae);
+ }
+ }
+
+ /**
+ * create a sequence containing a vector of objects.
+ */
+ public DerSequence(
+ Asn1EncodableVector v)
+ : base(v.Count)
+ {
+ foreach (Asn1Encodable ae in v)
+ {
+ AddObject(ae);
+ }
+ }
+
+ /*
+ * A note on the implementation:
+ *
+ * As Der requires the constructed, definite-length model to
+ * be used for structured types, this varies slightly from the
+ * ASN.1 descriptions given. Rather than just outputing Sequence,
+ * we also have to specify Constructed, and the objects length.
+ */
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ // TODO Intermediate buffer could be avoided if we could calculate expected length
+ MemoryStream bOut = new MemoryStream();
+ DerOutputStream dOut = new DerOutputStream(bOut);
+
+ foreach (Asn1Encodable obj in this)
+ {
+ dOut.WriteObject(obj);
+ }
+
+ dOut.Dispose();
+
+ byte[] bytes = bOut.ToArray();
+
+ derOut.WriteEncoded(Asn1Tags.Sequence | Asn1Tags.Constructed, bytes);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerSet.cs b/Crypto/src/asn1/DerSet.cs
new file mode 100644
index 000000000..6d3f438bd
--- /dev/null
+++ b/Crypto/src/asn1/DerSet.cs
@@ -0,0 +1,108 @@
+using System.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * A Der encoded set object
+ */
+ public class DerSet
+ : Asn1Set
+ {
+ public static readonly DerSet Empty = new DerSet();
+
+ public static DerSet FromVector(
+ Asn1EncodableVector v)
+ {
+ return v.Count < 1 ? Empty : new DerSet(v);
+ }
+
+ internal static DerSet FromVector(
+ Asn1EncodableVector v,
+ bool needsSorting)
+ {
+ return v.Count < 1 ? Empty : new DerSet(v, needsSorting);
+ }
+
+ /**
+ * create an empty set
+ */
+ public DerSet()
+ : base(0)
+ {
+ }
+
+ /**
+ * @param obj - a single object that makes up the set.
+ */
+ public DerSet(
+ Asn1Encodable obj)
+ : base(1)
+ {
+ AddObject(obj);
+ }
+
+ public DerSet(
+ params Asn1Encodable[] v)
+ : base(v.Length)
+ {
+ foreach (Asn1Encodable o in v)
+ {
+ AddObject(o);
+ }
+
+ Sort();
+ }
+
+ /**
+ * @param v - a vector of objects making up the set.
+ */
+ public DerSet(
+ Asn1EncodableVector v)
+ : this(v, true)
+ {
+ }
+
+ internal DerSet(
+ Asn1EncodableVector v,
+ bool needsSorting)
+ : base(v.Count)
+ {
+ foreach (Asn1Encodable o in v)
+ {
+ AddObject(o);
+ }
+
+ if (needsSorting)
+ {
+ Sort();
+ }
+ }
+
+ /*
+ * A note on the implementation:
+ *
+ * As Der requires the constructed, definite-length model to
+ * be used for structured types, this varies slightly from the
+ * ASN.1 descriptions given. Rather than just outputing Set,
+ * we also have to specify Constructed, and the objects length.
+ */
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ // TODO Intermediate buffer could be avoided if we could calculate expected length
+ MemoryStream bOut = new MemoryStream();
+ DerOutputStream dOut = new DerOutputStream(bOut);
+
+ foreach (Asn1Encodable obj in this)
+ {
+ dOut.WriteObject(obj);
+ }
+
+ dOut.Dispose();
+
+ byte[] bytes = bOut.ToArray();
+
+ derOut.WriteEncoded(Asn1Tags.Set | Asn1Tags.Constructed, bytes);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerStringBase.cs b/Crypto/src/asn1/DerStringBase.cs
new file mode 100644
index 000000000..2a5fb041e
--- /dev/null
+++ b/Crypto/src/asn1/DerStringBase.cs
@@ -0,0 +1,22 @@
+namespace Org.BouncyCastle.Asn1
+{
+ public abstract class DerStringBase
+ : Asn1Object, IAsn1String
+ {
+ protected DerStringBase()
+ {
+ }
+
+ public abstract string GetString();
+
+ public override string ToString()
+ {
+ return GetString();
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return GetString().GetHashCode();
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerT61String.cs b/Crypto/src/asn1/DerT61String.cs
new file mode 100644
index 000000000..4dee6f30c
--- /dev/null
+++ b/Crypto/src/asn1/DerT61String.cs
@@ -0,0 +1,102 @@
+using System;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * Der T61String (also the teletex string) - 8-bit characters
+ */
+ public class DerT61String
+ : DerStringBase
+ {
+ private readonly string str;
+
+ /**
+ * return a T61 string from the passed in object.
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerT61String GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerT61String)
+ {
+ return (DerT61String)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name);
+ }
+
+ /**
+ * return an T61 string from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerT61String GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerT61String)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerT61String(Asn1OctetString.GetInstance(o).GetOctets());
+ }
+
+ /**
+ * basic constructor - with bytes.
+ */
+ public DerT61String(
+ byte[] str)
+ : this(Strings.FromByteArray(str))
+ {
+ }
+
+ /**
+ * basic constructor - with string.
+ */
+ public DerT61String(
+ string str)
+ {
+ if (str == null)
+ throw new ArgumentNullException("str");
+
+ this.str = str;
+ }
+
+ public override string GetString()
+ {
+ return str;
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.T61String, GetOctets());
+ }
+
+ public byte[] GetOctets()
+ {
+ return Strings.ToByteArray(str);
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerT61String other = asn1Object as DerT61String;
+
+ if (other == null)
+ return false;
+
+ return this.str.Equals(other.str);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerTaggedObject.cs b/Crypto/src/asn1/DerTaggedObject.cs
new file mode 100644
index 000000000..717d724b6
--- /dev/null
+++ b/Crypto/src/asn1/DerTaggedObject.cs
@@ -0,0 +1,72 @@
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * DER TaggedObject - in ASN.1 notation this is any object preceded by
+ * a [n] where n is some number - these are assumed to follow the construction
+ * rules (as with sequences).
+ */
+ public class DerTaggedObject
+ : Asn1TaggedObject
+ {
+ /**
+ * @param tagNo the tag number for this object.
+ * @param obj the tagged object.
+ */
+ public DerTaggedObject(
+ int tagNo,
+ Asn1Encodable obj)
+ : base(tagNo, obj)
+ {
+ }
+
+ /**
+ * @param explicitly true if an explicitly tagged object.
+ * @param tagNo the tag number for this object.
+ * @param obj the tagged object.
+ */
+ public DerTaggedObject(
+ bool explicitly,
+ int tagNo,
+ Asn1Encodable obj)
+ : base(explicitly, tagNo, obj)
+ {
+ }
+
+ /**
+ * create an implicitly tagged object that contains a zero
+ * length sequence.
+ */
+ public DerTaggedObject(
+ int tagNo)
+ : base(false, tagNo, DerSequence.Empty)
+ {
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ if (!IsEmpty())
+ {
+ byte[] bytes = obj.GetDerEncoded();
+
+ if (explicitly)
+ {
+ derOut.WriteEncoded(Asn1Tags.Constructed | Asn1Tags.Tagged, tagNo, bytes);
+ }
+ else
+ {
+ //
+ // need to mark constructed types... (preserve Constructed tag)
+ //
+ int flags = (bytes[0] & Asn1Tags.Constructed) | Asn1Tags.Tagged;
+ derOut.WriteTag(flags, tagNo);
+ derOut.Write(bytes, 1, bytes.Length - 1);
+ }
+ }
+ else
+ {
+ derOut.WriteEncoded(Asn1Tags.Constructed | Asn1Tags.Tagged, tagNo, new byte[0]);
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerUTCTime.cs b/Crypto/src/asn1/DerUTCTime.cs
new file mode 100644
index 000000000..56fabeb47
--- /dev/null
+++ b/Crypto/src/asn1/DerUTCTime.cs
@@ -0,0 +1,263 @@
+using System;
+using System.Globalization;
+using System.Text;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * UTC time object.
+ */
+ public class DerUtcTime
+ : Asn1Object
+ {
+ private readonly string time;
+
+ /**
+ * return an UTC Time from the passed in object.
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerUtcTime GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerUtcTime)
+ {
+ return (DerUtcTime)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name);
+ }
+
+ /**
+ * return an UTC Time from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerUtcTime GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerUtcTime)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerUtcTime(((Asn1OctetString)o).GetOctets());
+ }
+
+ /**
+ * The correct format for this is YYMMDDHHMMSSZ (it used to be that seconds were
+ * never encoded. When you're creating one of these objects from scratch, that's
+ * what you want to use, otherwise we'll try to deal with whatever Gets read from
+ * the input stream... (this is why the input format is different from the GetTime()
+ * method output).
+ *
+ * @param time the time string.
+ */
+ public DerUtcTime(
+ string time)
+ {
+ if (time == null)
+ throw new ArgumentNullException("time");
+
+ this.time = time;
+
+ try
+ {
+ ToDateTime();
+ }
+ catch (FormatException e)
+ {
+ throw new ArgumentException("invalid date string: " + e.Message);
+ }
+ }
+
+ /**
+ * base constructor from a DateTime object
+ */
+ public DerUtcTime(
+ DateTime time)
+ {
+ this.time = time.ToString("yyMMddHHmmss") + "Z";
+ }
+
+ internal DerUtcTime(
+ byte[] bytes)
+ {
+ //
+ // explicitly convert to characters
+ //
+ this.time = Strings.FromAsciiByteArray(bytes);
+ }
+
+// public DateTime ToDateTime()
+// {
+// string tm = this.AdjustedTimeString;
+//
+// return new DateTime(
+// Int16.Parse(tm.Substring(0, 4)),
+// Int16.Parse(tm.Substring(4, 2)),
+// Int16.Parse(tm.Substring(6, 2)),
+// Int16.Parse(tm.Substring(8, 2)),
+// Int16.Parse(tm.Substring(10, 2)),
+// Int16.Parse(tm.Substring(12, 2)));
+// }
+
+ /**
+ * return the time as a date based on whatever a 2 digit year will return. For
+ * standardised processing use ToAdjustedDateTime().
+ *
+ * @return the resulting date
+ * @exception ParseException if the date string cannot be parsed.
+ */
+ public DateTime ToDateTime()
+ {
+ return ParseDateString(TimeString, @"yyMMddHHmmss'GMT'zzz");
+ }
+
+ /**
+ * return the time as an adjusted date
+ * in the range of 1950 - 2049.
+ *
+ * @return a date in the range of 1950 to 2049.
+ * @exception ParseException if the date string cannot be parsed.
+ */
+ public DateTime ToAdjustedDateTime()
+ {
+ return ParseDateString(AdjustedTimeString, @"yyyyMMddHHmmss'GMT'zzz");
+ }
+
+ private DateTime ParseDateString(
+ string dateStr,
+ string formatStr)
+ {
+ DateTime dt = DateTime.ParseExact(
+ dateStr,
+ formatStr,
+ DateTimeFormatInfo.InvariantInfo);
+
+ return dt.ToUniversalTime();
+ }
+
+ /**
+ * return the time - always in the form of
+ * YYMMDDhhmmssGMT(+hh:mm|-hh:mm).
+ *
+ * Normally in a certificate we would expect "Z" rather than "GMT",
+ * however adding the "GMT" means we can just use:
+ *
+ * dateF = new SimpleDateFormat("yyMMddHHmmssz");
+ *
+ * To read in the time and Get a date which is compatible with our local
+ * time zone.
+ *
+ * Note: In some cases, due to the local date processing, this
+ * may lead to unexpected results. If you want to stick the normal
+ * convention of 1950 to 2049 use the GetAdjustedTime() method.
+ */
+ public string TimeString
+ {
+ get
+ {
+ //
+ // standardise the format.
+ //
+ if (time.IndexOf('-') < 0 && time.IndexOf('+') < 0)
+ {
+ if (time.Length == 11)
+ {
+ return time.Substring(0, 10) + "00GMT+00:00";
+ }
+ else
+ {
+ return time.Substring(0, 12) + "GMT+00:00";
+ }
+ }
+ else
+ {
+ int index = time.IndexOf('-');
+ if (index < 0)
+ {
+ index = time.IndexOf('+');
+ }
+ string d = time;
+
+ if (index == time.Length - 3)
+ {
+ d += "00";
+ }
+
+ if (index == 10)
+ {
+ return d.Substring(0, 10) + "00GMT" + d.Substring(10, 3) + ":" + d.Substring(13, 2);
+ }
+ else
+ {
+ return d.Substring(0, 12) + "GMT" + d.Substring(12, 3) + ":" + d.Substring(15, 2);
+ }
+ }
+ }
+ }
+
+ [Obsolete("Use 'AdjustedTimeString' property instead")]
+ public string AdjustedTime
+ {
+ get { return AdjustedTimeString; }
+ }
+
+ ///
+ /// Return a time string as an adjusted date with a 4 digit year.
+ /// This goes in the range of 1950 - 2049.
+ ///
+ public string AdjustedTimeString
+ {
+ get
+ {
+ string d = TimeString;
+ string c = d[0] < '5' ? "20" : "19";
+
+ return c + d;
+ }
+ }
+
+ private byte[] GetOctets()
+ {
+ return Strings.ToAsciiByteArray(time);
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.UtcTime, GetOctets());
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerUtcTime other = asn1Object as DerUtcTime;
+
+ if (other == null)
+ return false;
+
+ return this.time.Equals(other.time);
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return time.GetHashCode();
+ }
+
+ public override string ToString()
+ {
+ return time;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerUTF8String.cs b/Crypto/src/asn1/DerUTF8String.cs
new file mode 100644
index 000000000..92a50e824
--- /dev/null
+++ b/Crypto/src/asn1/DerUTF8String.cs
@@ -0,0 +1,96 @@
+using System;
+using System.Text;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * Der UTF8String object.
+ */
+ public class DerUtf8String
+ : DerStringBase
+ {
+ private readonly string str;
+
+ /**
+ * return an UTF8 string from the passed in object.
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerUtf8String GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerUtf8String)
+ {
+ return (DerUtf8String)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name);
+ }
+
+ /**
+ * return an UTF8 string from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerUtf8String GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerUtf8String)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerUtf8String(Asn1OctetString.GetInstance(o).GetOctets());
+ }
+
+ /**
+ * basic constructor - byte encoded string.
+ */
+ public DerUtf8String(
+ byte[] str)
+ : this(Encoding.UTF8.GetString(str, 0, str.Length))
+ {
+ }
+
+ /**
+ * basic constructor
+ */
+ public DerUtf8String(
+ string str)
+ {
+ if (str == null)
+ throw new ArgumentNullException("str");
+
+ this.str = str;
+ }
+
+ public override string GetString()
+ {
+ return str;
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerUtf8String other = asn1Object as DerUtf8String;
+
+ if (other == null)
+ return false;
+
+ return this.str.Equals(other.str);
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.Utf8String, Encoding.UTF8.GetBytes(str));
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerUniversalString.cs b/Crypto/src/asn1/DerUniversalString.cs
new file mode 100644
index 000000000..305102f2f
--- /dev/null
+++ b/Crypto/src/asn1/DerUniversalString.cs
@@ -0,0 +1,107 @@
+using System;
+using System.Text;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * Der UniversalString object.
+ */
+ public class DerUniversalString
+ : DerStringBase
+ {
+ private static readonly char[] table = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+
+ private readonly byte[] str;
+
+ /**
+ * return a Universal string from the passed in object.
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerUniversalString GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerUniversalString)
+ {
+ return (DerUniversalString)obj;
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name);
+ }
+
+ /**
+ * return a Universal string from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerUniversalString GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ Asn1Object o = obj.GetObject();
+
+ if (isExplicit || o is DerUniversalString)
+ {
+ return GetInstance(o);
+ }
+
+ return new DerUniversalString(Asn1OctetString.GetInstance(o).GetOctets());
+ }
+
+ /**
+ * basic constructor - byte encoded string.
+ */
+ public DerUniversalString(
+ byte[] str)
+ {
+ if (str == null)
+ throw new ArgumentNullException("str");
+
+ this.str = str;
+ }
+
+ public override string GetString()
+ {
+ StringBuilder buffer = new StringBuilder("#");
+ byte[] enc = GetDerEncoded();
+
+ for (int i = 0; i != enc.Length; i++)
+ {
+ uint ubyte = enc[i];
+ buffer.Append(table[(ubyte >> 4) & 0xf]);
+ buffer.Append(table[enc[i] & 0xf]);
+ }
+
+ return buffer.ToString();
+ }
+
+ public byte[] GetOctets()
+ {
+ return (byte[]) str.Clone();
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.UniversalString, this.str);
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerUniversalString other = asn1Object as DerUniversalString;
+
+ if (other == null)
+ return false;
+
+// return this.GetString().Equals(other.GetString());
+ return Arrays.AreEqual(this.str, other.str);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerUnknownTag.cs b/Crypto/src/asn1/DerUnknownTag.cs
new file mode 100644
index 000000000..1e0e61495
--- /dev/null
+++ b/Crypto/src/asn1/DerUnknownTag.cs
@@ -0,0 +1,80 @@
+using System;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * We insert one of these when we find a tag we don't recognise.
+ */
+ public class DerUnknownTag
+ : Asn1Object
+ {
+ private readonly bool isConstructed;
+ private readonly int tag;
+ private readonly byte[] data;
+
+ /**
+ * @param tag the tag value.
+ * @param data the contents octets.
+ */
+ public DerUnknownTag(
+ int tag,
+ byte[] data)
+ : this(false, tag, data)
+ {
+ }
+
+ public DerUnknownTag(
+ bool isConstructed,
+ int tag,
+ byte[] data)
+ {
+ if (data == null)
+ throw new ArgumentNullException("data");
+
+ this.isConstructed = isConstructed;
+ this.tag = tag;
+ this.data = data;
+ }
+
+ public bool IsConstructed
+ {
+ get { return isConstructed; }
+ }
+
+ public int Tag
+ {
+ get { return tag; }
+ }
+
+ public byte[] GetData()
+ {
+ return data;
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(isConstructed ? Asn1Tags.Constructed : 0, tag, data);
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerUnknownTag other = asn1Object as DerUnknownTag;
+
+ if (other == null)
+ return false;
+
+ return this.isConstructed == other.isConstructed
+ && this.tag == other.tag
+ && Arrays.AreEqual(this.data, other.data);
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return isConstructed.GetHashCode() ^ tag.GetHashCode() ^ Arrays.GetHashCode(data);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/DerVisibleString.cs b/Crypto/src/asn1/DerVisibleString.cs
new file mode 100644
index 000000000..84c9caade
--- /dev/null
+++ b/Crypto/src/asn1/DerVisibleString.cs
@@ -0,0 +1,111 @@
+using System;
+using System.Text;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * Der VisibleString object.
+ */
+ public class DerVisibleString
+ : DerStringBase
+ {
+ private readonly string str;
+
+ /**
+ * return a Visible string from the passed in object.
+ *
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static DerVisibleString GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is DerVisibleString)
+ {
+ return (DerVisibleString)obj;
+ }
+
+ if (obj is Asn1OctetString)
+ {
+ return new DerVisibleString(((Asn1OctetString)obj).GetOctets());
+ }
+
+ if (obj is Asn1TaggedObject)
+ {
+ return GetInstance(((Asn1TaggedObject)obj).GetObject());
+ }
+
+ throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name);
+ }
+
+ /**
+ * return a Visible string from a tagged object.
+ *
+ * @param obj the tagged object holding the object we want
+ * @param explicitly true if the object is meant to be explicitly
+ * tagged false otherwise.
+ * @exception ArgumentException if the tagged object cannot
+ * be converted.
+ */
+ public static DerVisibleString GetInstance(
+ Asn1TaggedObject obj,
+ bool explicitly)
+ {
+ return GetInstance(obj.GetObject());
+ }
+
+ /**
+ * basic constructor - byte encoded string.
+ */
+ public DerVisibleString(
+ byte[] str)
+ : this(Strings.FromAsciiByteArray(str))
+ {
+ }
+
+ /**
+ * basic constructor
+ */
+ public DerVisibleString(
+ string str)
+ {
+ if (str == null)
+ throw new ArgumentNullException("str");
+
+ this.str = str;
+ }
+
+ public override string GetString()
+ {
+ return str;
+ }
+
+ public byte[] GetOctets()
+ {
+ return Strings.ToAsciiByteArray(str);
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ derOut.WriteEncoded(Asn1Tags.VisibleString, GetOctets());
+ }
+
+ protected override bool Asn1Equals(
+ Asn1Object asn1Object)
+ {
+ DerVisibleString other = asn1Object as DerVisibleString;
+
+ if (other == null)
+ return false;
+
+ return this.str.Equals(other.str);
+ }
+
+ protected override int Asn1GetHashCode()
+ {
+ return this.str.GetHashCode();
+ }
+ }
+}
diff --git a/Crypto/src/asn1/IAsn1ApplicationSpecificParser.cs b/Crypto/src/asn1/IAsn1ApplicationSpecificParser.cs
new file mode 100644
index 000000000..89cf64c70
--- /dev/null
+++ b/Crypto/src/asn1/IAsn1ApplicationSpecificParser.cs
@@ -0,0 +1,10 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public interface IAsn1ApplicationSpecificParser
+ : IAsn1Convertible
+ {
+ IAsn1Convertible ReadObject();
+ }
+}
diff --git a/Crypto/src/asn1/IAsn1Choice.cs b/Crypto/src/asn1/IAsn1Choice.cs
new file mode 100644
index 000000000..ecd76e427
--- /dev/null
+++ b/Crypto/src/asn1/IAsn1Choice.cs
@@ -0,0 +1,17 @@
+
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * Marker interface for CHOICE objects - if you implement this in a roll-your-own
+ * object, any attempt to tag the object implicitly will convert the tag to an
+ * explicit one as the encoding rules require.
+ *
+ * If you use this interface your class should also implement the getInstance
+ * pattern which takes a tag object and the tagging mode used.
+ *
+ */
+ public interface IAsn1Choice
+ {
+ // marker interface
+ }
+}
diff --git a/Crypto/src/asn1/IAsn1Convertible.cs b/Crypto/src/asn1/IAsn1Convertible.cs
new file mode 100644
index 000000000..d3f83afc9
--- /dev/null
+++ b/Crypto/src/asn1/IAsn1Convertible.cs
@@ -0,0 +1,7 @@
+namespace Org.BouncyCastle.Asn1
+{
+ public interface IAsn1Convertible
+ {
+ Asn1Object ToAsn1Object();
+ }
+}
diff --git a/Crypto/src/asn1/IAsn1String.cs b/Crypto/src/asn1/IAsn1String.cs
new file mode 100644
index 000000000..cbc2635ff
--- /dev/null
+++ b/Crypto/src/asn1/IAsn1String.cs
@@ -0,0 +1,10 @@
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * basic interface for Der string objects.
+ */
+ public interface IAsn1String
+ {
+ string GetString();
+ }
+}
diff --git a/Crypto/src/asn1/IndefiniteLengthInputStream.cs b/Crypto/src/asn1/IndefiniteLengthInputStream.cs
new file mode 100644
index 000000000..56c1bdfbc
--- /dev/null
+++ b/Crypto/src/asn1/IndefiniteLengthInputStream.cs
@@ -0,0 +1,166 @@
+using System;
+using System.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ class IndefiniteLengthInputStream
+ : LimitedInputStream
+ {
+ private int _lookAhead;
+ private bool _eofOn00 = true;
+
+ internal IndefiniteLengthInputStream(
+ Stream inStream,
+ int limit)
+ : base(inStream, limit)
+ {
+ _lookAhead = RequireByte();
+ CheckForEof();
+ }
+
+ internal void SetEofOn00(
+ bool eofOn00)
+ {
+ _eofOn00 = eofOn00;
+ CheckForEof();
+ }
+
+ private bool CheckForEof()
+ {
+ if (_lookAhead == 0x00 && _eofOn00)
+ {
+ int extra = RequireByte();
+ if (extra != 0)
+ {
+ throw new IOException("malformed end-of-contents marker");
+ }
+
+ _lookAhead = -1;
+ SetParentEofDetect(true);
+ }
+ return _lookAhead < 0;
+ }
+
+ public override int Read(
+ byte[] buffer,
+ int offset,
+ int count)
+ {
+ // Only use this optimisation if we aren't checking for 00
+ if (_eofOn00 || count <= 1)
+ return base.Read(buffer, offset, count);
+
+ if (_lookAhead < 0)
+ return 0;
+
+ int numRead = _in.Read(buffer, offset + 1, count - 1);
+
+ if (numRead <= 0)
+ {
+ // Corrupted stream
+ throw new EndOfStreamException();
+ }
+
+ buffer[offset] = (byte)_lookAhead;
+ _lookAhead = RequireByte();
+
+ return numRead + 1;
+ }
+
+ public override int ReadByte()
+ {
+ if (CheckForEof())
+ return -1;
+
+ int result = _lookAhead;
+ _lookAhead = RequireByte();
+ return result;
+ }
+
+ private int RequireByte()
+ {
+ int b = _in.ReadByte();
+ if (b < 0)
+ {
+ // Corrupted stream
+ throw new EndOfStreamException();
+ }
+ return b;
+ }
+ }
+}
+
+//using System;
+//using System.IO;
+
+//namespace Org.BouncyCastle.Asn1
+//{
+// class IndefiniteLengthInputStream
+// : LimitedInputStream
+// {
+// private bool _eofReached = false;
+// private bool _eofOn00 = true;
+
+// internal IndefiniteLengthInputStream(
+// Stream inStream,
+// int limit)
+// : base(inStream, limit)
+// {
+// }
+
+// internal void SetEofOn00(
+// bool eofOn00)
+// {
+// _eofOn00 = eofOn00;
+// }
+
+// public override int Read(
+// byte[] buffer,
+// int offset,
+// int count)
+// {
+// if (_eofReached)
+// return 0;
+
+// if (_eofOn00)
+// return base.Read(buffer, offset, count);
+
+// int numRead = _in.Read(buffer, offset, count);
+
+// if (numRead <= 0)
+// throw new EndOfStreamException();
+
+// return numRead;
+// }
+
+// public override int ReadByte()
+// {
+// if (_eofReached)
+// return -1;
+
+// int b1 = _in.ReadByte();
+
+// if (b1 < 0)
+// throw new EndOfStreamException();
+
+// if (b1 == 0 && _eofOn00)
+// {
+// int b2 = _in.ReadByte();
+
+// if (b2 < 0)
+// throw new EndOfStreamException();
+
+// if (b2 == 0)
+// {
+// _eofReached = true;
+// SetParentEofDetect(true);
+// return -1;
+// }
+
+// throw new InvalidDataException();
+// }
+
+// return b1;
+// }
+// }
+//}
diff --git a/Crypto/src/asn1/LazyASN1InputStream.cs b/Crypto/src/asn1/LazyASN1InputStream.cs
new file mode 100644
index 000000000..4cf2305fd
--- /dev/null
+++ b/Crypto/src/asn1/LazyASN1InputStream.cs
@@ -0,0 +1,33 @@
+using System;
+using System.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ public class LazyAsn1InputStream
+ : Asn1InputStream
+ {
+ public LazyAsn1InputStream(
+ byte[] input)
+ : base(input)
+ {
+ }
+
+ public LazyAsn1InputStream(
+ Stream inputStream)
+ : base(inputStream)
+ {
+ }
+
+ internal override DerSequence CreateDerSequence(
+ DefiniteLengthInputStream dIn)
+ {
+ return new LazyDerSequence(dIn.ToArray());
+ }
+
+ internal override DerSet CreateDerSet(
+ DefiniteLengthInputStream dIn)
+ {
+ return new LazyDerSet(dIn.ToArray());
+ }
+ }
+}
diff --git a/Crypto/src/asn1/LazyDERSequence.cs b/Crypto/src/asn1/LazyDERSequence.cs
new file mode 100644
index 000000000..5e3dd076e
--- /dev/null
+++ b/Crypto/src/asn1/LazyDERSequence.cs
@@ -0,0 +1,82 @@
+using System;
+using System.Collections;
+using System.Diagnostics;
+
+namespace Org.BouncyCastle.Asn1
+{
+ internal class LazyDerSequence
+ : DerSequence
+ {
+ private byte[] encoded;
+ private bool parsed = false;
+
+ internal LazyDerSequence(
+ byte[] encoded)
+ {
+ this.encoded = encoded;
+ }
+
+ private void Parse()
+ {
+ lock (this)
+ {
+ if (!parsed)
+ {
+ Asn1InputStream e = new LazyAsn1InputStream(encoded);
+
+ Asn1Object o;
+ while ((o = e.ReadObject()) != null)
+ {
+ AddObject(o);
+ }
+
+ encoded = null;
+ parsed = true;
+ }
+ }
+ }
+
+ public override Asn1Encodable this[int index]
+ {
+ get
+ {
+ Parse();
+
+ return base[index];
+ }
+ }
+
+ public override IEnumerator GetEnumerator()
+ {
+ Parse();
+
+ return base.GetEnumerator();
+ }
+
+ public override int Count
+ {
+ get
+ {
+ Parse();
+
+ return base.Count;
+ }
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ lock (this)
+ {
+ if (parsed)
+ {
+ base.Encode(derOut);
+ }
+ else
+ {
+ derOut.WriteEncoded(Asn1Tags.Sequence | Asn1Tags.Constructed, encoded);
+ }
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/LazyDERSet.cs b/Crypto/src/asn1/LazyDERSet.cs
new file mode 100644
index 000000000..84fce4808
--- /dev/null
+++ b/Crypto/src/asn1/LazyDERSet.cs
@@ -0,0 +1,82 @@
+using System;
+using System.Collections;
+using System.Diagnostics;
+
+namespace Org.BouncyCastle.Asn1
+{
+ internal class LazyDerSet
+ : DerSet
+ {
+ private byte[] encoded;
+ private bool parsed = false;
+
+ internal LazyDerSet(
+ byte[] encoded)
+ {
+ this.encoded = encoded;
+ }
+
+ private void Parse()
+ {
+ lock (this)
+ {
+ if (!parsed)
+ {
+ Asn1InputStream e = new LazyAsn1InputStream(encoded);
+
+ Asn1Object o;
+ while ((o = e.ReadObject()) != null)
+ {
+ AddObject(o);
+ }
+
+ encoded = null;
+ parsed = true;
+ }
+ }
+ }
+
+ public override Asn1Encodable this[int index]
+ {
+ get
+ {
+ Parse();
+
+ return base[index];
+ }
+ }
+
+ public override IEnumerator GetEnumerator()
+ {
+ Parse();
+
+ return base.GetEnumerator();
+ }
+
+ public override int Count
+ {
+ get
+ {
+ Parse();
+
+ return base.Count;
+ }
+ }
+
+ internal override void Encode(
+ DerOutputStream derOut)
+ {
+ lock (this)
+ {
+ if (parsed)
+ {
+ base.Encode(derOut);
+ }
+ else
+ {
+ derOut.WriteEncoded(Asn1Tags.Set | Asn1Tags.Constructed, encoded);
+ }
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/LimitedInputStream.cs b/Crypto/src/asn1/LimitedInputStream.cs
new file mode 100644
index 000000000..62486aa77
--- /dev/null
+++ b/Crypto/src/asn1/LimitedInputStream.cs
@@ -0,0 +1,35 @@
+using System.IO;
+
+using Org.BouncyCastle.Utilities.IO;
+
+namespace Org.BouncyCastle.Asn1
+{
+ internal abstract class LimitedInputStream
+ : BaseInputStream
+ {
+ protected readonly Stream _in;
+ private int _limit;
+
+ internal LimitedInputStream(
+ Stream inStream,
+ int limit)
+ {
+ this._in = inStream;
+ this._limit = limit;
+ }
+
+ internal virtual int GetRemaining()
+ {
+ // TODO: maybe one day this can become more accurate
+ return _limit;
+ }
+
+ protected virtual void SetParentEofDetect(bool on)
+ {
+ if (_in is IndefiniteLengthInputStream)
+ {
+ ((IndefiniteLengthInputStream)_in).SetEofOn00(on);
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/OidTokenizer.cs b/Crypto/src/asn1/OidTokenizer.cs
new file mode 100644
index 000000000..6e76e8c8b
--- /dev/null
+++ b/Crypto/src/asn1/OidTokenizer.cs
@@ -0,0 +1,45 @@
+namespace Org.BouncyCastle.Asn1
+{
+ /**
+ * class for breaking up an Oid into it's component tokens, ala
+ * java.util.StringTokenizer. We need this class as some of the
+ * lightweight Java environment don't support classes like
+ * StringTokenizer.
+ */
+ public class OidTokenizer
+ {
+ private string oid;
+ private int index;
+
+ public OidTokenizer(
+ string oid)
+ {
+ this.oid = oid;
+ }
+
+ public bool HasMoreTokens
+ {
+ get { return index != -1; }
+ }
+
+ public string NextToken()
+ {
+ if (index == -1)
+ {
+ return null;
+ }
+
+ int end = oid.IndexOf('.', index);
+ if (end == -1)
+ {
+ string lastToken = oid.Substring(index);
+ index = -1;
+ return lastToken;
+ }
+
+ string nextToken = oid.Substring(index, end - index);
+ index = end + 1;
+ return nextToken;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/bc/BCObjectIdentifiers.cs b/Crypto/src/asn1/bc/BCObjectIdentifiers.cs
new file mode 100644
index 000000000..075e5384c
--- /dev/null
+++ b/Crypto/src/asn1/bc/BCObjectIdentifiers.cs
@@ -0,0 +1,39 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.BC
+{
+ public abstract class BCObjectIdentifiers
+ {
+ // iso.org.dod.internet.private.enterprise.legion-of-the-bouncy-castle
+ // 1.3.6.1.4.1.22554
+ public static readonly DerObjectIdentifier bc = new DerObjectIdentifier("1.3.6.1.4.1.22554");
+
+ // pbe(1) algorithms
+ public static readonly DerObjectIdentifier bc_pbe = new DerObjectIdentifier(bc + ".1");
+
+ // SHA-1(1)
+ public static readonly DerObjectIdentifier bc_pbe_sha1 = new DerObjectIdentifier(bc_pbe + ".1");
+
+ // SHA-2(2) . (SHA-256(1)|SHA-384(2)|SHA-512(3)|SHA-224(4))
+ public static readonly DerObjectIdentifier bc_pbe_sha256 = new DerObjectIdentifier(bc_pbe + ".2.1");
+ public static readonly DerObjectIdentifier bc_pbe_sha384 = new DerObjectIdentifier(bc_pbe + ".2.2");
+ public static readonly DerObjectIdentifier bc_pbe_sha512 = new DerObjectIdentifier(bc_pbe + ".2.3");
+ public static readonly DerObjectIdentifier bc_pbe_sha224 = new DerObjectIdentifier(bc_pbe + ".2.4");
+
+ // PKCS-5(1)|PKCS-12(2)
+ public static readonly DerObjectIdentifier bc_pbe_sha1_pkcs5 = new DerObjectIdentifier(bc_pbe_sha1 + ".1");
+ public static readonly DerObjectIdentifier bc_pbe_sha1_pkcs12 = new DerObjectIdentifier(bc_pbe_sha1 + ".2");
+
+ public static readonly DerObjectIdentifier bc_pbe_sha256_pkcs5 = new DerObjectIdentifier(bc_pbe_sha256 + ".1");
+ public static readonly DerObjectIdentifier bc_pbe_sha256_pkcs12 = new DerObjectIdentifier(bc_pbe_sha256 + ".2");
+
+ // AES(1) . (CBC-128(2)|CBC-192(22)|CBC-256(42))
+ public static readonly DerObjectIdentifier bc_pbe_sha1_pkcs12_aes128_cbc = new DerObjectIdentifier(bc_pbe_sha1_pkcs12 + ".1.2");
+ public static readonly DerObjectIdentifier bc_pbe_sha1_pkcs12_aes192_cbc = new DerObjectIdentifier(bc_pbe_sha1_pkcs12 + ".1.22");
+ public static readonly DerObjectIdentifier bc_pbe_sha1_pkcs12_aes256_cbc = new DerObjectIdentifier(bc_pbe_sha1_pkcs12 + ".1.42");
+
+ public static readonly DerObjectIdentifier bc_pbe_sha256_pkcs12_aes128_cbc = new DerObjectIdentifier(bc_pbe_sha256_pkcs12 + ".1.2");
+ public static readonly DerObjectIdentifier bc_pbe_sha256_pkcs12_aes192_cbc = new DerObjectIdentifier(bc_pbe_sha256_pkcs12 + ".1.22");
+ public static readonly DerObjectIdentifier bc_pbe_sha256_pkcs12_aes256_cbc = new DerObjectIdentifier(bc_pbe_sha256_pkcs12 + ".1.42");
+ }
+}
\ No newline at end of file
diff --git a/Crypto/src/asn1/cmp/CAKeyUpdAnnContent.cs b/Crypto/src/asn1/cmp/CAKeyUpdAnnContent.cs
new file mode 100644
index 000000000..3cdb128a6
--- /dev/null
+++ b/Crypto/src/asn1/cmp/CAKeyUpdAnnContent.cs
@@ -0,0 +1,60 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class CAKeyUpdAnnContent
+ : Asn1Encodable
+ {
+ private readonly CmpCertificate oldWithNew;
+ private readonly CmpCertificate newWithOld;
+ private readonly CmpCertificate newWithNew;
+
+ private CAKeyUpdAnnContent(Asn1Sequence seq)
+ {
+ oldWithNew = CmpCertificate.GetInstance(seq[0]);
+ newWithOld = CmpCertificate.GetInstance(seq[1]);
+ newWithNew = CmpCertificate.GetInstance(seq[2]);
+ }
+
+ public static CAKeyUpdAnnContent GetInstance(object obj)
+ {
+ if (obj is CAKeyUpdAnnContent)
+ return (CAKeyUpdAnnContent)obj;
+
+ if (obj is Asn1Sequence)
+ return new CAKeyUpdAnnContent((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public virtual CmpCertificate OldWithNew
+ {
+ get { return oldWithNew; }
+ }
+
+ public virtual CmpCertificate NewWithOld
+ {
+ get { return newWithOld; }
+ }
+
+ public virtual CmpCertificate NewWithNew
+ {
+ get { return newWithNew; }
+ }
+
+ /**
+ *
+ * CAKeyUpdAnnContent ::= SEQUENCE {
+ * oldWithNew CmpCertificate, -- old pub signed with new priv
+ * newWithOld CmpCertificate, -- new pub signed with old priv
+ * newWithNew CmpCertificate -- new pub signed with new priv
+ * }
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(oldWithNew, newWithOld, newWithNew);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/CertConfirmContent.cs b/Crypto/src/asn1/cmp/CertConfirmContent.cs
new file mode 100644
index 000000000..f4016d8d8
--- /dev/null
+++ b/Crypto/src/asn1/cmp/CertConfirmContent.cs
@@ -0,0 +1,47 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class CertConfirmContent
+ : Asn1Encodable
+ {
+ private readonly Asn1Sequence content;
+
+ private CertConfirmContent(Asn1Sequence seq)
+ {
+ content = seq;
+ }
+
+ public static CertConfirmContent GetInstance(object obj)
+ {
+ if (obj is CertConfirmContent)
+ return (CertConfirmContent)obj;
+
+ if (obj is Asn1Sequence)
+ return new CertConfirmContent((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public virtual CertStatus[] ToCertStatusArray()
+ {
+ CertStatus[] result = new CertStatus[content.Count];
+ for (int i = 0; i != result.Length; i++)
+ {
+ result[i] = CertStatus.GetInstance(content[i]);
+ }
+ return result;
+ }
+
+ /**
+ *
+ * CertConfirmContent ::= SEQUENCE OF CertStatus
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return content;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/CertOrEncCert.cs b/Crypto/src/asn1/cmp/CertOrEncCert.cs
new file mode 100644
index 000000000..4c049c180
--- /dev/null
+++ b/Crypto/src/asn1/cmp/CertOrEncCert.cs
@@ -0,0 +1,85 @@
+using System;
+
+using Org.BouncyCastle.Asn1.Crmf;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class CertOrEncCert
+ : Asn1Encodable, IAsn1Choice
+ {
+ private readonly CmpCertificate certificate;
+ private readonly EncryptedValue encryptedCert;
+
+ private CertOrEncCert(Asn1TaggedObject tagged)
+ {
+ if (tagged.TagNo == 0)
+ {
+ certificate = CmpCertificate.GetInstance(tagged.GetObject());
+ }
+ else if (tagged.TagNo == 1)
+ {
+ encryptedCert = EncryptedValue.GetInstance(tagged.GetObject());
+ }
+ else
+ {
+ throw new ArgumentException("unknown tag: " + tagged.TagNo, "tagged");
+ }
+ }
+
+ public static CertOrEncCert GetInstance(object obj)
+ {
+ if (obj is CertOrEncCert)
+ return (CertOrEncCert)obj;
+
+ if (obj is Asn1TaggedObject)
+ return new CertOrEncCert((Asn1TaggedObject)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public CertOrEncCert(CmpCertificate certificate)
+ {
+ if (certificate == null)
+ throw new ArgumentNullException("certificate");
+
+ this.certificate = certificate;
+ }
+
+ public CertOrEncCert(EncryptedValue encryptedCert)
+ {
+ if (encryptedCert == null)
+ throw new ArgumentNullException("encryptedCert");
+
+ this.encryptedCert = encryptedCert;
+ }
+
+ public virtual CmpCertificate Certificate
+ {
+ get { return certificate; }
+ }
+
+ public virtual EncryptedValue EncryptedCert
+ {
+ get { return encryptedCert; }
+ }
+
+ /**
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+
+ if (caPubs != null)
+ {
+ v.Add(new DerTaggedObject(true, 1, caPubs));
+ }
+
+ v.Add(response);
+
+ return new DerSequence(v);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/CertResponse.cs b/Crypto/src/asn1/cmp/CertResponse.cs
new file mode 100644
index 000000000..246b8ce70
--- /dev/null
+++ b/Crypto/src/asn1/cmp/CertResponse.cs
@@ -0,0 +1,115 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class CertResponse
+ : Asn1Encodable
+ {
+ private readonly DerInteger certReqId;
+ private readonly PkiStatusInfo status;
+ private readonly CertifiedKeyPair certifiedKeyPair;
+ private readonly Asn1OctetString rspInfo;
+
+ private CertResponse(Asn1Sequence seq)
+ {
+ certReqId = DerInteger.GetInstance(seq[0]);
+ status = PkiStatusInfo.GetInstance(seq[1]);
+
+ if (seq.Count >= 3)
+ {
+ if (seq.Count == 3)
+ {
+ Asn1Encodable o = seq[2];
+ if (o is Asn1OctetString)
+ {
+ rspInfo = Asn1OctetString.GetInstance(o);
+ }
+ else
+ {
+ certifiedKeyPair = CertifiedKeyPair.GetInstance(o);
+ }
+ }
+ else
+ {
+ certifiedKeyPair = CertifiedKeyPair.GetInstance(seq[2]);
+ rspInfo = Asn1OctetString.GetInstance(seq[3]);
+ }
+ }
+ }
+
+ public static CertResponse GetInstance(object obj)
+ {
+ if (obj is CertResponse)
+ return (CertResponse)obj;
+
+ if (obj is Asn1Sequence)
+ return new CertResponse((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public CertResponse(
+ DerInteger certReqId,
+ PkiStatusInfo status)
+ : this(certReqId, status, null, null)
+ {
+ }
+
+ public CertResponse(
+ DerInteger certReqId,
+ PkiStatusInfo status,
+ CertifiedKeyPair certifiedKeyPair,
+ Asn1OctetString rspInfo)
+ {
+ if (certReqId == null)
+ throw new ArgumentNullException("certReqId");
+
+ if (status == null)
+ throw new ArgumentNullException("status");
+
+ this.certReqId = certReqId;
+ this.status = status;
+ this.certifiedKeyPair = certifiedKeyPair;
+ this.rspInfo = rspInfo;
+ }
+
+ public virtual DerInteger CertReqID
+ {
+ get { return certReqId; }
+ }
+
+ public virtual PkiStatusInfo Status
+ {
+ get { return status; }
+ }
+
+ public virtual CertifiedKeyPair CertifiedKeyPair
+ {
+ get { return certifiedKeyPair; }
+ }
+
+ /**
+ *
+ * CertResponse ::= SEQUENCE {
+ * certReqId INTEGER,
+ * -- to match this response with corresponding request (a value
+ * -- of -1 is to be used if certReqId is not specified in the
+ * -- corresponding request)
+ * status PKIStatusInfo,
+ * certifiedKeyPair CertifiedKeyPair OPTIONAL,
+ * rspInfo OCTET STRING OPTIONAL
+ * -- analogous to the id-regInfo-utf8Pairs string defined
+ * -- for regInfo in CertReqMsg [CRMF]
+ * }
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(certReqId, status);
+ v.AddOptional(certifiedKeyPair);
+ v.AddOptional(rspInfo);
+ return new DerSequence(v);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/CertStatus.cs b/Crypto/src/asn1/cmp/CertStatus.cs
new file mode 100644
index 000000000..52d5ac504
--- /dev/null
+++ b/Crypto/src/asn1/cmp/CertStatus.cs
@@ -0,0 +1,84 @@
+using System;
+
+using Org.BouncyCastle.Math;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class CertStatus
+ : Asn1Encodable
+ {
+ private readonly Asn1OctetString certHash;
+ private readonly DerInteger certReqId;
+ private readonly PkiStatusInfo statusInfo;
+
+ private CertStatus(Asn1Sequence seq)
+ {
+ certHash = Asn1OctetString.GetInstance(seq[0]);
+ certReqId = DerInteger.GetInstance(seq[1]);
+
+ if (seq.Count > 2)
+ {
+ statusInfo = PkiStatusInfo.GetInstance(seq[2]);
+ }
+ }
+
+ public CertStatus(byte[] certHash, BigInteger certReqId)
+ {
+ this.certHash = new DerOctetString(certHash);
+ this.certReqId = new DerInteger(certReqId);
+ }
+
+ public CertStatus(byte[] certHash, BigInteger certReqId, PkiStatusInfo statusInfo)
+ {
+ this.certHash = new DerOctetString(certHash);
+ this.certReqId = new DerInteger(certReqId);
+ this.statusInfo = statusInfo;
+ }
+
+ public static CertStatus GetInstance(object obj)
+ {
+ if (obj is CertStatus)
+ return (CertStatus)obj;
+
+ if (obj is Asn1Sequence)
+ return new CertStatus((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public virtual Asn1OctetString CertHash
+ {
+ get { return certHash; }
+ }
+
+ public virtual DerInteger CertReqID
+ {
+ get { return certReqId; }
+ }
+
+ public virtual PkiStatusInfo StatusInfo
+ {
+ get { return statusInfo; }
+ }
+
+ /**
+ *
+ * CertStatus ::= SEQUENCE {
+ * certHash OCTET STRING,
+ * -- the hash of the certificate, using the same hash algorithm
+ * -- as is used to create and verify the certificate signature
+ * certReqId INTEGER,
+ * -- to match this confirmation with the corresponding req/rep
+ * statusInfo PKIStatusInfo OPTIONAL
+ * }
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(certOrEncCert);
+
+ if (privateKey != null)
+ {
+ v.Add(new DerTaggedObject(true, 0, privateKey));
+ }
+
+ if (publicationInfo != null)
+ {
+ v.Add(new DerTaggedObject(true, 1, publicationInfo));
+ }
+
+ return new DerSequence(v);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/Challenge.cs b/Crypto/src/asn1/cmp/Challenge.cs
new file mode 100644
index 000000000..bee5f96f5
--- /dev/null
+++ b/Crypto/src/asn1/cmp/Challenge.cs
@@ -0,0 +1,79 @@
+using System;
+
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class Challenge
+ : Asn1Encodable
+ {
+ private readonly AlgorithmIdentifier owf;
+ private readonly Asn1OctetString witness;
+ private readonly Asn1OctetString challenge;
+
+ private Challenge(Asn1Sequence seq)
+ {
+ int index = 0;
+
+ if (seq.Count == 3)
+ {
+ owf = AlgorithmIdentifier.GetInstance(seq[index++]);
+ }
+
+ witness = Asn1OctetString.GetInstance(seq[index++]);
+ challenge = Asn1OctetString.GetInstance(seq[index]);
+ }
+
+ public static Challenge GetInstance(object obj)
+ {
+ if (obj is Challenge)
+ return (Challenge)obj;
+
+ if (obj is Asn1Sequence)
+ return new Challenge((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public virtual AlgorithmIdentifier Owf
+ {
+ get { return owf; }
+ }
+
+ /**
+ *
+ * Challenge ::= SEQUENCE {
+ * owf AlgorithmIdentifier OPTIONAL,
+ *
+ * -- MUST be present in the first Challenge; MAY be omitted in
+ * -- any subsequent Challenge in POPODecKeyChallContent (if
+ * -- omitted, then the owf used in the immediately preceding
+ * -- Challenge is to be used).
+ *
+ * witness OCTET STRING,
+ * -- the result of applying the one-way function (owf) to a
+ * -- randomly-generated INTEGER, A. [Note that a different
+ * -- INTEGER MUST be used for each Challenge.]
+ * challenge OCTET STRING
+ * -- the encryption (under the public key for which the cert.
+ * -- request is being made) of Rand, where Rand is specified as
+ * -- Rand ::= SEQUENCE {
+ * -- int INTEGER,
+ * -- - the randomly-generated INTEGER A (above)
+ * -- sender GeneralName
+ * -- - the sender's name (as included in PKIHeader)
+ * -- }
+ * }
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+ v.AddOptional(owf);
+ v.Add(witness);
+ v.Add(challenge);
+ return new DerSequence(v);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/CmpCertificate.cs b/Crypto/src/asn1/cmp/CmpCertificate.cs
new file mode 100644
index 000000000..16ee30059
--- /dev/null
+++ b/Crypto/src/asn1/cmp/CmpCertificate.cs
@@ -0,0 +1,80 @@
+using System;
+
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class CmpCertificate
+ : Asn1Encodable, IAsn1Choice
+ {
+ private readonly X509CertificateStructure x509v3PKCert;
+ private readonly AttributeCertificate x509v2AttrCert;
+
+ /**
+ * Note: the addition of attribute certificates is a BC extension.
+ */
+ public CmpCertificate(AttributeCertificate x509v2AttrCert)
+ {
+ this.x509v2AttrCert = x509v2AttrCert;
+ }
+
+ public CmpCertificate(X509CertificateStructure x509v3PKCert)
+ {
+ if (x509v3PKCert.Version != 3)
+ throw new ArgumentException("only version 3 certificates allowed", "x509v3PKCert");
+
+ this.x509v3PKCert = x509v3PKCert;
+ }
+
+ public static CmpCertificate GetInstance(object obj)
+ {
+ if (obj is CmpCertificate)
+ return (CmpCertificate)obj;
+
+ if (obj is Asn1Sequence)
+ return new CmpCertificate(X509CertificateStructure.GetInstance(obj));
+
+ if (obj is Asn1TaggedObject)
+ return new CmpCertificate(AttributeCertificate.GetInstance(((Asn1TaggedObject)obj).GetObject()));
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public virtual bool IsX509v3PKCert
+ {
+ get { return x509v3PKCert != null; }
+ }
+
+ public virtual X509CertificateStructure X509v3PKCert
+ {
+ get { return x509v3PKCert; }
+ }
+
+ public virtual AttributeCertificate X509v2AttrCert
+ {
+ get { return x509v2AttrCert; }
+ }
+
+ /**
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(pkiStatusInfo);
+ v.AddOptional(errorCode);
+ v.AddOptional(errorDetails);
+ return new DerSequence(v);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/GenMsgContent.cs b/Crypto/src/asn1/cmp/GenMsgContent.cs
new file mode 100644
index 000000000..9f042491c
--- /dev/null
+++ b/Crypto/src/asn1/cmp/GenMsgContent.cs
@@ -0,0 +1,52 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class GenMsgContent
+ : Asn1Encodable
+ {
+ private readonly Asn1Sequence content;
+
+ private GenMsgContent(Asn1Sequence seq)
+ {
+ content = seq;
+ }
+
+ public static GenMsgContent GetInstance(object obj)
+ {
+ if (obj is GenMsgContent)
+ return (GenMsgContent)obj;
+
+ if (obj is Asn1Sequence)
+ return new GenMsgContent((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public GenMsgContent(params InfoTypeAndValue[] itv)
+ {
+ content = new DerSequence(itv);
+ }
+
+ public virtual InfoTypeAndValue[] ToInfoTypeAndValueArray()
+ {
+ InfoTypeAndValue[] result = new InfoTypeAndValue[content.Count];
+ for (int i = 0; i != result.Length; ++i)
+ {
+ result[i] = InfoTypeAndValue.GetInstance(content[i]);
+ }
+ return result;
+ }
+
+ /**
+ *
+ * GenMsgContent ::= SEQUENCE OF InfoTypeAndValue
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return content;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/GenRepContent.cs b/Crypto/src/asn1/cmp/GenRepContent.cs
new file mode 100644
index 000000000..5bdc5550a
--- /dev/null
+++ b/Crypto/src/asn1/cmp/GenRepContent.cs
@@ -0,0 +1,52 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class GenRepContent
+ : Asn1Encodable
+ {
+ private readonly Asn1Sequence content;
+
+ private GenRepContent(Asn1Sequence seq)
+ {
+ content = seq;
+ }
+
+ public static GenRepContent GetInstance(object obj)
+ {
+ if (obj is GenRepContent)
+ return (GenRepContent)obj;
+
+ if (obj is Asn1Sequence)
+ return new GenRepContent((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public GenRepContent(params InfoTypeAndValue[] itv)
+ {
+ content = new DerSequence(itv);
+ }
+
+ public virtual InfoTypeAndValue[] ToInfoTypeAndValueArray()
+ {
+ InfoTypeAndValue[] result = new InfoTypeAndValue[content.Count];
+ for (int i = 0; i != result.Length; ++i)
+ {
+ result[i] = InfoTypeAndValue.GetInstance(content[i]);
+ }
+ return result;
+ }
+
+ /**
+ *
+ * GenRepContent ::= SEQUENCE OF InfoTypeAndValue
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return content;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/InfoTypeAndValue.cs b/Crypto/src/asn1/cmp/InfoTypeAndValue.cs
new file mode 100644
index 000000000..9b51dba02
--- /dev/null
+++ b/Crypto/src/asn1/cmp/InfoTypeAndValue.cs
@@ -0,0 +1,121 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ /**
+ * Example InfoTypeAndValue contents include, but are not limited
+ * to, the following (un-comment in this ASN.1 module and use as
+ * appropriate for a given environment):
+ *
+ * PKIFailureInfo ::= BIT STRING {
+ * badAlg (0),
+ * -- unrecognized or unsupported Algorithm Identifier
+ * badMessageCheck (1), -- integrity check failed (e.g., signature did not verify)
+ * badRequest (2),
+ * -- transaction not permitted or supported
+ * badTime (3), -- messageTime was not sufficiently close to the system time, as defined by local policy
+ * badCertId (4), -- no certificate could be found matching the provided criteria
+ * badDataFormat (5),
+ * -- the data submitted has the wrong format
+ * wrongAuthority (6), -- the authority indicated in the request is different from the one creating the response token
+ * incorrectData (7), -- the requester's data is incorrect (for notary services)
+ * missingTimeStamp (8), -- when the timestamp is missing but should be there (by policy)
+ * badPOP (9) -- the proof-of-possession failed
+ * timeNotAvailable (14),
+ * -- the TSA's time source is not available
+ * unacceptedPolicy (15),
+ * -- the requested TSA policy is not supported by the TSA
+ * unacceptedExtension (16),
+ * -- the requested extension is not supported by the TSA
+ * addInfoNotAvailable (17)
+ * -- the additional information requested could not be understood
+ * -- or is not available
+ * systemFailure (25)
+ * -- the request cannot be handled due to system failure
+ *
+ */
+ public class PkiFailureInfo
+ : DerBitString
+ {
+ public const int BadAlg = (1 << 7); // unrecognized or unsupported Algorithm Identifier
+ public const int BadMessageCheck = (1 << 6); // integrity check failed (e.g., signature did not verify)
+ public const int BadRequest = (1 << 5);
+ public const int BadTime = (1 << 4); // -- messageTime was not sufficiently close to the system time, as defined by local policy
+ public const int BadCertId = (1 << 3); // no certificate could be found matching the provided criteria
+ public const int BadDataFormat = (1 << 2);
+ public const int WrongAuthority = (1 << 1); // the authority indicated in the request is different from the one creating the response token
+ public const int IncorrectData = 1; // the requester's data is incorrect (for notary services)
+ public const int MissingTimeStamp = (1 << 15); // when the timestamp is missing but should be there (by policy)
+ public const int BadPop = (1 << 14); // the proof-of-possession failed
+ public const int TimeNotAvailable = (1 << 9); // the TSA's time source is not available
+ public const int UnacceptedPolicy = (1 << 8); // the requested TSA policy is not supported by the TSA
+ public const int UnacceptedExtension = (1 << 23); //the requested extension is not supported by the TSA
+ public const int AddInfoNotAvailable = (1 << 22); //the additional information requested could not be understood or is not available
+ public const int SystemFailure = (1 << 30); //the request cannot be handled due to system failure
+
+ /**
+ * Basic constructor.
+ */
+ public PkiFailureInfo(
+ int info)
+ : base(GetBytes(info), GetPadBits(info))
+ {
+ }
+
+ public PkiFailureInfo(
+ DerBitString info)
+ : base(info.GetBytes(), info.PadBits)
+ {
+ }
+
+ public override string ToString()
+ {
+ return "PkiFailureInfo: 0x" + this.IntValue.ToString("X");
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/PKIFreeText.cs b/Crypto/src/asn1/cmp/PKIFreeText.cs
new file mode 100644
index 000000000..571c8d93a
--- /dev/null
+++ b/Crypto/src/asn1/cmp/PKIFreeText.cs
@@ -0,0 +1,97 @@
+using System;
+using System.Collections;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class PkiFreeText
+ : Asn1Encodable
+ {
+ internal Asn1Sequence strings;
+
+ public static PkiFreeText GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ return GetInstance(Asn1Sequence.GetInstance(obj, isExplicit));
+ }
+
+ public static PkiFreeText GetInstance(
+ object obj)
+ {
+ if (obj is PkiFreeText)
+ {
+ return (PkiFreeText)obj;
+ }
+ else if (obj is Asn1Sequence)
+ {
+ return new PkiFreeText((Asn1Sequence)obj);
+ }
+
+ throw new ArgumentException("Unknown object in factory: " + obj.GetType().Name, "obj");
+ }
+
+ public PkiFreeText(
+ Asn1Sequence seq)
+ {
+ foreach (object o in seq)
+ {
+ if (!(o is DerUtf8String))
+ {
+ throw new ArgumentException("attempt to insert non UTF8 STRING into PkiFreeText");
+ }
+ }
+
+ this.strings = seq;
+ }
+
+ public PkiFreeText(
+ DerUtf8String p)
+ {
+ strings = new DerSequence(p);
+ }
+
+ /**
+ * Return the number of string elements present.
+ *
+ * @return number of elements present.
+ */
+ [Obsolete("Use 'Count' property instead")]
+ public int Size
+ {
+ get { return strings.Count; }
+ }
+
+ public int Count
+ {
+ get { return strings.Count; }
+ }
+
+ /**
+ * Return the UTF8STRING at index.
+ *
+ * @param index index of the string of interest
+ * @return the string at index.
+ */
+ public DerUtf8String this[int index]
+ {
+ get { return (DerUtf8String) strings[index]; }
+ }
+
+ [Obsolete("Use 'object[index]' syntax instead")]
+ public DerUtf8String GetStringAt(
+ int index)
+ {
+ return this[index];
+ }
+
+ /**
+ *
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return strings;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/PKIHeader.cs b/Crypto/src/asn1/cmp/PKIHeader.cs
new file mode 100644
index 000000000..e758e9f16
--- /dev/null
+++ b/Crypto/src/asn1/cmp/PKIHeader.cs
@@ -0,0 +1,237 @@
+using System;
+
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class PkiHeader
+ : Asn1Encodable
+ {
+ /**
+ * Value for a "null" recipient or sender.
+ */
+ public static readonly GeneralName NULL_NAME = new GeneralName(X509Name.GetInstance(new DerSequence()));
+
+ public static readonly int CMP_1999 = 1;
+ public static readonly int CMP_2000 = 2;
+
+ private readonly DerInteger pvno;
+ private readonly GeneralName sender;
+ private readonly GeneralName recipient;
+ private readonly DerGeneralizedTime messageTime;
+ private readonly AlgorithmIdentifier protectionAlg;
+ private readonly Asn1OctetString senderKID; // KeyIdentifier
+ private readonly Asn1OctetString recipKID; // KeyIdentifier
+ private readonly Asn1OctetString transactionID;
+ private readonly Asn1OctetString senderNonce;
+ private readonly Asn1OctetString recipNonce;
+ private readonly PkiFreeText freeText;
+ private readonly Asn1Sequence generalInfo;
+
+ private PkiHeader(Asn1Sequence seq)
+ {
+ pvno = DerInteger.GetInstance(seq[0]);
+ sender = GeneralName.GetInstance(seq[1]);
+ recipient = GeneralName.GetInstance(seq[2]);
+
+ for (int pos = 3; pos < seq.Count; ++pos)
+ {
+ Asn1TaggedObject tObj = (Asn1TaggedObject)seq[pos];
+
+ switch (tObj.TagNo)
+ {
+ case 0:
+ messageTime = DerGeneralizedTime.GetInstance(tObj, true);
+ break;
+ case 1:
+ protectionAlg = AlgorithmIdentifier.GetInstance(tObj, true);
+ break;
+ case 2:
+ senderKID = Asn1OctetString.GetInstance(tObj, true);
+ break;
+ case 3:
+ recipKID = Asn1OctetString.GetInstance(tObj, true);
+ break;
+ case 4:
+ transactionID = Asn1OctetString.GetInstance(tObj, true);
+ break;
+ case 5:
+ senderNonce = Asn1OctetString.GetInstance(tObj, true);
+ break;
+ case 6:
+ recipNonce = Asn1OctetString.GetInstance(tObj, true);
+ break;
+ case 7:
+ freeText = PkiFreeText.GetInstance(tObj, true);
+ break;
+ case 8:
+ generalInfo = Asn1Sequence.GetInstance(tObj, true);
+ break;
+ default:
+ throw new ArgumentException("unknown tag number: " + tObj.TagNo, "seq");
+ }
+ }
+ }
+
+ public static PkiHeader GetInstance(object obj)
+ {
+ if (obj is PkiHeader)
+ return (PkiHeader)obj;
+
+ if (obj is Asn1Sequence)
+ return new PkiHeader((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public PkiHeader(
+ int pvno,
+ GeneralName sender,
+ GeneralName recipient)
+ : this(new DerInteger(pvno), sender, recipient)
+ {
+ }
+
+ private PkiHeader(
+ DerInteger pvno,
+ GeneralName sender,
+ GeneralName recipient)
+ {
+ this.pvno = pvno;
+ this.sender = sender;
+ this.recipient = recipient;
+ }
+
+ public virtual DerInteger Pvno
+ {
+ get { return pvno; }
+ }
+
+ public virtual GeneralName Sender
+ {
+ get { return sender; }
+ }
+
+ public virtual GeneralName Recipient
+ {
+ get { return recipient; }
+ }
+
+ public virtual DerGeneralizedTime MessageTime
+ {
+ get { return messageTime; }
+ }
+
+ public virtual AlgorithmIdentifier ProtectionAlg
+ {
+ get { return protectionAlg; }
+ }
+
+ public virtual Asn1OctetString SenderKID
+ {
+ get { return senderKID; }
+ }
+
+ public virtual Asn1OctetString RecipKID
+ {
+ get { return recipKID; }
+ }
+
+ public virtual Asn1OctetString TransactionID
+ {
+ get { return transactionID; }
+ }
+
+ public virtual Asn1OctetString SenderNonce
+ {
+ get { return senderNonce; }
+ }
+
+ public virtual Asn1OctetString RecipNonce
+ {
+ get { return recipNonce; }
+ }
+
+ public virtual PkiFreeText FreeText
+ {
+ get { return freeText; }
+ }
+
+ public virtual InfoTypeAndValue[] GetGeneralInfo()
+ {
+ if (generalInfo == null)
+ {
+ return null;
+ }
+ InfoTypeAndValue[] results = new InfoTypeAndValue[generalInfo.Count];
+ for (int i = 0; i < results.Length; i++)
+ {
+ results[i] = InfoTypeAndValue.GetInstance(generalInfo[i]);
+ }
+ return results;
+ }
+
+ /**
+ *
+ * PkiHeader ::= SEQUENCE {
+ * pvno INTEGER { cmp1999(1), cmp2000(2) },
+ * sender GeneralName,
+ * -- identifies the sender
+ * recipient GeneralName,
+ * -- identifies the intended recipient
+ * messageTime [0] GeneralizedTime OPTIONAL,
+ * -- time of production of this message (used when sender
+ * -- believes that the transport will be "suitable"; i.e.,
+ * -- that the time will still be meaningful upon receipt)
+ * protectionAlg [1] AlgorithmIdentifier OPTIONAL,
+ * -- algorithm used for calculation of protection bits
+ * senderKID [2] KeyIdentifier OPTIONAL,
+ * recipKID [3] KeyIdentifier OPTIONAL,
+ * -- to identify specific keys used for protection
+ * transactionID [4] OCTET STRING OPTIONAL,
+ * -- identifies the transaction; i.e., this will be the same in
+ * -- corresponding request, response, certConf, and PKIConf
+ * -- messages
+ * senderNonce [5] OCTET STRING OPTIONAL,
+ * recipNonce [6] OCTET STRING OPTIONAL,
+ * -- nonces used to provide replay protection, senderNonce
+ * -- is inserted by the creator of this message; recipNonce
+ * -- is a nonce previously inserted in a related message by
+ * -- the intended recipient of this message
+ * freeText [7] PKIFreeText OPTIONAL,
+ * -- this may be used to indicate context-specific instructions
+ * -- (this field is intended for human consumption)
+ * generalInfo [8] SEQUENCE SIZE (1..MAX) OF
+ * InfoTypeAndValue OPTIONAL
+ * -- this may be used to convey context-specific information
+ * -- (this field not primarily intended for human consumption)
+ * }
+ *
+ * PKIHeader ::= SEQUENCE {
+ * pvno INTEGER { cmp1999(1), cmp2000(2) },
+ * sender GeneralName,
+ * -- identifies the sender
+ * recipient GeneralName,
+ * -- identifies the intended recipient
+ * messageTime [0] GeneralizedTime OPTIONAL,
+ * -- time of production of this message (used when sender
+ * -- believes that the transport will be "suitable"; i.e.,
+ * -- that the time will still be meaningful upon receipt)
+ * protectionAlg [1] AlgorithmIdentifier OPTIONAL,
+ * -- algorithm used for calculation of protection bits
+ * senderKID [2] KeyIdentifier OPTIONAL,
+ * recipKID [3] KeyIdentifier OPTIONAL,
+ * -- to identify specific keys used for protection
+ * transactionID [4] OCTET STRING OPTIONAL,
+ * -- identifies the transaction; i.e., this will be the same in
+ * -- corresponding request, response, certConf, and PKIConf
+ * -- messages
+ * senderNonce [5] OCTET STRING OPTIONAL,
+ * recipNonce [6] OCTET STRING OPTIONAL,
+ * -- nonces used to provide replay protection, senderNonce
+ * -- is inserted by the creator of this message; recipNonce
+ * -- is a nonce previously inserted in a related message by
+ * -- the intended recipient of this message
+ * freeText [7] PKIFreeText OPTIONAL,
+ * -- this may be used to indicate context-specific instructions
+ * -- (this field is intended for human consumption)
+ * generalInfo [8] SEQUENCE SIZE (1..MAX) OF
+ * InfoTypeAndValue OPTIONAL
+ * -- this may be used to convey context-specific information
+ * -- (this field not primarily intended for human consumption)
+ * }
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return content;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/PKIStatus.cs b/Crypto/src/asn1/cmp/PKIStatus.cs
new file mode 100644
index 000000000..b03dd3d62
--- /dev/null
+++ b/Crypto/src/asn1/cmp/PKIStatus.cs
@@ -0,0 +1,62 @@
+using System;
+
+using Org.BouncyCastle.Math;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public enum PkiStatus
+ {
+ Granted = 0,
+ GrantedWithMods = 1,
+ Rejection = 2,
+ Waiting = 3,
+ RevocationWarning = 4,
+ RevocationNotification = 5,
+ KeyUpdateWarning = 6,
+ }
+
+ public class PkiStatusEncodable
+ : Asn1Encodable
+ {
+ public static readonly PkiStatusEncodable granted = new PkiStatusEncodable(PkiStatus.Granted);
+ public static readonly PkiStatusEncodable grantedWithMods = new PkiStatusEncodable(PkiStatus.GrantedWithMods);
+ public static readonly PkiStatusEncodable rejection = new PkiStatusEncodable(PkiStatus.Rejection);
+ public static readonly PkiStatusEncodable waiting = new PkiStatusEncodable(PkiStatus.Waiting);
+ public static readonly PkiStatusEncodable revocationWarning = new PkiStatusEncodable(PkiStatus.RevocationWarning);
+ public static readonly PkiStatusEncodable revocationNotification = new PkiStatusEncodable(PkiStatus.RevocationNotification);
+ public static readonly PkiStatusEncodable keyUpdateWaiting = new PkiStatusEncodable(PkiStatus.KeyUpdateWarning);
+
+ private readonly DerInteger status;
+
+ private PkiStatusEncodable(PkiStatus status)
+ : this(new DerInteger((int)status))
+ {
+ }
+
+ private PkiStatusEncodable(DerInteger status)
+ {
+ this.status = status;
+ }
+
+ public static PkiStatusEncodable GetInstance(object obj)
+ {
+ if (obj is PkiStatusEncodable)
+ return (PkiStatusEncodable)obj;
+
+ if (obj is DerInteger)
+ return new PkiStatusEncodable((DerInteger)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public virtual BigInteger Value
+ {
+ get { return status.Value; }
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ return status;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/PKIStatusInfo.cs b/Crypto/src/asn1/cmp/PKIStatusInfo.cs
new file mode 100644
index 000000000..2463e0081
--- /dev/null
+++ b/Crypto/src/asn1/cmp/PKIStatusInfo.cs
@@ -0,0 +1,165 @@
+using System;
+
+using Org.BouncyCastle.Math;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class PkiStatusInfo
+ : Asn1Encodable
+ {
+ DerInteger status;
+ PkiFreeText statusString;
+ DerBitString failInfo;
+
+ public static PkiStatusInfo GetInstance(
+ Asn1TaggedObject obj,
+ bool isExplicit)
+ {
+ return GetInstance(Asn1Sequence.GetInstance(obj, isExplicit));
+ }
+
+ public static PkiStatusInfo GetInstance(
+ object obj)
+ {
+ if (obj is PkiStatusInfo)
+ {
+ return (PkiStatusInfo)obj;
+ }
+ else if (obj is Asn1Sequence)
+ {
+ return new PkiStatusInfo((Asn1Sequence)obj);
+ }
+
+ throw new ArgumentException("Unknown object in factory: " + obj.GetType().Name, "obj");
+ }
+
+ public PkiStatusInfo(
+ Asn1Sequence seq)
+ {
+ this.status = DerInteger.GetInstance(seq[0]);
+
+ this.statusString = null;
+ this.failInfo = null;
+
+ if (seq.Count > 2)
+ {
+ this.statusString = PkiFreeText.GetInstance(seq[1]);
+ this.failInfo = DerBitString.GetInstance(seq[2]);
+ }
+ else if (seq.Count > 1)
+ {
+ object obj = seq[1];
+ if (obj is DerBitString)
+ {
+ this.failInfo = DerBitString.GetInstance(obj);
+ }
+ else
+ {
+ this.statusString = PkiFreeText.GetInstance(obj);
+ }
+ }
+ }
+
+ /**
+ * @param status
+ */
+ public PkiStatusInfo(int status)
+ {
+ this.status = new DerInteger(status);
+ }
+
+ /**
+ * @param status
+ * @param statusString
+ */
+ public PkiStatusInfo(
+ int status,
+ PkiFreeText statusString)
+ {
+ this.status = new DerInteger(status);
+ this.statusString = statusString;
+ }
+
+ public PkiStatusInfo(
+ int status,
+ PkiFreeText statusString,
+ PkiFailureInfo failInfo)
+ {
+ this.status = new DerInteger(status);
+ this.statusString = statusString;
+ this.failInfo = failInfo;
+ }
+
+ public BigInteger Status
+ {
+ get
+ {
+ return status.Value;
+ }
+ }
+
+ public PkiFreeText StatusString
+ {
+ get
+ {
+ return statusString;
+ }
+ }
+
+ public DerBitString FailInfo
+ {
+ get
+ {
+ return failInfo;
+ }
+ }
+
+ /**
+ *
+ * PkiStatusInfo ::= SEQUENCE {
+ * status PKIStatus, (INTEGER)
+ * statusString PkiFreeText OPTIONAL,
+ * failInfo PkiFailureInfo OPTIONAL (BIT STRING)
+ * }
+ *
+ * PKIStatus:
+ * granted (0), -- you got exactly what you asked for
+ * grantedWithMods (1), -- you got something like what you asked for
+ * rejection (2), -- you don't get it, more information elsewhere in the message
+ * waiting (3), -- the request body part has not yet been processed, expect to hear more later
+ * revocationWarning (4), -- this message contains a warning that a revocation is imminent
+ * revocationNotification (5), -- notification that a revocation has occurred
+ * keyUpdateWarning (6) -- update already done for the oldCertId specified in CertReqMsg
+ *
+ * PkiFailureInfo:
+ * badAlg (0), -- unrecognized or unsupported Algorithm Identifier
+ * badMessageCheck (1), -- integrity check failed (e.g., signature did not verify)
+ * badRequest (2), -- transaction not permitted or supported
+ * badTime (3), -- messageTime was not sufficiently close to the system time, as defined by local policy
+ * badCertId (4), -- no certificate could be found matching the provided criteria
+ * badDataFormat (5), -- the data submitted has the wrong format
+ * wrongAuthority (6), -- the authority indicated in the request is different from the one creating the response token
+ * incorrectData (7), -- the requester's data is incorrect (for notary services)
+ * missingTimeStamp (8), -- when the timestamp is missing but should be there (by policy)
+ * badPOP (9) -- the proof-of-possession failed
+ *
+ *
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(status);
+
+ if (statusString != null)
+ {
+ v.Add(statusString);
+ }
+
+ if (failInfo!= null)
+ {
+ v.Add(failInfo);
+ }
+
+ return new DerSequence(v);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/PbmParameter.cs b/Crypto/src/asn1/cmp/PbmParameter.cs
new file mode 100644
index 000000000..59b1bd7bb
--- /dev/null
+++ b/Crypto/src/asn1/cmp/PbmParameter.cs
@@ -0,0 +1,100 @@
+using System;
+
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class PbmParameter
+ : Asn1Encodable
+ {
+ private Asn1OctetString salt;
+ private AlgorithmIdentifier owf;
+ private DerInteger iterationCount;
+ private AlgorithmIdentifier mac;
+
+ private PbmParameter(Asn1Sequence seq)
+ {
+ salt = Asn1OctetString.GetInstance(seq[0]);
+ owf = AlgorithmIdentifier.GetInstance(seq[1]);
+ iterationCount = DerInteger.GetInstance(seq[2]);
+ mac = AlgorithmIdentifier.GetInstance(seq[3]);
+ }
+
+ public static PbmParameter GetInstance(object obj)
+ {
+ if (obj is PbmParameter)
+ return (PbmParameter)obj;
+
+ if (obj is Asn1Sequence)
+ return new PbmParameter((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public PbmParameter(
+ byte[] salt,
+ AlgorithmIdentifier owf,
+ int iterationCount,
+ AlgorithmIdentifier mac)
+ : this(new DerOctetString(salt), owf, new DerInteger(iterationCount), mac)
+ {
+ }
+
+ public PbmParameter(
+ Asn1OctetString salt,
+ AlgorithmIdentifier owf,
+ DerInteger iterationCount,
+ AlgorithmIdentifier mac)
+ {
+ this.salt = salt;
+ this.owf = owf;
+ this.iterationCount = iterationCount;
+ this.mac = mac;
+ }
+
+ public virtual Asn1OctetString Salt
+ {
+ get { return salt; }
+ }
+
+ public virtual AlgorithmIdentifier Owf
+ {
+ get { return owf; }
+ }
+
+ public virtual DerInteger IterationCount
+ {
+ get { return iterationCount; }
+ }
+
+ public virtual AlgorithmIdentifier Mac
+ {
+ get { return mac; }
+ }
+
+ /**
+ *
+ * PbmParameter ::= SEQUENCE {
+ * salt OCTET STRING,
+ * -- note: implementations MAY wish to limit acceptable sizes
+ * -- of this string to values appropriate for their environment
+ * -- in order to reduce the risk of denial-of-service attacks
+ * owf AlgorithmIdentifier,
+ * -- AlgId for a One-Way Function (SHA-1 recommended)
+ * iterationCount INTEGER,
+ * -- number of times the OWF is applied
+ * -- note: implementations MAY wish to limit acceptable sizes
+ * -- of this integer to values appropriate for their environment
+ * -- in order to reduce the risk of denial-of-service attacks
+ * mac AlgorithmIdentifier
+ * -- the MAC AlgId (e.g., DES-MAC, Triple-DES-MAC [PKCS11],
+ * } -- or HMAC [RFC2104, RFC2202])
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(salt, owf, iterationCount, mac);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/PollRepContent.cs b/Crypto/src/asn1/cmp/PollRepContent.cs
new file mode 100644
index 000000000..4045ac7ed
--- /dev/null
+++ b/Crypto/src/asn1/cmp/PollRepContent.cs
@@ -0,0 +1,66 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class PollRepContent
+ : Asn1Encodable
+ {
+ private readonly DerInteger certReqId;
+ private readonly DerInteger checkAfter;
+ private readonly PkiFreeText reason;
+
+ private PollRepContent(Asn1Sequence seq)
+ {
+ certReqId = DerInteger.GetInstance(seq[0]);
+ checkAfter = DerInteger.GetInstance(seq[1]);
+
+ if (seq.Count > 2)
+ {
+ reason = PkiFreeText.GetInstance(seq[2]);
+ }
+ }
+
+ public static PollRepContent GetInstance(object obj)
+ {
+ if (obj is PollRepContent)
+ return (PollRepContent)obj;
+
+ if (obj is Asn1Sequence)
+ return new PollRepContent((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public virtual DerInteger CertReqID
+ {
+ get { return certReqId; }
+ }
+
+ public virtual DerInteger CheckAfter
+ {
+ get { return checkAfter; }
+ }
+
+ public virtual PkiFreeText Reason
+ {
+ get { return reason; }
+ }
+
+ /**
+ *
+ * PollRepContent ::= SEQUENCE OF SEQUENCE {
+ * certReqId INTEGER,
+ * checkAfter INTEGER, -- time in seconds
+ * reason PKIFreeText OPTIONAL
+ * }
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(certReqId, checkAfter);
+ v.AddOptional(reason);
+ return new DerSequence(v);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/PollReqContent.cs b/Crypto/src/asn1/cmp/PollReqContent.cs
new file mode 100644
index 000000000..ca2164151
--- /dev/null
+++ b/Crypto/src/asn1/cmp/PollReqContent.cs
@@ -0,0 +1,59 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class PollReqContent
+ : Asn1Encodable
+ {
+ private readonly Asn1Sequence content;
+
+ private PollReqContent(Asn1Sequence seq)
+ {
+ content = seq;
+ }
+
+ public static PollReqContent GetInstance(object obj)
+ {
+ if (obj is PollReqContent)
+ return (PollReqContent)obj;
+
+ if (obj is Asn1Sequence)
+ return new PollReqContent((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public virtual DerInteger[][] GetCertReqIDs()
+ {
+ DerInteger[][] result = new DerInteger[content.Count][];
+ for (int i = 0; i != result.Length; ++i)
+ {
+ result[i] = SequenceToDerIntegerArray((Asn1Sequence)content[i]);
+ }
+ return result;
+ }
+
+ private static DerInteger[] SequenceToDerIntegerArray(Asn1Sequence seq)
+ {
+ DerInteger[] result = new DerInteger[seq.Count];
+ for (int i = 0; i != result.Length; ++i)
+ {
+ result[i] = DerInteger.GetInstance(seq[i]);
+ }
+ return result;
+ }
+
+ /**
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(status, certId, willBeRevokedAt, badSinceDate);
+ v.AddOptional(crlDetails);
+ return new DerSequence(v);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/RevDetails.cs b/Crypto/src/asn1/cmp/RevDetails.cs
new file mode 100644
index 000000000..1bd95f1db
--- /dev/null
+++ b/Crypto/src/asn1/cmp/RevDetails.cs
@@ -0,0 +1,75 @@
+using System;
+
+using Org.BouncyCastle.Asn1.Crmf;
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class RevDetails
+ : Asn1Encodable
+ {
+ private readonly CertTemplate certDetails;
+ private readonly X509Extensions crlEntryDetails;
+
+ private RevDetails(Asn1Sequence seq)
+ {
+ certDetails = CertTemplate.GetInstance(seq[0]);
+
+ if (seq.Count > 1)
+ {
+ crlEntryDetails = X509Extensions.GetInstance(seq[1]);
+ }
+ }
+
+ public static RevDetails GetInstance(object obj)
+ {
+ if (obj is RevDetails)
+ return (RevDetails)obj;
+
+ if (obj is Asn1Sequence)
+ return new RevDetails((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public RevDetails(CertTemplate certDetails)
+ {
+ this.certDetails = certDetails;
+ }
+
+ public RevDetails(CertTemplate certDetails, X509Extensions crlEntryDetails)
+ {
+ this.crlEntryDetails = crlEntryDetails;
+ }
+
+ public virtual CertTemplate CertDetails
+ {
+ get { return certDetails; }
+ }
+
+ public virtual X509Extensions CrlEntryDetails
+ {
+ get { return crlEntryDetails; }
+ }
+
+ /**
+ *
+ * RevDetails ::= SEQUENCE {
+ * certDetails CertTemplate,
+ * -- allows requester to specify as much as they can about
+ * -- the cert. for which revocation is requested
+ * -- (e.g., for cases in which serialNumber is not available)
+ * crlEntryDetails Extensions OPTIONAL
+ * -- requested crlEntryExtensions
+ * }
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(certDetails);
+ v.AddOptional(crlEntryDetails);
+ return new DerSequence(v);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/RevRepContent.cs b/Crypto/src/asn1/cmp/RevRepContent.cs
new file mode 100644
index 000000000..47987265a
--- /dev/null
+++ b/Crypto/src/asn1/cmp/RevRepContent.cs
@@ -0,0 +1,112 @@
+using System;
+
+using Org.BouncyCastle.Asn1.Crmf;
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class RevRepContent
+ : Asn1Encodable
+ {
+ private readonly Asn1Sequence status;
+ private readonly Asn1Sequence revCerts;
+ private readonly Asn1Sequence crls;
+
+ private RevRepContent(Asn1Sequence seq)
+ {
+ status = Asn1Sequence.GetInstance(seq[0]);
+
+ for (int pos = 1; pos < seq.Count; ++pos)
+ {
+ Asn1TaggedObject tObj = Asn1TaggedObject.GetInstance(seq[pos]);
+
+ if (tObj.TagNo == 0)
+ {
+ revCerts = Asn1Sequence.GetInstance(tObj, true);
+ }
+ else
+ {
+ crls = Asn1Sequence.GetInstance(tObj, true);
+ }
+ }
+ }
+
+ public static RevRepContent GetInstance(object obj)
+ {
+ if (obj is RevRepContent)
+ return (RevRepContent)obj;
+
+ if (obj is Asn1Sequence)
+ return new RevRepContent((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public virtual PkiStatusInfo[] GetStatus()
+ {
+ PkiStatusInfo[] results = new PkiStatusInfo[status.Count];
+ for (int i = 0; i != results.Length; ++i)
+ {
+ results[i] = PkiStatusInfo.GetInstance(status[i]);
+ }
+ return results;
+ }
+
+ public virtual CertId[] GetRevCerts()
+ {
+ if (revCerts == null)
+ return null;
+
+ CertId[] results = new CertId[revCerts.Count];
+ for (int i = 0; i != results.Length; ++i)
+ {
+ results[i] = CertId.GetInstance(revCerts[i]);
+ }
+ return results;
+ }
+
+ public virtual CertificateList[] GetCrls()
+ {
+ if (crls == null)
+ return null;
+
+ CertificateList[] results = new CertificateList[crls.Count];
+ for (int i = 0; i != results.Length; ++i)
+ {
+ results[i] = CertificateList.GetInstance(crls[i]);
+ }
+ return results;
+ }
+
+ /**
+ *
+ * RevRepContent ::= SEQUENCE {
+ * status SEQUENCE SIZE (1..MAX) OF PKIStatusInfo,
+ * -- in same order as was sent in RevReqContent
+ * revCerts [0] SEQUENCE SIZE (1..MAX) OF CertId OPTIONAL,
+ * -- IDs for which revocation was requested
+ * -- (same order as status)
+ * crls [1] SEQUENCE SIZE (1..MAX) OF CertificateList OPTIONAL
+ * -- the resulting CRLs (there may be more than one)
+ * }
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(status);
+ AddOptional(v, 0, revCerts);
+ AddOptional(v, 1, crls);
+ return new DerSequence(v);
+ }
+
+ private void AddOptional(Asn1EncodableVector v, int tagNo, Asn1Encodable obj)
+ {
+ if (obj != null)
+ {
+ v.Add(new DerTaggedObject(true, tagNo, obj));
+ }
+ }
+ }
+}
+
diff --git a/Crypto/src/asn1/cmp/RevRepContentBuilder.cs b/Crypto/src/asn1/cmp/RevRepContentBuilder.cs
new file mode 100644
index 000000000..cc17d1d4c
--- /dev/null
+++ b/Crypto/src/asn1/cmp/RevRepContentBuilder.cs
@@ -0,0 +1,55 @@
+using System;
+
+using Org.BouncyCastle.Asn1.Crmf;
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class RevRepContentBuilder
+ {
+ private readonly Asn1EncodableVector status = new Asn1EncodableVector();
+ private readonly Asn1EncodableVector revCerts = new Asn1EncodableVector();
+ private readonly Asn1EncodableVector crls = new Asn1EncodableVector();
+
+ public virtual RevRepContentBuilder Add(PkiStatusInfo status)
+ {
+ this.status.Add(status);
+ return this;
+ }
+
+ public virtual RevRepContentBuilder Add(PkiStatusInfo status, CertId certId)
+ {
+ if (this.status.Count != this.revCerts.Count)
+ throw new InvalidOperationException("status and revCerts sequence must be in common order");
+
+ this.status.Add(status);
+ this.revCerts.Add(certId);
+ return this;
+ }
+
+ public virtual RevRepContentBuilder AddCrl(CertificateList crl)
+ {
+ this.crls.Add(crl);
+ return this;
+ }
+
+ public virtual RevRepContent Build()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+
+ v.Add(new DerSequence(status));
+
+ if (revCerts.Count != 0)
+ {
+ v.Add(new DerTaggedObject(true, 0, new DerSequence(revCerts)));
+ }
+
+ if (crls.Count != 0)
+ {
+ v.Add(new DerTaggedObject(true, 1, new DerSequence(crls)));
+ }
+
+ return RevRepContent.GetInstance(new DerSequence(v));
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cmp/RevReqContent.cs b/Crypto/src/asn1/cmp/RevReqContent.cs
new file mode 100644
index 000000000..fbf869203
--- /dev/null
+++ b/Crypto/src/asn1/cmp/RevReqContent.cs
@@ -0,0 +1,52 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.Cmp
+{
+ public class RevReqContent
+ : Asn1Encodable
+ {
+ private readonly Asn1Sequence content;
+
+ private RevReqContent(Asn1Sequence seq)
+ {
+ content = seq;
+ }
+
+ public static RevReqContent GetInstance(object obj)
+ {
+ if (obj is RevReqContent)
+ return (RevReqContent)obj;
+
+ if (obj is Asn1Sequence)
+ return new RevReqContent((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public RevReqContent(params RevDetails[] revDetails)
+ {
+ this.content = new DerSequence(revDetails);
+ }
+
+ public virtual RevDetails[] ToRevDetailsArray()
+ {
+ RevDetails[] result = new RevDetails[content.Count];
+ for (int i = 0; i != result.Length; ++i)
+ {
+ result[i] = RevDetails.GetInstance(content[i]);
+ }
+ return result;
+ }
+
+ /**
+ *
+ * RevReqContent ::= SEQUENCE OF RevDetails
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return content;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/cms/Attribute.cs b/Crypto/src/asn1/cms/Attribute.cs
new file mode 100644
index 000000000..c4a104a3f
--- /dev/null
+++ b/Crypto/src/asn1/cms/Attribute.cs
@@ -0,0 +1,70 @@
+using System;
+
+using Org.BouncyCastle.Asn1;
+
+namespace Org.BouncyCastle.Asn1.Cms
+{
+ public class Attribute
+ : Asn1Encodable
+ {
+ private DerObjectIdentifier attrType;
+ private Asn1Set attrValues;
+
+ /**
+ * return an Attribute object from the given object.
+ *
+ * @param o the object we want converted.
+ * @exception ArgumentException if the object cannot be converted.
+ */
+ public static Attribute GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is Attribute)
+ return (Attribute) obj;
+
+ if (obj is Asn1Sequence)
+ return new Attribute((Asn1Sequence) obj);
+
+ throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj");
+ }
+
+ public Attribute(
+ Asn1Sequence seq)
+ {
+ attrType = (DerObjectIdentifier)seq[0];
+ attrValues = (Asn1Set)seq[1];
+ }
+
+ public Attribute(
+ DerObjectIdentifier attrType,
+ Asn1Set attrValues)
+ {
+ this.attrType = attrType;
+ this.attrValues = attrValues;
+ }
+
+ public DerObjectIdentifier AttrType
+ {
+ get { return attrType; }
+ }
+
+ public Asn1Set AttrValues
+ {
+ get { return attrValues; }
+ }
+
+ /**
+ * Produce an object suitable for an Asn1OutputStream.
+ *
+ * EncryptedValue ::= SEQUENCE {
+ * intendedAlg [0] AlgorithmIdentifier OPTIONAL,
+ * -- the intended algorithm for which the value will be used
+ * symmAlg [1] AlgorithmIdentifier OPTIONAL,
+ * -- the symmetric algorithm used to encrypt the value
+ * encSymmKey [2] BIT STRING OPTIONAL,
+ * -- the (encrypted) symmetric key used to encrypt the value
+ * keyAlg [3] AlgorithmIdentifier OPTIONAL,
+ * -- algorithm used to encrypt the symmetric key
+ * valueHint [4] OCTET STRING OPTIONAL,
+ * -- a brief description or identifier of the encValue content
+ * -- (may be meaningful only to the sending entity, and used only
+ * -- if EncryptedValue might be re-examined by the sending entity
+ * -- in the future)
+ * encValue BIT STRING }
+ * -- the encrypted value itself
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+
+ AddOptional(v, 0, intendedAlg);
+ AddOptional(v, 1, symmAlg);
+ AddOptional(v, 2, encSymmKey);
+ AddOptional(v, 3, keyAlg);
+ AddOptional(v, 4, valueHint);
+
+ v.Add(encValue);
+
+ return new DerSequence(v);
+ }
+
+ private void AddOptional(Asn1EncodableVector v, int tagNo, Asn1Encodable obj)
+ {
+ if (obj != null)
+ {
+ v.Add(new DerTaggedObject(false, tagNo, obj));
+ }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/crmf/OptionalValidity.cs b/Crypto/src/asn1/crmf/OptionalValidity.cs
new file mode 100644
index 000000000..c0037999a
--- /dev/null
+++ b/Crypto/src/asn1/crmf/OptionalValidity.cs
@@ -0,0 +1,64 @@
+using System;
+
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.Crmf
+{
+ public class OptionalValidity
+ : Asn1Encodable
+ {
+ private readonly Time notBefore;
+ private readonly Time notAfter;
+
+ private OptionalValidity(Asn1Sequence seq)
+ {
+ foreach (Asn1TaggedObject tObj in seq)
+ {
+ if (tObj.TagNo == 0)
+ {
+ notBefore = Time.GetInstance(tObj, true);
+ }
+ else
+ {
+ notAfter = Time.GetInstance(tObj, true);
+ }
+ }
+ }
+
+ public static OptionalValidity GetInstance(object obj)
+ {
+ if (obj is OptionalValidity)
+ return (OptionalValidity)obj;
+
+ if (obj is Asn1Sequence)
+ return new OptionalValidity((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ /**
+ *
+ * OptionalValidity ::= SEQUENCE {
+ * notBefore [0] Time OPTIONAL,
+ * notAfter [1] Time OPTIONAL } --at least one MUST be present
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+
+ if (notBefore != null)
+ {
+ v.Add(new DerTaggedObject(true, 0, notBefore));
+ }
+
+ if (notAfter != null)
+ {
+ v.Add(new DerTaggedObject(true, 1, notAfter));
+ }
+
+ return new DerSequence(v);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/crmf/PKIArchiveOptions.cs b/Crypto/src/asn1/crmf/PKIArchiveOptions.cs
new file mode 100644
index 000000000..910f73b22
--- /dev/null
+++ b/Crypto/src/asn1/crmf/PKIArchiveOptions.cs
@@ -0,0 +1,105 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.Crmf
+{
+ public class PkiArchiveOptions
+ : Asn1Encodable, IAsn1Choice
+ {
+ public const int encryptedPrivKey = 0;
+ public const int keyGenParameters = 1;
+ public const int archiveRemGenPrivKey = 2;
+
+ private readonly Asn1Encodable value;
+
+ public static PkiArchiveOptions GetInstance(object obj)
+ {
+ if (obj is PkiArchiveOptions)
+ return (PkiArchiveOptions)obj;
+
+ if (obj is Asn1TaggedObject)
+ return new PkiArchiveOptions((Asn1TaggedObject)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ private PkiArchiveOptions(Asn1TaggedObject tagged)
+ {
+ switch (tagged.TagNo)
+ {
+ case encryptedPrivKey:
+ value = EncryptedKey.GetInstance(tagged.GetObject());
+ break;
+ case keyGenParameters:
+ value = Asn1OctetString.GetInstance(tagged, false);
+ break;
+ case archiveRemGenPrivKey:
+ value = DerBoolean.GetInstance(tagged, false);
+ break;
+ default:
+ throw new ArgumentException("unknown tag number: " + tagged.TagNo, "tagged");
+ }
+ }
+
+ public PkiArchiveOptions(EncryptedKey encKey)
+ {
+ this.value = encKey;
+ }
+
+ public PkiArchiveOptions(Asn1OctetString keyGenParameters)
+ {
+ this.value = keyGenParameters;
+ }
+
+ public PkiArchiveOptions(bool archiveRemGenPrivKey)
+ {
+ this.value = DerBoolean.GetInstance(archiveRemGenPrivKey);
+ }
+
+ public virtual int Type
+ {
+ get
+ {
+ if (value is EncryptedKey)
+ return encryptedPrivKey;
+
+ if (value is Asn1OctetString)
+ return keyGenParameters;
+
+ return archiveRemGenPrivKey;
+ }
+ }
+
+ public virtual Asn1Encodable Value
+ {
+ get { return value; }
+ }
+
+ /**
+ *
+ * PkiArchiveOptions ::= CHOICE {
+ * encryptedPrivKey [0] EncryptedKey,
+ * -- the actual value of the private key
+ * keyGenParameters [1] KeyGenParameters,
+ * -- parameters which allow the private key to be re-generated
+ * archiveRemGenPrivKey [2] BOOLEAN }
+ * -- set to TRUE if sender wishes receiver to archive the private
+ * -- key of a key pair that the receiver generates in response to
+ * -- this request; set to FALSE if no archival is desired.
+ *
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ if (value is EncryptedKey)
+ {
+ return new DerTaggedObject(true, encryptedPrivKey, value); // choice
+ }
+
+ if (value is Asn1OctetString)
+ {
+ return new DerTaggedObject(false, keyGenParameters, value);
+ }
+
+ return new DerTaggedObject(false, archiveRemGenPrivKey, value);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/crmf/PKIPublicationInfo.cs b/Crypto/src/asn1/crmf/PKIPublicationInfo.cs
new file mode 100644
index 000000000..c8bc1403e
--- /dev/null
+++ b/Crypto/src/asn1/crmf/PKIPublicationInfo.cs
@@ -0,0 +1,64 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.Crmf
+{
+ public class PkiPublicationInfo
+ : Asn1Encodable
+ {
+ private readonly DerInteger action;
+ private readonly Asn1Sequence pubInfos;
+
+ private PkiPublicationInfo(Asn1Sequence seq)
+ {
+ action = DerInteger.GetInstance(seq[0]);
+ pubInfos = Asn1Sequence.GetInstance(seq[1]);
+ }
+
+ public static PkiPublicationInfo GetInstance(object obj)
+ {
+ if (obj is PkiPublicationInfo)
+ return (PkiPublicationInfo)obj;
+
+ if (obj is Asn1Sequence)
+ return new PkiPublicationInfo((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public virtual DerInteger Action
+ {
+ get { return action; }
+ }
+
+ public virtual SinglePubInfo[] GetPubInfos()
+ {
+ if (pubInfos == null)
+ return null;
+
+ SinglePubInfo[] results = new SinglePubInfo[pubInfos.Count];
+ for (int i = 0; i != results.Length; ++i)
+ {
+ results[i] = SinglePubInfo.GetInstance(pubInfos[i]);
+ }
+ return results;
+ }
+
+ /**
+ *
+ * PkiPublicationInfo ::= SEQUENCE {
+ * action INTEGER {
+ * dontPublish (0),
+ * pleasePublish (1) },
+ * pubInfos SEQUENCE SIZE (1..MAX) OF SinglePubInfo OPTIONAL }
+ * -- pubInfos MUST NOT be present if action is "dontPublish"
+ * -- (if action is "pleasePublish" and pubInfos is omitted,
+ * -- "dontCare" is assumed)
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(action, pubInfos);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/crmf/PKMacValue.cs b/Crypto/src/asn1/crmf/PKMacValue.cs
new file mode 100644
index 000000000..20a08fd1d
--- /dev/null
+++ b/Crypto/src/asn1/crmf/PKMacValue.cs
@@ -0,0 +1,89 @@
+using System;
+
+using Org.BouncyCastle.Asn1.Cmp;
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.Crmf
+{
+ /**
+ * Password-based MAC value for use with POPOSigningKeyInput.
+ */
+ public class PKMacValue
+ : Asn1Encodable
+ {
+ private readonly AlgorithmIdentifier algID;
+ private readonly DerBitString macValue;
+
+ private PKMacValue(Asn1Sequence seq)
+ {
+ this.algID = AlgorithmIdentifier.GetInstance(seq[0]);
+ this.macValue = DerBitString.GetInstance(seq[1]);
+ }
+
+ public static PKMacValue GetInstance(object obj)
+ {
+ if (obj is PKMacValue)
+ return (PKMacValue)obj;
+
+ if (obj is Asn1Sequence)
+ return new PKMacValue((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public static PKMacValue GetInstance(Asn1TaggedObject obj, bool isExplicit)
+ {
+ return GetInstance(Asn1Sequence.GetInstance(obj, isExplicit));
+ }
+
+ /**
+ * Creates a new PKMACValue.
+ * @param params parameters for password-based MAC
+ * @param value MAC of the DER-encoded SubjectPublicKeyInfo
+ */
+ public PKMacValue(
+ PbmParameter pbmParams,
+ DerBitString macValue)
+ : this(new AlgorithmIdentifier(CmpObjectIdentifiers.passwordBasedMac, pbmParams), macValue)
+ {
+ }
+
+ /**
+ * Creates a new PKMACValue.
+ * @param aid CMPObjectIdentifiers.passwordBasedMAC, with PBMParameter
+ * @param value MAC of the DER-encoded SubjectPublicKeyInfo
+ */
+ public PKMacValue(
+ AlgorithmIdentifier algID,
+ DerBitString macValue)
+ {
+ this.algID = algID;
+ this.macValue = macValue;
+ }
+
+ public virtual AlgorithmIdentifier AlgID
+ {
+ get { return algID; }
+ }
+
+ public virtual DerBitString MacValue
+ {
+ get { return macValue; }
+ }
+
+ /**
+ *
+ * PKMACValue ::= SEQUENCE {
+ * algId AlgorithmIdentifier,
+ * -- algorithm value shall be PasswordBasedMac 1.2.840.113533.7.66.13
+ * -- parameter value is PBMParameter
+ * value BIT STRING }
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(algID, macValue);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/crmf/PopoPrivKey.cs b/Crypto/src/asn1/crmf/PopoPrivKey.cs
new file mode 100644
index 000000000..0cedc5127
--- /dev/null
+++ b/Crypto/src/asn1/crmf/PopoPrivKey.cs
@@ -0,0 +1,84 @@
+using System;
+
+using Org.BouncyCastle.Asn1.Cms;
+
+namespace Org.BouncyCastle.Asn1.Crmf
+{
+ public class PopoPrivKey
+ : Asn1Encodable, IAsn1Choice
+ {
+ public const int thisMessage = 0;
+ public const int subsequentMessage = 1;
+ public const int dhMAC = 2;
+ public const int agreeMAC = 3;
+ public const int encryptedKey = 4;
+
+ private readonly int tagNo;
+ private readonly Asn1Encodable obj;
+
+ private PopoPrivKey(Asn1TaggedObject obj)
+ {
+ this.tagNo = obj.TagNo;
+
+ switch (tagNo)
+ {
+ case thisMessage:
+ this.obj = DerBitString.GetInstance(obj, false);
+ break;
+ case subsequentMessage:
+ this.obj = SubsequentMessage.ValueOf(DerInteger.GetInstance(obj, false).Value.IntValue);
+ break;
+ case dhMAC:
+ this.obj = DerBitString.GetInstance(obj, false);
+ break;
+ case agreeMAC:
+ this.obj = PKMacValue.GetInstance(obj, false);
+ break;
+ case encryptedKey:
+ this.obj = EnvelopedData.GetInstance(obj, false);
+ break;
+ default:
+ throw new ArgumentException("unknown tag in PopoPrivKey", "obj");
+ }
+ }
+
+ public static PopoPrivKey GetInstance(Asn1TaggedObject tagged, bool isExplicit)
+ {
+ return new PopoPrivKey(Asn1TaggedObject.GetInstance(tagged.GetObject()));
+ }
+
+ public PopoPrivKey(SubsequentMessage msg)
+ {
+ this.tagNo = subsequentMessage;
+ this.obj = msg;
+ }
+
+ public virtual int Type
+ {
+ get { return tagNo; }
+ }
+
+ public virtual Asn1Encodable Value
+ {
+ get { return obj; }
+ }
+
+ /**
+ *
+ * PopoPrivKey ::= CHOICE {
+ * thisMessage [0] BIT STRING, -- Deprecated
+ * -- possession is proven in this message (which contains the private
+ * -- key itself (encrypted for the CA))
+ * subsequentMessage [1] SubsequentMessage,
+ * -- possession will be proven in a subsequent message
+ * dhMAC [2] BIT STRING, -- Deprecated
+ * agreeMAC [3] PKMACValue,
+ * encryptedKey [4] EnvelopedData }
+ *
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerTaggedObject(false, tagNo, obj);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/crmf/PopoSigningKey.cs b/Crypto/src/asn1/crmf/PopoSigningKey.cs
new file mode 100644
index 000000000..614278eda
--- /dev/null
+++ b/Crypto/src/asn1/crmf/PopoSigningKey.cs
@@ -0,0 +1,115 @@
+using System;
+
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.Crmf
+{
+ public class PopoSigningKey
+ : Asn1Encodable
+ {
+ private readonly PopoSigningKeyInput poposkInput;
+ private readonly AlgorithmIdentifier algorithmIdentifier;
+ private readonly DerBitString signature;
+
+ private PopoSigningKey(Asn1Sequence seq)
+ {
+ int index = 0;
+
+ if (seq[index] is Asn1TaggedObject)
+ {
+ Asn1TaggedObject tagObj
+ = (Asn1TaggedObject) seq[index++];
+ if (tagObj.TagNo != 0)
+ {
+ throw new ArgumentException( "Unknown PopoSigningKeyInput tag: " + tagObj.TagNo, "seq");
+ }
+ poposkInput = PopoSigningKeyInput.GetInstance(tagObj.GetObject());
+ }
+ algorithmIdentifier = AlgorithmIdentifier.GetInstance(seq[index++]);
+ signature = DerBitString.GetInstance(seq[index]);
+ }
+
+ public static PopoSigningKey GetInstance(object obj)
+ {
+ if (obj is PopoSigningKey)
+ return (PopoSigningKey)obj;
+
+ if (obj is Asn1Sequence)
+ return new PopoSigningKey((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public static PopoSigningKey GetInstance(Asn1TaggedObject obj, bool isExplicit)
+ {
+ return GetInstance(Asn1Sequence.GetInstance(obj, isExplicit));
+ }
+
+ /**
+ * Creates a new Proof of Possession object for a signing key.
+ * @param poposkIn the PopoSigningKeyInput structure, or null if the
+ * CertTemplate includes both subject and publicKey values.
+ * @param aid the AlgorithmIdentifier used to sign the proof of possession.
+ * @param signature a signature over the DER-encoded value of poposkIn,
+ * or the DER-encoded value of certReq if poposkIn is null.
+ */
+ public PopoSigningKey(
+ PopoSigningKeyInput poposkIn,
+ AlgorithmIdentifier aid,
+ DerBitString signature)
+ {
+ this.poposkInput = poposkIn;
+ this.algorithmIdentifier = aid;
+ this.signature = signature;
+ }
+
+ public virtual PopoSigningKeyInput PoposkInput
+ {
+ get { return poposkInput; }
+ }
+
+ public virtual AlgorithmIdentifier AlgorithmIdentifier
+ {
+ get { return algorithmIdentifier; }
+ }
+
+ public virtual DerBitString Signature
+ {
+ get { return signature; }
+ }
+
+ /**
+ *
+ * PopoSigningKey ::= SEQUENCE {
+ * poposkInput [0] PopoSigningKeyInput OPTIONAL,
+ * algorithmIdentifier AlgorithmIdentifier,
+ * signature BIT STRING }
+ * -- The signature (using "algorithmIdentifier") is on the
+ * -- DER-encoded value of poposkInput. NOTE: If the CertReqMsg
+ * -- certReq CertTemplate contains the subject and publicKey values,
+ * -- then poposkInput MUST be omitted and the signature MUST be
+ * -- computed on the DER-encoded value of CertReqMsg certReq. If
+ * -- the CertReqMsg certReq CertTemplate does not contain the public
+ * -- key and subject values, then poposkInput MUST be present and
+ * -- MUST be signed. This strategy ensures that the public key is
+ * -- not present in both the poposkInput and CertReqMsg certReq
+ * -- CertTemplate fields.
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+
+ if (poposkInput != null)
+ {
+ v.Add(new DerTaggedObject(false, 0, poposkInput));
+ }
+
+ v.Add(algorithmIdentifier);
+ v.Add(signature);
+
+ return new DerSequence(v);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/crmf/PopoSigningKeyInput.cs b/Crypto/src/asn1/crmf/PopoSigningKeyInput.cs
new file mode 100644
index 000000000..63695262f
--- /dev/null
+++ b/Crypto/src/asn1/crmf/PopoSigningKeyInput.cs
@@ -0,0 +1,115 @@
+using System;
+
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.Crmf
+{
+ public class PopoSigningKeyInput
+ : Asn1Encodable
+ {
+ private readonly GeneralName sender;
+ private readonly PKMacValue publicKeyMac;
+ private readonly SubjectPublicKeyInfo publicKey;
+
+ private PopoSigningKeyInput(Asn1Sequence seq)
+ {
+ Asn1Encodable authInfo = (Asn1Encodable)seq[0];
+
+ if (authInfo is Asn1TaggedObject)
+ {
+ Asn1TaggedObject tagObj = (Asn1TaggedObject)authInfo;
+ if (tagObj.TagNo != 0)
+ {
+ throw new ArgumentException("Unknown authInfo tag: " + tagObj.TagNo, "seq");
+ }
+ sender = GeneralName.GetInstance(tagObj.GetObject());
+ }
+ else
+ {
+ publicKeyMac = PKMacValue.GetInstance(authInfo);
+ }
+
+ publicKey = SubjectPublicKeyInfo.GetInstance(seq[1]);
+ }
+
+ public static PopoSigningKeyInput GetInstance(object obj)
+ {
+ if (obj is PopoSigningKeyInput)
+ return (PopoSigningKeyInput)obj;
+
+ if (obj is Asn1Sequence)
+ return new PopoSigningKeyInput((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ /** Creates a new PopoSigningKeyInput with sender name as authInfo. */
+ public PopoSigningKeyInput(
+ GeneralName sender,
+ SubjectPublicKeyInfo spki)
+ {
+ this.sender = sender;
+ this.publicKey = spki;
+ }
+
+ /** Creates a new PopoSigningKeyInput using password-based MAC. */
+ public PopoSigningKeyInput(
+ PKMacValue pkmac,
+ SubjectPublicKeyInfo spki)
+ {
+ this.publicKeyMac = pkmac;
+ this.publicKey = spki;
+ }
+
+ /** Returns the sender field, or null if authInfo is publicKeyMac */
+ public virtual GeneralName Sender
+ {
+ get { return sender; }
+ }
+
+ /** Returns the publicKeyMac field, or null if authInfo is sender */
+ public virtual PKMacValue PublicKeyMac
+ {
+ get { return publicKeyMac; }
+ }
+
+ public virtual SubjectPublicKeyInfo PublicKey
+ {
+ get { return publicKey; }
+ }
+
+ /**
+ *
+ * PopoSigningKeyInput ::= SEQUENCE {
+ * authInfo CHOICE {
+ * sender [0] GeneralName,
+ * -- used only if an authenticated identity has been
+ * -- established for the sender (e.g., a DN from a
+ * -- previously-issued and currently-valid certificate
+ * publicKeyMac PKMacValue },
+ * -- used if no authenticated GeneralName currently exists for
+ * -- the sender; publicKeyMac contains a password-based MAC
+ * -- on the DER-encoded value of publicKey
+ * publicKey SubjectPublicKeyInfo } -- from CertTemplate
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+
+ if (sender != null)
+ {
+ v.Add(new DerTaggedObject(false, 0, sender));
+ }
+ else
+ {
+ v.Add(publicKeyMac);
+ }
+
+ v.Add(publicKey);
+
+ return new DerSequence(v);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/crmf/ProofOfPossession.cs b/Crypto/src/asn1/crmf/ProofOfPossession.cs
new file mode 100644
index 000000000..fc00edb32
--- /dev/null
+++ b/Crypto/src/asn1/crmf/ProofOfPossession.cs
@@ -0,0 +1,98 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.Crmf
+{
+ public class ProofOfPossession
+ : Asn1Encodable, IAsn1Choice
+ {
+ public const int TYPE_RA_VERIFIED = 0;
+ public const int TYPE_SIGNING_KEY = 1;
+ public const int TYPE_KEY_ENCIPHERMENT = 2;
+ public const int TYPE_KEY_AGREEMENT = 3;
+
+ private readonly int tagNo;
+ private readonly Asn1Encodable obj;
+
+ private ProofOfPossession(Asn1TaggedObject tagged)
+ {
+ tagNo = tagged.TagNo;
+ switch (tagNo)
+ {
+ case 0:
+ obj = DerNull.Instance;
+ break;
+ case 1:
+ obj = PopoSigningKey.GetInstance(tagged, false);
+ break;
+ case 2:
+ case 3:
+ obj = PopoPrivKey.GetInstance(tagged, false);
+ break;
+ default:
+ throw new ArgumentException("unknown tag: " + tagNo, "tagged");
+ }
+ }
+
+ public static ProofOfPossession GetInstance(object obj)
+ {
+ if (obj is ProofOfPossession)
+ return (ProofOfPossession)obj;
+
+ if (obj is Asn1TaggedObject)
+ return new ProofOfPossession((Asn1TaggedObject)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ /** Creates a ProofOfPossession with type raVerified. */
+ public ProofOfPossession()
+ {
+ tagNo = TYPE_RA_VERIFIED;
+ obj = DerNull.Instance;
+ }
+
+ /** Creates a ProofOfPossession for a signing key. */
+ public ProofOfPossession(PopoSigningKey Poposk)
+ {
+ tagNo = TYPE_SIGNING_KEY;
+ obj = Poposk;
+ }
+
+ /**
+ * Creates a ProofOfPossession for key encipherment or agreement.
+ * @param type one of TYPE_KEY_ENCIPHERMENT or TYPE_KEY_AGREEMENT
+ */
+ public ProofOfPossession(int type, PopoPrivKey privkey)
+ {
+ tagNo = type;
+ obj = privkey;
+ }
+
+ public virtual int Type
+ {
+ get { return tagNo; }
+ }
+
+ public virtual Asn1Encodable Object
+ {
+ get { return obj; }
+ }
+
+ /**
+ *
+ * ProofOfPossession ::= CHOICE {
+ * raVerified [0] NULL,
+ * -- used if the RA has already verified that the requester is in
+ * -- possession of the private key
+ * signature [1] PopoSigningKey,
+ * keyEncipherment [2] PopoPrivKey,
+ * keyAgreement [3] PopoPrivKey }
+ *
+ * @return a basic ASN.1 object representation.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerTaggedObject(false, tagNo, obj);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/crmf/SinglePubInfo.cs b/Crypto/src/asn1/crmf/SinglePubInfo.cs
new file mode 100644
index 000000000..eaf8a3efd
--- /dev/null
+++ b/Crypto/src/asn1/crmf/SinglePubInfo.cs
@@ -0,0 +1,58 @@
+using System;
+
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.Crmf
+{
+ public class SinglePubInfo
+ : Asn1Encodable
+ {
+ private readonly DerInteger pubMethod;
+ private readonly GeneralName pubLocation;
+
+ private SinglePubInfo(Asn1Sequence seq)
+ {
+ pubMethod = DerInteger.GetInstance(seq[0]);
+
+ if (seq.Count == 2)
+ {
+ pubLocation = GeneralName.GetInstance(seq[1]);
+ }
+ }
+
+ public static SinglePubInfo GetInstance(object obj)
+ {
+ if (obj is SinglePubInfo)
+ return (SinglePubInfo)obj;
+
+ if (obj is Asn1Sequence)
+ return new SinglePubInfo((Asn1Sequence)obj);
+
+ throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj");
+ }
+
+ public virtual GeneralName PubLocation
+ {
+ get { return pubLocation; }
+ }
+
+ /**
+ *
+ * @return
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(ldsVersion, unicodeVersion);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/isismtt/ISISMTTObjectIdentifiers.cs b/Crypto/src/asn1/isismtt/ISISMTTObjectIdentifiers.cs
new file mode 100644
index 000000000..af60b030a
--- /dev/null
+++ b/Crypto/src/asn1/isismtt/ISISMTTObjectIdentifiers.cs
@@ -0,0 +1,177 @@
+namespace Org.BouncyCastle.Asn1.IsisMtt
+{
+ public abstract class IsisMttObjectIdentifiers
+ {
+ public static readonly DerObjectIdentifier IdIsisMtt = new DerObjectIdentifier("1.3.36.8");
+
+ public static readonly DerObjectIdentifier IdIsisMttCP = new DerObjectIdentifier(IdIsisMtt + ".1");
+
+ /**
+ * The id-isismtt-cp-accredited OID indicates that the certificate is a
+ * qualified certificate according to Directive 1999/93/EC of the European
+ * Parliament and of the Council of 13 December 1999 on a Community
+ * Framework for Electronic Signatures, which additionally conforms the
+ * special requirements of the SigG and has been issued by an accredited CA.
+ */
+ public static readonly DerObjectIdentifier IdIsisMttCPAccredited = new DerObjectIdentifier(IdIsisMttCP + ".1");
+
+ public static readonly DerObjectIdentifier IdIsisMttAT = new DerObjectIdentifier(IdIsisMtt + ".3");
+
+ /**
+ * Certificate extensionDate of certificate generation
+ *
+ *
+ * DateOfCertGenSyntax ::= GeneralizedTime
+ *
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATDateOfCertGen = new DerObjectIdentifier(IdIsisMttAT + ".1");
+
+ /**
+ * Attribute to indicate that the certificate holder may sign in the name of
+ * a third person. May also be used as extension in a certificate.
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATProcuration = new DerObjectIdentifier(IdIsisMttAT + ".2");
+
+ /**
+ * Attribute to indicate admissions to certain professions. May be used as
+ * attribute in attribute certificate or as extension in a certificate
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATAdmission = new DerObjectIdentifier(IdIsisMttAT + ".3");
+
+ /**
+ * Monetary limit for transactions. The QcEuMonetaryLimit QC statement MUST
+ * be used in new certificates in place of the extension/attribute
+ * MonetaryLimit since January 1, 2004. For the sake of backward
+ * compatibility with certificates already in use, SigG conforming
+ * components MUST support MonetaryLimit (as well as QcEuLimitValue).
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATMonetaryLimit = new DerObjectIdentifier(IdIsisMttAT + ".4");
+
+ /**
+ * A declaration of majority. May be used as attribute in attribute
+ * certificate or as extension in a certificate
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATDeclarationOfMajority = new DerObjectIdentifier(IdIsisMttAT + ".5");
+
+ /**
+ *
+ * Serial number of the smart card containing the corresponding private key
+ *
+ *
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATIccsn = new DerObjectIdentifier(IdIsisMttAT + ".6");
+
+ /**
+ *
+ * Reference for a file of a smartcard that stores the public key of this
+ * certificate and that is used as �security anchor�.
+ *
+ *
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATPKReference = new DerObjectIdentifier(IdIsisMttAT + ".7");
+
+ /**
+ * Some other restriction regarding the usage of this certificate. May be
+ * used as attribute in attribute certificate or as extension in a
+ * certificate.
+ *
+ *
+ *
+ * @see Org.BouncyCastle.Asn1.IsisMtt.X509.Restriction
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATRestriction = new DerObjectIdentifier(IdIsisMttAT + ".8");
+
+ /**
+ *
+ * (Single)Request extension: Clients may include this extension in a
+ * (single) Request to request the responder to send the certificate in the
+ * response message along with the status information. Besides the LDAP
+ * service, this extension provides another mechanism for the distribution
+ * of certificates, which MAY optionally be provided by certificate
+ * repositories.
+ *
+ *
+ * RetrieveIfAllowed ::= BOOLEAN
+ *
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATRetrieveIfAllowed = new DerObjectIdentifier(IdIsisMttAT + ".9");
+
+ /**
+ * SingleOCSPResponse extension: The certificate requested by the client by
+ * inserting the RetrieveIfAllowed extension in the request, will be
+ * returned in this extension.
+ *
+ * @see Org.BouncyCastle.Asn1.IsisMtt.Ocsp.RequestedCertificate
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATRequestedCertificate = new DerObjectIdentifier(IdIsisMttAT + ".10");
+
+ /**
+ * Base ObjectIdentifier for naming authorities
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATNamingAuthorities = new DerObjectIdentifier(IdIsisMttAT + ".11");
+
+ /**
+ * SingleOCSPResponse extension: Date, when certificate has been published
+ * in the directory and status information has become available. Currently,
+ * accrediting authorities enforce that SigG-conforming OCSP servers include
+ * this extension in the responses.
+ *
+ *
+ * CertInDirSince ::= GeneralizedTime
+ *
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATCertInDirSince = new DerObjectIdentifier(IdIsisMttAT + ".12");
+
+ /**
+ * Hash of a certificate in OCSP.
+ *
+ * @see Org.BouncyCastle.Asn1.IsisMtt.Ocsp.CertHash
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATCertHash = new DerObjectIdentifier(IdIsisMttAT + ".13");
+
+ /**
+ *
+ *
+ * Used in
+ * {@link Org.BouncyCastle.Asn1.X509.SubjectDirectoryAttributes SubjectDirectoryAttributes}
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATNameAtBirth = new DerObjectIdentifier(IdIsisMttAT + ".14");
+
+ /**
+ * Some other information of non-restrictive nature regarding the usage of
+ * this certificate. May be used as attribute in atribute certificate or as
+ * extension in a certificate.
+ *
+ *
+ *
+ * @see Org.BouncyCastle.Asn1.IsisMtt.X509.AdditionalInformationSyntax
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATAdditionalInformation = new DerObjectIdentifier(IdIsisMttAT + ".15");
+
+ /**
+ * Indicates that an attribute certificate exists, which limits the
+ * usability of this public key certificate. Whenever verifying a signature
+ * with the help of this certificate, the content of the corresponding
+ * attribute certificate should be concerned. This extension MUST be
+ * included in a PKC, if a corresponding attribute certificate (having the
+ * PKC as base certificate) contains some attribute that restricts the
+ * usability of the PKC too. Attribute certificates with restricting content
+ * MUST always be included in the signed document.
+ *
+ *
+ * LiabilityLimitationFlagSyntax ::= BOOLEAN
+ *
+ */
+ public static readonly DerObjectIdentifier IdIsisMttATLiabilityLimitationFlag = new DerObjectIdentifier("0.2.262.1.10.12.0");
+ }
+}
diff --git a/Crypto/src/asn1/isismtt/ocsp/CertHash.cs b/Crypto/src/asn1/isismtt/ocsp/CertHash.cs
new file mode 100644
index 000000000..da5b530e4
--- /dev/null
+++ b/Crypto/src/asn1/isismtt/ocsp/CertHash.cs
@@ -0,0 +1,121 @@
+using System;
+
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.IsisMtt.Ocsp
+{
+ /**
+ * ISIS-MTT PROFILE: The responder may include this extension in a response to
+ * send the hash of the requested certificate to the responder. This hash is
+ * cryptographically bound to the certificate and serves as evidence that the
+ * certificate is known to the responder (i.e. it has been issued and is present
+ * in the directory). Hence, this extension is a means to provide a positive
+ * statement of availability as described in T8.[8]. As explained in T13.[1],
+ * clients may rely on this information to be able to validate signatures after
+ * the expiry of the corresponding certificate. Hence, clients MUST support this
+ * extension. If a positive statement of availability is to be delivered, this
+ * extension syntax and OID MUST be used.
+ *
+ *
+ *
+ *
+ * @return an Asn1Object
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(hashAlgorithm, new DerOctetString(certificateHash));
+ }
+ }
+}
diff --git a/Crypto/src/asn1/isismtt/ocsp/RequestedCertificate.cs b/Crypto/src/asn1/isismtt/ocsp/RequestedCertificate.cs
new file mode 100644
index 000000000..7724bfed6
--- /dev/null
+++ b/Crypto/src/asn1/isismtt/ocsp/RequestedCertificate.cs
@@ -0,0 +1,186 @@
+using System;
+using System.IO;
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.IsisMtt.Ocsp
+{
+ /**
+ * ISIS-MTT-Optional: The certificate requested by the client by inserting the
+ * RetrieveIfAllowed extension in the request, will be returned in this
+ * extension.
+ *
+ * ISIS-MTT-SigG: The signature act allows publishing certificates only then,
+ * when the certificate owner gives his isExplicit permission. Accordingly, there
+ * may be �nondownloadable� certificates, about which the responder must provide
+ * status information, but MUST NOT include them in the response. Clients may
+ * get therefore the following three kind of answers on a single request
+ * including the RetrieveIfAllowed extension:
+ *
+ *
a) the responder supports the extension and is allowed to publish the
+ * certificate: RequestedCertificate returned including the requested
+ * certificate
+ *
b) the responder supports the extension but is NOT allowed to publish
+ * the certificate: RequestedCertificate returned including an empty OCTET
+ * STRING
+ *
c) the responder does not support the extension: RequestedCertificate is
+ * not included in the response
+ *
+ * Clients requesting RetrieveIfAllowed MUST be able to handle these cases. If
+ * any of the OCTET STRING options is used, it MUST contain the DER encoding of
+ * the requested certificate.
+ *
+ *
+ *
+ * @return an Asn1Object
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector vec = new Asn1EncodableVector();
+ if (namingAuthorityID != null)
+ {
+ vec.Add(namingAuthorityID);
+ }
+ if (namingAuthorityUrl != null)
+ {
+ vec.Add(new DerIA5String(namingAuthorityUrl, true));
+ }
+ if (namingAuthorityText != null)
+ {
+ vec.Add(namingAuthorityText);
+ }
+ return new DerSequence(vec);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/isismtt/x509/ProcurationSyntax.cs b/Crypto/src/asn1/isismtt/x509/ProcurationSyntax.cs
new file mode 100644
index 000000000..a25df225e
--- /dev/null
+++ b/Crypto/src/asn1/isismtt/x509/ProcurationSyntax.cs
@@ -0,0 +1,232 @@
+using System;
+using System.Collections;
+
+using Org.BouncyCastle.Asn1.X500;
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.IsisMtt.X509
+{
+ /**
+ * Attribute to indicate that the certificate holder may sign in the name of a
+ * third person.
+ *
+ * ISIS-MTT PROFILE: The corresponding ProcurationSyntax contains either the
+ * name of the person who is represented (subcomponent thirdPerson) or a
+ * reference to his/her base certificate (in the component signingFor,
+ * subcomponent certRef), furthermore the optional components country and
+ * typeSubstitution to indicate the country whose laws apply, and respectively
+ * the type of procuration (e.g. manager, procuration, custody).
+ *
+ *
+ * ISIS-MTT PROFILE: The GeneralName MUST be of type directoryName and MAY only
+ * contain: - RFC3039 attributes, except pseudonym (countryName, commonName,
+ * surname, givenName, serialNumber, organizationName, organizationalUnitName,
+ * stateOrProvincename, localityName, postalAddress) and - SubjectDirectoryName
+ * attributes (title, dateOfBirth, placeOfBirth, gender, countryOfCitizenship,
+ * countryOfResidence and NameAtBirth).
+ *
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(algId, data);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/pkcs/EncryptionScheme.cs b/Crypto/src/asn1/pkcs/EncryptionScheme.cs
new file mode 100644
index 000000000..5b64d6f67
--- /dev/null
+++ b/Crypto/src/asn1/pkcs/EncryptionScheme.cs
@@ -0,0 +1,49 @@
+using System;
+
+using Org.BouncyCastle.Asn1;
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.Pkcs
+{
+ public class EncryptionScheme
+ : AlgorithmIdentifier
+ {
+ public EncryptionScheme(
+ DerObjectIdentifier objectID,
+ Asn1Encodable parameters)
+ : base(objectID, parameters)
+ {
+ }
+
+ internal EncryptionScheme(
+ Asn1Sequence seq)
+ : this((DerObjectIdentifier)seq[0], seq[1])
+ {
+ }
+
+ public new static EncryptionScheme GetInstance(object obj)
+ {
+ if (obj is EncryptionScheme)
+ {
+ return (EncryptionScheme)obj;
+ }
+
+ if (obj is Asn1Sequence)
+ {
+ return new EncryptionScheme((Asn1Sequence)obj);
+ }
+
+ throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj");
+ }
+
+ public Asn1Object Asn1Object
+ {
+ get { return Parameters.ToAsn1Object(); }
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(ObjectID, Parameters);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/pkcs/IssuerAndSerialNumber.cs b/Crypto/src/asn1/pkcs/IssuerAndSerialNumber.cs
new file mode 100644
index 000000000..ff608f15b
--- /dev/null
+++ b/Crypto/src/asn1/pkcs/IssuerAndSerialNumber.cs
@@ -0,0 +1,71 @@
+using System;
+
+using Org.BouncyCastle.Asn1.X509;
+using Org.BouncyCastle.Math;
+
+namespace Org.BouncyCastle.Asn1.Pkcs
+{
+ public class IssuerAndSerialNumber
+ : Asn1Encodable
+ {
+ private readonly X509Name name;
+ private readonly DerInteger certSerialNumber;
+
+ public static IssuerAndSerialNumber GetInstance(
+ object obj)
+ {
+ if (obj is IssuerAndSerialNumber)
+ {
+ return (IssuerAndSerialNumber) obj;
+ }
+
+ if (obj is Asn1Sequence)
+ {
+ return new IssuerAndSerialNumber((Asn1Sequence) obj);
+ }
+
+ throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj");
+ }
+
+ private IssuerAndSerialNumber(
+ Asn1Sequence seq)
+ {
+ if (seq.Count != 2)
+ throw new ArgumentException("Wrong number of elements in sequence", "seq");
+
+ this.name = X509Name.GetInstance(seq[0]);
+ this.certSerialNumber = DerInteger.GetInstance(seq[1]);
+ }
+
+ public IssuerAndSerialNumber(
+ X509Name name,
+ BigInteger certSerialNumber)
+ {
+ this.name = name;
+ this.certSerialNumber = new DerInteger(certSerialNumber);
+ }
+
+ public IssuerAndSerialNumber(
+ X509Name name,
+ DerInteger certSerialNumber)
+ {
+ this.name = name;
+ this.certSerialNumber = certSerialNumber;
+ }
+
+ public X509Name Name
+ {
+ get { return name; }
+ }
+
+ public DerInteger CertificateSerialNumber
+ {
+ get { return certSerialNumber; }
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(name, certSerialNumber);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/pkcs/KeyDerivationFunc.cs b/Crypto/src/asn1/pkcs/KeyDerivationFunc.cs
new file mode 100644
index 000000000..9fc89853b
--- /dev/null
+++ b/Crypto/src/asn1/pkcs/KeyDerivationFunc.cs
@@ -0,0 +1,21 @@
+using Org.BouncyCastle.Asn1;
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.Pkcs
+{
+ public class KeyDerivationFunc
+ : AlgorithmIdentifier
+ {
+ internal KeyDerivationFunc(Asn1Sequence seq)
+ : base(seq)
+ {
+ }
+
+ public KeyDerivationFunc(
+ DerObjectIdentifier id,
+ Asn1Encodable parameters)
+ : base(id, parameters)
+ {
+ }
+ }
+}
\ No newline at end of file
diff --git a/Crypto/src/asn1/pkcs/MacData.cs b/Crypto/src/asn1/pkcs/MacData.cs
new file mode 100644
index 000000000..780b24153
--- /dev/null
+++ b/Crypto/src/asn1/pkcs/MacData.cs
@@ -0,0 +1,96 @@
+using System;
+
+using Org.BouncyCastle.Asn1;
+using Org.BouncyCastle.Asn1.X509;
+using Org.BouncyCastle.Math;
+
+namespace Org.BouncyCastle.Asn1.Pkcs
+{
+ public class MacData
+ : Asn1Encodable
+ {
+ internal DigestInfo digInfo;
+ internal byte[] salt;
+ internal BigInteger iterationCount;
+
+ public static MacData GetInstance(
+ object obj)
+ {
+ if (obj is MacData)
+ {
+ return (MacData) obj;
+ }
+
+ if (obj is Asn1Sequence)
+ {
+ return new MacData((Asn1Sequence) obj);
+ }
+
+ throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj");
+ }
+
+ private MacData(
+ Asn1Sequence seq)
+ {
+ this.digInfo = DigestInfo.GetInstance(seq[0]);
+ this.salt = ((Asn1OctetString) seq[1]).GetOctets();
+
+ if (seq.Count == 3)
+ {
+ this.iterationCount = ((DerInteger) seq[2]).Value;
+ }
+ else
+ {
+ this.iterationCount = BigInteger.One;
+ }
+ }
+
+ public MacData(
+ DigestInfo digInfo,
+ byte[] salt,
+ int iterationCount)
+ {
+ this.digInfo = digInfo;
+ this.salt = (byte[]) salt.Clone();
+ this.iterationCount = BigInteger.ValueOf(iterationCount);
+ }
+
+ public DigestInfo Mac
+ {
+ get { return digInfo; }
+ }
+
+ public byte[] GetSalt()
+ {
+ return (byte[]) salt.Clone();
+ }
+
+ public BigInteger IterationCount
+ {
+ get { return iterationCount; }
+ }
+
+ /**
+ *
+ * MacData ::= SEQUENCE {
+ * mac DigestInfo,
+ * macSalt OCTET STRING,
+ * iterations INTEGER DEFAULT 1
+ * -- Note: The default is for historic reasons and its use is deprecated. A
+ * -- higher value, like 1024 is recommended.
+ *
+ * @return the basic DERObject construction.
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(digInfo, new DerOctetString(salt));
+
+ if (!iterationCount.Equals(BigInteger.One))
+ {
+ v.Add(new DerInteger(iterationCount));
+ }
+
+ return new DerSequence(v);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/pkcs/PBEParameter.cs b/Crypto/src/asn1/pkcs/PBEParameter.cs
new file mode 100644
index 000000000..80d5ec3e1
--- /dev/null
+++ b/Crypto/src/asn1/pkcs/PBEParameter.cs
@@ -0,0 +1,60 @@
+using System;
+using System.Collections;
+
+using Org.BouncyCastle.Asn1;
+using Org.BouncyCastle.Math;
+
+namespace Org.BouncyCastle.Asn1.Pkcs
+{
+ public class PbeParameter
+ : Asn1Encodable
+ {
+ private readonly Asn1OctetString salt;
+ private readonly DerInteger iterationCount;
+
+ public static PbeParameter GetInstance(object obj)
+ {
+ if (obj is PbeParameter || obj == null)
+ {
+ return (PbeParameter) obj;
+ }
+
+ if (obj is Asn1Sequence)
+ {
+ return new PbeParameter((Asn1Sequence) obj);
+ }
+
+ throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj");
+ }
+
+ private PbeParameter(Asn1Sequence seq)
+ {
+ if (seq.Count != 2)
+ throw new ArgumentException("Wrong number of elements in sequence", "seq");
+
+ salt = Asn1OctetString.GetInstance(seq[0]);
+ iterationCount = DerInteger.GetInstance(seq[1]);
+ }
+
+ public PbeParameter(byte[] salt, int iterationCount)
+ {
+ this.salt = new DerOctetString(salt);
+ this.iterationCount = new DerInteger(iterationCount);
+ }
+
+ public byte[] GetSalt()
+ {
+ return salt.GetOctets();
+ }
+
+ public BigInteger IterationCount
+ {
+ get { return iterationCount.Value; }
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(salt, iterationCount);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/pkcs/PBES2Parameters.cs b/Crypto/src/asn1/pkcs/PBES2Parameters.cs
new file mode 100644
index 000000000..645bb867c
--- /dev/null
+++ b/Crypto/src/asn1/pkcs/PBES2Parameters.cs
@@ -0,0 +1,61 @@
+using System;
+using System.Collections;
+
+namespace Org.BouncyCastle.Asn1.Pkcs
+{
+ public class PbeS2Parameters
+ : Asn1Encodable
+ {
+ private readonly KeyDerivationFunc func;
+ private readonly EncryptionScheme scheme;
+
+ public static PbeS2Parameters GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is PbeS2Parameters)
+ return (PbeS2Parameters) obj;
+
+ if (obj is Asn1Sequence)
+ return new PbeS2Parameters((Asn1Sequence) obj);
+
+ throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj");
+ }
+
+ public PbeS2Parameters(
+ Asn1Sequence seq)
+ {
+ if (seq.Count != 2)
+ throw new ArgumentException("Wrong number of elements in sequence", "seq");
+
+ Asn1Sequence funcSeq = (Asn1Sequence)seq[0].ToAsn1Object();
+
+ // TODO Not sure if this special case is really necessary/appropriate
+ if (funcSeq[0].Equals(PkcsObjectIdentifiers.IdPbkdf2))
+ {
+ func = new KeyDerivationFunc(PkcsObjectIdentifiers.IdPbkdf2,
+ Pbkdf2Params.GetInstance(funcSeq[1]));
+ }
+ else
+ {
+ func = new KeyDerivationFunc(funcSeq);
+ }
+
+ scheme = EncryptionScheme.GetInstance(seq[1].ToAsn1Object());
+ }
+
+ public KeyDerivationFunc KeyDerivationFunc
+ {
+ get { return func; }
+ }
+
+ public EncryptionScheme EncryptionScheme
+ {
+ get { return scheme; }
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(func, scheme);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/pkcs/PBKDF2Params.cs b/Crypto/src/asn1/pkcs/PBKDF2Params.cs
new file mode 100644
index 000000000..1351b94cf
--- /dev/null
+++ b/Crypto/src/asn1/pkcs/PBKDF2Params.cs
@@ -0,0 +1,86 @@
+using System;
+
+using Org.BouncyCastle.Math;
+
+namespace Org.BouncyCastle.Asn1.Pkcs
+{
+ public class Pbkdf2Params
+ : Asn1Encodable
+ {
+ private readonly Asn1OctetString octStr;
+ private readonly DerInteger iterationCount;
+ private readonly DerInteger keyLength;
+
+ public static Pbkdf2Params GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is Pbkdf2Params)
+ return (Pbkdf2Params)obj;
+
+ if (obj is Asn1Sequence)
+ return new Pbkdf2Params((Asn1Sequence)obj);
+
+ throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj");
+ }
+
+ public Pbkdf2Params(
+ Asn1Sequence seq)
+ {
+ if (seq.Count < 2 || seq.Count > 3)
+ throw new ArgumentException("Wrong number of elements in sequence", "seq");
+
+ octStr = (Asn1OctetString)seq[0];
+ iterationCount = (DerInteger)seq[1];
+
+ if (seq.Count > 2)
+ {
+ keyLength = (DerInteger)seq[2];
+ }
+ }
+
+ public Pbkdf2Params(
+ byte[] salt,
+ int iterationCount)
+ {
+ this.octStr = new DerOctetString(salt);
+ this.iterationCount = new DerInteger(iterationCount);
+ }
+
+ public Pbkdf2Params(
+ byte[] salt,
+ int iterationCount,
+ int keyLength)
+ : this(salt, iterationCount)
+ {
+ this.keyLength = new DerInteger(keyLength);
+ }
+
+ public byte[] GetSalt()
+ {
+ return octStr.GetOctets();
+ }
+
+ public BigInteger IterationCount
+ {
+ get { return iterationCount.Value; }
+ }
+
+ public BigInteger KeyLength
+ {
+ get { return keyLength == null ? null : keyLength.Value; }
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(
+ octStr, iterationCount);
+
+ if (keyLength != null)
+ {
+ v.Add(keyLength);
+ }
+
+ return new DerSequence(v);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/pkcs/PKCS12PBEParams.cs b/Crypto/src/asn1/pkcs/PKCS12PBEParams.cs
new file mode 100644
index 000000000..7521f93ea
--- /dev/null
+++ b/Crypto/src/asn1/pkcs/PKCS12PBEParams.cs
@@ -0,0 +1,63 @@
+using System;
+
+using Org.BouncyCastle.Asn1;
+using Org.BouncyCastle.Math;
+
+namespace Org.BouncyCastle.Asn1.Pkcs
+{
+ public class Pkcs12PbeParams
+ : Asn1Encodable
+ {
+ private readonly DerInteger iterations;
+ private readonly Asn1OctetString iv;
+
+ public Pkcs12PbeParams(
+ byte[] salt,
+ int iterations)
+ {
+ this.iv = new DerOctetString(salt);
+ this.iterations = new DerInteger(iterations);
+ }
+
+ private Pkcs12PbeParams(
+ Asn1Sequence seq)
+ {
+ if (seq.Count != 2)
+ throw new ArgumentException("Wrong number of elements in sequence", "seq");
+
+ iv = Asn1OctetString.GetInstance(seq[0]);
+ iterations = DerInteger.GetInstance(seq[1]);
+ }
+
+ public static Pkcs12PbeParams GetInstance(
+ object obj)
+ {
+ if (obj is Pkcs12PbeParams)
+ {
+ return (Pkcs12PbeParams) obj;
+ }
+
+ if (obj is Asn1Sequence)
+ {
+ return new Pkcs12PbeParams((Asn1Sequence) obj);
+ }
+
+ throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj");
+ }
+
+ public BigInteger Iterations
+ {
+ get { return iterations.Value; }
+ }
+
+ public byte[] GetIV()
+ {
+ return iv.GetOctets();
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(iv, iterations);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/pkcs/PKCSObjectIdentifiers.cs b/Crypto/src/asn1/pkcs/PKCSObjectIdentifiers.cs
new file mode 100644
index 000000000..0b2ffa0d1
--- /dev/null
+++ b/Crypto/src/asn1/pkcs/PKCSObjectIdentifiers.cs
@@ -0,0 +1,256 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.Pkcs
+{
+ public abstract class PkcsObjectIdentifiers
+ {
+ //
+ // pkcs-1 OBJECT IDENTIFIER ::= {
+ // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
+ //
+ public const string Pkcs1 = "1.2.840.113549.1.1";
+
+ public static readonly DerObjectIdentifier RsaEncryption = new DerObjectIdentifier(Pkcs1 + ".1");
+ public static readonly DerObjectIdentifier MD2WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".2");
+ public static readonly DerObjectIdentifier MD4WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".3");
+ public static readonly DerObjectIdentifier MD5WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".4");
+ public static readonly DerObjectIdentifier Sha1WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".5");
+ public static readonly DerObjectIdentifier SrsaOaepEncryptionSet = new DerObjectIdentifier(Pkcs1 + ".6");
+ public static readonly DerObjectIdentifier IdRsaesOaep = new DerObjectIdentifier(Pkcs1 + ".7");
+ public static readonly DerObjectIdentifier IdMgf1 = new DerObjectIdentifier(Pkcs1 + ".8");
+ public static readonly DerObjectIdentifier IdPSpecified = new DerObjectIdentifier(Pkcs1 + ".9");
+ public static readonly DerObjectIdentifier IdRsassaPss = new DerObjectIdentifier(Pkcs1 + ".10");
+ public static readonly DerObjectIdentifier Sha256WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".11");
+ public static readonly DerObjectIdentifier Sha384WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".12");
+ public static readonly DerObjectIdentifier Sha512WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".13");
+ public static readonly DerObjectIdentifier Sha224WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".14");
+
+ //
+ // pkcs-3 OBJECT IDENTIFIER ::= {
+ // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 3 }
+ //
+ public const string Pkcs3 = "1.2.840.113549.1.3";
+
+ public static readonly DerObjectIdentifier DhKeyAgreement = new DerObjectIdentifier(Pkcs3 + ".1");
+
+ //
+ // pkcs-5 OBJECT IDENTIFIER ::= {
+ // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 5 }
+ //
+ public const string Pkcs5 = "1.2.840.113549.1.5";
+
+ public static readonly DerObjectIdentifier PbeWithMD2AndDesCbc = new DerObjectIdentifier(Pkcs5 + ".1");
+ public static readonly DerObjectIdentifier PbeWithMD2AndRC2Cbc = new DerObjectIdentifier(Pkcs5 + ".4");
+ public static readonly DerObjectIdentifier PbeWithMD5AndDesCbc = new DerObjectIdentifier(Pkcs5 + ".3");
+ public static readonly DerObjectIdentifier PbeWithMD5AndRC2Cbc = new DerObjectIdentifier(Pkcs5 + ".6");
+ public static readonly DerObjectIdentifier PbeWithSha1AndDesCbc = new DerObjectIdentifier(Pkcs5 + ".10");
+ public static readonly DerObjectIdentifier PbeWithSha1AndRC2Cbc = new DerObjectIdentifier(Pkcs5 + ".11");
+
+ public static readonly DerObjectIdentifier IdPbeS2 = new DerObjectIdentifier(Pkcs5 + ".13");
+ public static readonly DerObjectIdentifier IdPbkdf2 = new DerObjectIdentifier(Pkcs5 + ".12");
+
+ //
+ // encryptionAlgorithm OBJECT IDENTIFIER ::= {
+ // iso(1) member-body(2) us(840) rsadsi(113549) 3 }
+ //
+ public const string EncryptionAlgorithm = "1.2.840.113549.3";
+
+ public static readonly DerObjectIdentifier DesEde3Cbc = new DerObjectIdentifier(EncryptionAlgorithm + ".7");
+ public static readonly DerObjectIdentifier RC2Cbc = new DerObjectIdentifier(EncryptionAlgorithm + ".2");
+
+ //
+ // object identifiers for digests
+ //
+ public const string DigestAlgorithm = "1.2.840.113549.2";
+
+ //
+ // md2 OBJECT IDENTIFIER ::=
+ // {iso(1) member-body(2) US(840) rsadsi(113549) DigestAlgorithm(2) 2}
+ //
+ public static readonly DerObjectIdentifier MD2 = new DerObjectIdentifier(DigestAlgorithm + ".2");
+
+ //
+ // md4 OBJECT IDENTIFIER ::=
+ // {iso(1) member-body(2) US(840) rsadsi(113549) DigestAlgorithm(2) 4}
+ //
+ public static readonly DerObjectIdentifier MD4 = new DerObjectIdentifier(DigestAlgorithm + ".4");
+
+ //
+ // md5 OBJECT IDENTIFIER ::=
+ // {iso(1) member-body(2) US(840) rsadsi(113549) DigestAlgorithm(2) 5}
+ //
+ public static readonly DerObjectIdentifier MD5 = new DerObjectIdentifier(DigestAlgorithm + ".5");
+
+ public static readonly DerObjectIdentifier IdHmacWithSha1 = new DerObjectIdentifier(DigestAlgorithm + ".7");
+ public static readonly DerObjectIdentifier IdHmacWithSha224 = new DerObjectIdentifier(DigestAlgorithm + ".8");
+ public static readonly DerObjectIdentifier IdHmacWithSha256 = new DerObjectIdentifier(DigestAlgorithm + ".9");
+ public static readonly DerObjectIdentifier IdHmacWithSha384 = new DerObjectIdentifier(DigestAlgorithm + ".10");
+ public static readonly DerObjectIdentifier IdHmacWithSha512 = new DerObjectIdentifier(DigestAlgorithm + ".11");
+
+ //
+ // pkcs-7 OBJECT IDENTIFIER ::= {
+ // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 7 }
+ //
+ public const string Pkcs7 = "1.2.840.113549.1.7";
+
+ public static readonly DerObjectIdentifier Data = new DerObjectIdentifier(Pkcs7 + ".1");
+ public static readonly DerObjectIdentifier SignedData = new DerObjectIdentifier(Pkcs7 + ".2");
+ public static readonly DerObjectIdentifier EnvelopedData = new DerObjectIdentifier(Pkcs7 + ".3");
+ public static readonly DerObjectIdentifier SignedAndEnvelopedData = new DerObjectIdentifier(Pkcs7 + ".4");
+ public static readonly DerObjectIdentifier DigestedData = new DerObjectIdentifier(Pkcs7 + ".5");
+ public static readonly DerObjectIdentifier EncryptedData = new DerObjectIdentifier(Pkcs7 + ".6");
+
+ //
+ // pkcs-9 OBJECT IDENTIFIER ::= {
+ // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 9 }
+ //
+ public const string Pkcs9 = "1.2.840.113549.1.9";
+
+ public static readonly DerObjectIdentifier Pkcs9AtEmailAddress = new DerObjectIdentifier(Pkcs9 + ".1");
+ public static readonly DerObjectIdentifier Pkcs9AtUnstructuredName = new DerObjectIdentifier(Pkcs9 + ".2");
+ public static readonly DerObjectIdentifier Pkcs9AtContentType = new DerObjectIdentifier(Pkcs9 + ".3");
+ public static readonly DerObjectIdentifier Pkcs9AtMessageDigest = new DerObjectIdentifier(Pkcs9 + ".4");
+ public static readonly DerObjectIdentifier Pkcs9AtSigningTime = new DerObjectIdentifier(Pkcs9 + ".5");
+ public static readonly DerObjectIdentifier Pkcs9AtCounterSignature = new DerObjectIdentifier(Pkcs9 + ".6");
+ public static readonly DerObjectIdentifier Pkcs9AtChallengePassword = new DerObjectIdentifier(Pkcs9 + ".7");
+ public static readonly DerObjectIdentifier Pkcs9AtUnstructuredAddress = new DerObjectIdentifier(Pkcs9 + ".8");
+ public static readonly DerObjectIdentifier Pkcs9AtExtendedCertificateAttributes = new DerObjectIdentifier(Pkcs9 + ".9");
+ public static readonly DerObjectIdentifier Pkcs9AtSigningDescription = new DerObjectIdentifier(Pkcs9 + ".13");
+ public static readonly DerObjectIdentifier Pkcs9AtExtensionRequest = new DerObjectIdentifier(Pkcs9 + ".14");
+ public static readonly DerObjectIdentifier Pkcs9AtSmimeCapabilities = new DerObjectIdentifier(Pkcs9 + ".15");
+ public static readonly DerObjectIdentifier Pkcs9AtFriendlyName = new DerObjectIdentifier(Pkcs9 + ".20");
+ public static readonly DerObjectIdentifier Pkcs9AtLocalKeyID = new DerObjectIdentifier(Pkcs9 + ".21");
+
+ [Obsolete("Use X509Certificate instead")]
+ public static readonly DerObjectIdentifier X509CertType = new DerObjectIdentifier(Pkcs9 + ".22.1");
+
+ public const string CertTypes = Pkcs9 + ".22";
+ public static readonly DerObjectIdentifier X509Certificate = new DerObjectIdentifier(CertTypes + ".1");
+ public static readonly DerObjectIdentifier SdsiCertificate = new DerObjectIdentifier(CertTypes + ".2");
+
+ public const string CrlTypes = Pkcs9 + ".23";
+ public static readonly DerObjectIdentifier X509Crl = new DerObjectIdentifier(CrlTypes + ".1");
+
+ public static readonly DerObjectIdentifier IdAlgPwriKek = new DerObjectIdentifier(Pkcs9 + ".16.3.9");
+
+ //
+ // SMIME capability sub oids.
+ //
+ public static readonly DerObjectIdentifier PreferSignedData = new DerObjectIdentifier(Pkcs9 + ".15.1");
+ public static readonly DerObjectIdentifier CannotDecryptAny = new DerObjectIdentifier(Pkcs9 + ".15.2");
+ public static readonly DerObjectIdentifier SmimeCapabilitiesVersions = new DerObjectIdentifier(Pkcs9 + ".15.3");
+
+ //
+ // other SMIME attributes
+ //
+ public static readonly DerObjectIdentifier IdAAReceiptRequest = new DerObjectIdentifier(Pkcs9 + ".16.2.1");
+
+ //
+ // id-ct OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840)
+ // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) ct(1)}
+ //
+ public const string IdCT = "1.2.840.113549.1.9.16.1";
+
+ public static readonly DerObjectIdentifier IdCTAuthData = new DerObjectIdentifier(IdCT + ".2");
+ public static readonly DerObjectIdentifier IdCTTstInfo = new DerObjectIdentifier(IdCT + ".4");
+ public static readonly DerObjectIdentifier IdCTCompressedData = new DerObjectIdentifier(IdCT + ".9");
+ public static readonly DerObjectIdentifier IdCTAuthEnvelopedData = new DerObjectIdentifier(IdCT + ".23");
+ public static readonly DerObjectIdentifier IdCTTimestampedData = new DerObjectIdentifier(IdCT + ".31");
+
+ //
+ // id-cti OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840)
+ // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) cti(6)}
+ //
+ public const string IdCti = "1.2.840.113549.1.9.16.6";
+
+ public static readonly DerObjectIdentifier IdCtiEtsProofOfOrigin = new DerObjectIdentifier(IdCti + ".1");
+ public static readonly DerObjectIdentifier IdCtiEtsProofOfReceipt = new DerObjectIdentifier(IdCti + ".2");
+ public static readonly DerObjectIdentifier IdCtiEtsProofOfDelivery = new DerObjectIdentifier(IdCti + ".3");
+ public static readonly DerObjectIdentifier IdCtiEtsProofOfSender = new DerObjectIdentifier(IdCti + ".4");
+ public static readonly DerObjectIdentifier IdCtiEtsProofOfApproval = new DerObjectIdentifier(IdCti + ".5");
+ public static readonly DerObjectIdentifier IdCtiEtsProofOfCreation = new DerObjectIdentifier(IdCti + ".6");
+
+ //
+ // id-aa OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840)
+ // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) attributes(2)}
+ //
+ public const string IdAA = "1.2.840.113549.1.9.16.2";
+
+ public static readonly DerObjectIdentifier IdAAContentHint = new DerObjectIdentifier(IdAA + ".4"); // See RFC 2634
+ public static readonly DerObjectIdentifier IdAAMsgSigDigest = new DerObjectIdentifier(IdAA + ".5");
+ public static readonly DerObjectIdentifier IdAAContentReference = new DerObjectIdentifier(IdAA + ".10");
+
+ /*
+ * id-aa-encrypKeyPref OBJECT IDENTIFIER ::= {id-aa 11}
+ *
+ */
+ public static readonly DerObjectIdentifier IdAAEncrypKeyPref = new DerObjectIdentifier(IdAA + ".11");
+ public static readonly DerObjectIdentifier IdAASigningCertificate = new DerObjectIdentifier(IdAA + ".12");
+ public static readonly DerObjectIdentifier IdAASigningCertificateV2 = new DerObjectIdentifier(IdAA + ".47");
+
+ public static readonly DerObjectIdentifier IdAAContentIdentifier = new DerObjectIdentifier(IdAA + ".7"); // See RFC 2634
+
+ /*
+ * RFC 3126
+ */
+ public static readonly DerObjectIdentifier IdAASignatureTimeStampToken = new DerObjectIdentifier(IdAA + ".14");
+
+ public static readonly DerObjectIdentifier IdAAEtsSigPolicyID = new DerObjectIdentifier(IdAA + ".15");
+ public static readonly DerObjectIdentifier IdAAEtsCommitmentType = new DerObjectIdentifier(IdAA + ".16");
+ public static readonly DerObjectIdentifier IdAAEtsSignerLocation = new DerObjectIdentifier(IdAA + ".17");
+ public static readonly DerObjectIdentifier IdAAEtsSignerAttr = new DerObjectIdentifier(IdAA + ".18");
+ public static readonly DerObjectIdentifier IdAAEtsOtherSigCert = new DerObjectIdentifier(IdAA + ".19");
+ public static readonly DerObjectIdentifier IdAAEtsContentTimestamp = new DerObjectIdentifier(IdAA + ".20");
+ public static readonly DerObjectIdentifier IdAAEtsCertificateRefs = new DerObjectIdentifier(IdAA + ".21");
+ public static readonly DerObjectIdentifier IdAAEtsRevocationRefs = new DerObjectIdentifier(IdAA + ".22");
+ public static readonly DerObjectIdentifier IdAAEtsCertValues = new DerObjectIdentifier(IdAA + ".23");
+ public static readonly DerObjectIdentifier IdAAEtsRevocationValues = new DerObjectIdentifier(IdAA + ".24");
+ public static readonly DerObjectIdentifier IdAAEtsEscTimeStamp = new DerObjectIdentifier(IdAA + ".25");
+ public static readonly DerObjectIdentifier IdAAEtsCertCrlTimestamp = new DerObjectIdentifier(IdAA + ".26");
+ public static readonly DerObjectIdentifier IdAAEtsArchiveTimestamp = new DerObjectIdentifier(IdAA + ".27");
+
+ [Obsolete("Use 'IdAAEtsSigPolicyID' instead")]
+ public static readonly DerObjectIdentifier IdAASigPolicyID = IdAAEtsSigPolicyID;
+ [Obsolete("Use 'IdAAEtsCommitmentType' instead")]
+ public static readonly DerObjectIdentifier IdAACommitmentType = IdAAEtsCommitmentType;
+ [Obsolete("Use 'IdAAEtsSignerLocation' instead")]
+ public static readonly DerObjectIdentifier IdAASignerLocation = IdAAEtsSignerLocation;
+ [Obsolete("Use 'IdAAEtsOtherSigCert' instead")]
+ public static readonly DerObjectIdentifier IdAAOtherSigCert = IdAAEtsOtherSigCert;
+
+ //
+ // id-spq OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840)
+ // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) id-spq(5)}
+ //
+ public const string IdSpq = "1.2.840.113549.1.9.16.5";
+
+ public static readonly DerObjectIdentifier IdSpqEtsUri = new DerObjectIdentifier(IdSpq + ".1");
+ public static readonly DerObjectIdentifier IdSpqEtsUNotice = new DerObjectIdentifier(IdSpq + ".2");
+
+ //
+ // pkcs-12 OBJECT IDENTIFIER ::= {
+ // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 12 }
+ //
+ public const string Pkcs12 = "1.2.840.113549.1.12";
+ public const string BagTypes = Pkcs12 + ".10.1";
+
+ public static readonly DerObjectIdentifier KeyBag = new DerObjectIdentifier(BagTypes + ".1");
+ public static readonly DerObjectIdentifier Pkcs8ShroudedKeyBag = new DerObjectIdentifier(BagTypes + ".2");
+ public static readonly DerObjectIdentifier CertBag = new DerObjectIdentifier(BagTypes + ".3");
+ public static readonly DerObjectIdentifier CrlBag = new DerObjectIdentifier(BagTypes + ".4");
+ public static readonly DerObjectIdentifier SecretBag = new DerObjectIdentifier(BagTypes + ".5");
+ public static readonly DerObjectIdentifier SafeContentsBag = new DerObjectIdentifier(BagTypes + ".6");
+
+ public const string Pkcs12PbeIds = Pkcs12 + ".1";
+
+ public static readonly DerObjectIdentifier PbeWithShaAnd128BitRC4 = new DerObjectIdentifier(Pkcs12PbeIds + ".1");
+ public static readonly DerObjectIdentifier PbeWithShaAnd40BitRC4 = new DerObjectIdentifier(Pkcs12PbeIds + ".2");
+ public static readonly DerObjectIdentifier PbeWithShaAnd3KeyTripleDesCbc = new DerObjectIdentifier(Pkcs12PbeIds + ".3");
+ public static readonly DerObjectIdentifier PbeWithShaAnd2KeyTripleDesCbc = new DerObjectIdentifier(Pkcs12PbeIds + ".4");
+ public static readonly DerObjectIdentifier PbeWithShaAnd128BitRC2Cbc = new DerObjectIdentifier(Pkcs12PbeIds + ".5");
+ public static readonly DerObjectIdentifier PbewithShaAnd40BitRC2Cbc = new DerObjectIdentifier(Pkcs12PbeIds + ".6");
+
+ public static readonly DerObjectIdentifier IdAlgCms3DesWrap = new DerObjectIdentifier("1.2.840.113549.1.9.16.3.6");
+ public static readonly DerObjectIdentifier IdAlgCmsRC2Wrap = new DerObjectIdentifier("1.2.840.113549.1.9.16.3.7");
+ }
+}
diff --git a/Crypto/src/asn1/pkcs/Pfx.cs b/Crypto/src/asn1/pkcs/Pfx.cs
new file mode 100644
index 000000000..9676f64fc
--- /dev/null
+++ b/Crypto/src/asn1/pkcs/Pfx.cs
@@ -0,0 +1,65 @@
+using System;
+
+using Org.BouncyCastle.Asn1;
+using Org.BouncyCastle.Math;
+
+namespace Org.BouncyCastle.Asn1.Pkcs
+{
+ /**
+ * the infamous Pfx from Pkcs12
+ */
+ public class Pfx
+ : Asn1Encodable
+ {
+ private ContentInfo contentInfo;
+ private MacData macData;
+
+ public Pfx(
+ Asn1Sequence seq)
+ {
+ BigInteger version = ((DerInteger) seq[0]).Value;
+ if (version.IntValue != 3)
+ {
+ throw new ArgumentException("wrong version for PFX PDU");
+ }
+
+ contentInfo = ContentInfo.GetInstance(seq[1]);
+
+ if (seq.Count == 3)
+ {
+ macData = MacData.GetInstance(seq[2]);
+ }
+ }
+
+ public Pfx(
+ ContentInfo contentInfo,
+ MacData macData)
+ {
+ this.contentInfo = contentInfo;
+ this.macData = macData;
+ }
+
+ public ContentInfo AuthSafe
+ {
+ get { return contentInfo; }
+ }
+
+ public MacData MacData
+ {
+ get { return macData; }
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(
+ new DerInteger(3), contentInfo);
+
+ if (macData != null)
+ {
+ v.Add(macData);
+ }
+
+ return new BerSequence(v);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/pkcs/PrivateKeyInfo.cs b/Crypto/src/asn1/pkcs/PrivateKeyInfo.cs
new file mode 100644
index 000000000..bd0ef7d1e
--- /dev/null
+++ b/Crypto/src/asn1/pkcs/PrivateKeyInfo.cs
@@ -0,0 +1,126 @@
+using System;
+using System.Collections;
+using System.IO;
+
+using Org.BouncyCastle.Asn1.X509;
+using Org.BouncyCastle.Math;
+
+namespace Org.BouncyCastle.Asn1.Pkcs
+{
+ public class PrivateKeyInfo
+ : Asn1Encodable
+ {
+ private readonly Asn1Object privKey;
+ private readonly AlgorithmIdentifier algID;
+ private readonly Asn1Set attributes;
+
+ public static PrivateKeyInfo GetInstance(
+ object obj)
+ {
+ if (obj is PrivateKeyInfo)
+ return (PrivateKeyInfo) obj;
+
+ if (obj != null)
+ return new PrivateKeyInfo(Asn1Sequence.GetInstance(obj));
+
+ return null;
+ }
+
+ public PrivateKeyInfo(
+ AlgorithmIdentifier algID,
+ Asn1Object privateKey)
+ : this(algID, privateKey, null)
+ {
+ }
+
+ public PrivateKeyInfo(
+ AlgorithmIdentifier algID,
+ Asn1Object privateKey,
+ Asn1Set attributes)
+ {
+ this.privKey = privateKey;
+ this.algID = algID;
+ this.attributes = attributes;
+ }
+
+ private PrivateKeyInfo(
+ Asn1Sequence seq)
+ {
+ IEnumerator e = seq.GetEnumerator();
+
+ e.MoveNext();
+ BigInteger version = ((DerInteger) e.Current).Value;
+ if (version.IntValue != 0)
+ {
+ throw new ArgumentException("wrong version for private key info");
+ }
+
+ e.MoveNext();
+ algID = AlgorithmIdentifier.GetInstance(e.Current);
+
+ try
+ {
+ e.MoveNext();
+ Asn1OctetString data = (Asn1OctetString) e.Current;
+
+ privKey = Asn1Object.FromByteArray(data.GetOctets());
+ }
+ catch (IOException)
+ {
+ throw new ArgumentException("Error recoverying private key from sequence");
+ }
+
+ if (e.MoveNext())
+ {
+ attributes = Asn1Set.GetInstance((Asn1TaggedObject) e.Current, false);
+ }
+ }
+
+ public AlgorithmIdentifier AlgorithmID
+ {
+ get { return algID; }
+ }
+
+ public Asn1Object PrivateKey
+ {
+ get { return privKey; }
+ }
+
+ public Asn1Set Attributes
+ {
+ get { return attributes; }
+ }
+
+ /**
+ * write out an RSA private key with its associated information
+ * as described in Pkcs8.
+ *
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(hashAlgorithm, new DerOctetString(hashedMessage));
+ }
+ }
+}
diff --git a/Crypto/src/asn1/tsp/TSTInfo.cs b/Crypto/src/asn1/tsp/TSTInfo.cs
new file mode 100644
index 000000000..61d5399c7
--- /dev/null
+++ b/Crypto/src/asn1/tsp/TSTInfo.cs
@@ -0,0 +1,249 @@
+using System;
+using System.Collections;
+using System.IO;
+
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.Tsp
+{
+ public class TstInfo
+ : Asn1Encodable
+ {
+ private readonly DerInteger version;
+ private readonly DerObjectIdentifier tsaPolicyId;
+ private readonly MessageImprint messageImprint;
+ private readonly DerInteger serialNumber;
+ private readonly DerGeneralizedTime genTime;
+ private readonly Accuracy accuracy;
+ private readonly DerBoolean ordering;
+ private readonly DerInteger nonce;
+ private readonly GeneralName tsa;
+ private readonly X509Extensions extensions;
+
+ public static TstInfo GetInstance(
+ object o)
+ {
+ if (o == null || o is TstInfo)
+ {
+ return (TstInfo) o;
+ }
+
+ if (o is Asn1Sequence)
+ {
+ return new TstInfo((Asn1Sequence) o);
+ }
+
+ if (o is Asn1OctetString)
+ {
+ try
+ {
+ byte[] octets = ((Asn1OctetString)o).GetOctets();
+ return GetInstance(Asn1Object.FromByteArray(octets));
+ }
+ catch (IOException)
+ {
+ throw new ArgumentException(
+ "Bad object format in 'TstInfo' factory.");
+ }
+ }
+
+ throw new ArgumentException(
+ "Unknown object in 'TstInfo' factory: " + o.GetType().FullName);
+ }
+
+ private TstInfo(
+ Asn1Sequence seq)
+ {
+ IEnumerator e = seq.GetEnumerator();
+
+ // version
+ e.MoveNext();
+ version = DerInteger.GetInstance(e.Current);
+
+ // tsaPolicy
+ e.MoveNext();
+ tsaPolicyId = DerObjectIdentifier.GetInstance(e.Current);
+
+ // messageImprint
+ e.MoveNext();
+ messageImprint = MessageImprint.GetInstance(e.Current);
+
+ // serialNumber
+ e.MoveNext();
+ serialNumber = DerInteger.GetInstance(e.Current);
+
+ // genTime
+ e.MoveNext();
+ genTime = DerGeneralizedTime.GetInstance(e.Current);
+
+ // default for ordering
+ ordering = DerBoolean.False;
+
+ while (e.MoveNext())
+ {
+ Asn1Object o = (Asn1Object) e.Current;
+
+ if (o is Asn1TaggedObject)
+ {
+ DerTaggedObject tagged = (DerTaggedObject) o;
+
+ switch (tagged.TagNo)
+ {
+ case 0:
+ tsa = GeneralName.GetInstance(tagged, true);
+ break;
+ case 1:
+ extensions = X509Extensions.GetInstance(tagged, false);
+ break;
+ default:
+ throw new ArgumentException("Unknown tag value " + tagged.TagNo);
+ }
+ }
+
+ if (o is DerSequence)
+ {
+ accuracy = Accuracy.GetInstance(o);
+ }
+
+ if (o is DerBoolean)
+ {
+ ordering = DerBoolean.GetInstance(o);
+ }
+
+ if (o is DerInteger)
+ {
+ nonce = DerInteger.GetInstance(o);
+ }
+ }
+ }
+
+ public TstInfo(
+ DerObjectIdentifier tsaPolicyId,
+ MessageImprint messageImprint,
+ DerInteger serialNumber,
+ DerGeneralizedTime genTime,
+ Accuracy accuracy,
+ DerBoolean ordering,
+ DerInteger nonce,
+ GeneralName tsa,
+ X509Extensions extensions)
+ {
+ this.version = new DerInteger(1);
+ this.tsaPolicyId = tsaPolicyId;
+ this.messageImprint = messageImprint;
+ this.serialNumber = serialNumber;
+ this.genTime = genTime;
+ this.accuracy = accuracy;
+ this.ordering = ordering;
+ this.nonce = nonce;
+ this.tsa = tsa;
+ this.extensions = extensions;
+ }
+
+ public DerInteger Version
+ {
+ get { return version; }
+ }
+
+ public MessageImprint MessageImprint
+ {
+ get { return messageImprint; }
+ }
+
+ public DerObjectIdentifier Policy
+ {
+ get { return tsaPolicyId; }
+ }
+
+ public DerInteger SerialNumber
+ {
+ get { return serialNumber; }
+ }
+
+ public Accuracy Accuracy
+ {
+ get { return accuracy; }
+ }
+
+ public DerGeneralizedTime GenTime
+ {
+ get { return genTime; }
+ }
+
+ public DerBoolean Ordering
+ {
+ get { return ordering; }
+ }
+
+ public DerInteger Nonce
+ {
+ get { return nonce; }
+ }
+
+ public GeneralName Tsa
+ {
+ get { return tsa; }
+ }
+
+ public X509Extensions Extensions
+ {
+ get { return extensions; }
+ }
+
+ /**
+ *
+ *
+ * TstInfo ::= SEQUENCE {
+ * version INTEGER { v1(1) },
+ * policy TSAPolicyId,
+ * messageImprint MessageImprint,
+ * -- MUST have the same value as the similar field in
+ * -- TimeStampReq
+ * serialNumber INTEGER,
+ * -- Time-Stamping users MUST be ready to accommodate integers
+ * -- up to 160 bits.
+ * genTime GeneralizedTime,
+ * accuracy Accuracy OPTIONAL,
+ * ordering BOOLEAN DEFAULT FALSE,
+ * nonce INTEGER OPTIONAL,
+ * -- MUST be present if the similar field was present
+ * -- in TimeStampReq. In that case it MUST have the same value.
+ * tsa [0] GeneralName OPTIONAL,
+ * extensions [1] IMPLICIT Extensions OPTIONAL }
+ *
+ *
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(
+ version, tsaPolicyId, messageImprint, serialNumber, genTime);
+
+ if (accuracy != null)
+ {
+ v.Add(accuracy);
+ }
+
+ if (ordering != null && ordering.IsTrue)
+ {
+ v.Add(ordering);
+ }
+
+ if (nonce != null)
+ {
+ v.Add(nonce);
+ }
+
+ if (tsa != null)
+ {
+ v.Add(new DerTaggedObject(true, 0, tsa));
+ }
+
+ if (extensions != null)
+ {
+ v.Add(new DerTaggedObject(false, 1, extensions));
+ }
+
+ return new DerSequence(v);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/tsp/TimeStampReq.cs b/Crypto/src/asn1/tsp/TimeStampReq.cs
new file mode 100644
index 000000000..55e973e76
--- /dev/null
+++ b/Crypto/src/asn1/tsp/TimeStampReq.cs
@@ -0,0 +1,164 @@
+using System;
+
+using Org.BouncyCastle.Asn1.X509;
+
+namespace Org.BouncyCastle.Asn1.Tsp
+{
+ public class TimeStampReq
+ : Asn1Encodable
+ {
+ private readonly DerInteger version;
+ private readonly MessageImprint messageImprint;
+ private readonly DerObjectIdentifier tsaPolicy;
+ private readonly DerInteger nonce;
+ private readonly DerBoolean certReq;
+ private readonly X509Extensions extensions;
+
+ public static TimeStampReq GetInstance(
+ object o)
+ {
+ if (o == null || o is TimeStampReq)
+ {
+ return (TimeStampReq) o;
+ }
+
+ if (o is Asn1Sequence)
+ {
+ return new TimeStampReq((Asn1Sequence) o);
+ }
+
+ throw new ArgumentException(
+ "Unknown object in 'TimeStampReq' factory: " + o.GetType().FullName);
+ }
+
+ private TimeStampReq(
+ Asn1Sequence seq)
+ {
+ int nbObjects = seq.Count;
+ int seqStart = 0;
+
+ // version
+ version = DerInteger.GetInstance(seq[seqStart++]);
+
+ // messageImprint
+ messageImprint = MessageImprint.GetInstance(seq[seqStart++]);
+
+ for (int opt = seqStart; opt < nbObjects; opt++)
+ {
+ // tsaPolicy
+ if (seq[opt] is DerObjectIdentifier)
+ {
+ tsaPolicy = DerObjectIdentifier.GetInstance(seq[opt]);
+ }
+ // nonce
+ else if (seq[opt] is DerInteger)
+ {
+ nonce = DerInteger.GetInstance(seq[opt]);
+ }
+ // certReq
+ else if (seq[opt] is DerBoolean)
+ {
+ certReq = DerBoolean.GetInstance(seq[opt]);
+ }
+ // extensions
+ else if (seq[opt] is Asn1TaggedObject)
+ {
+ Asn1TaggedObject tagged = (Asn1TaggedObject) seq[opt];
+ if (tagged.TagNo == 0)
+ {
+ extensions = X509Extensions.GetInstance(tagged, false);
+ }
+ }
+ }
+ }
+
+ public TimeStampReq(
+ MessageImprint messageImprint,
+ DerObjectIdentifier tsaPolicy,
+ DerInteger nonce,
+ DerBoolean certReq,
+ X509Extensions extensions)
+ {
+ // default
+ this.version = new DerInteger(1);
+
+ this.messageImprint = messageImprint;
+ this.tsaPolicy = tsaPolicy;
+ this.nonce = nonce;
+ this.certReq = certReq;
+ this.extensions = extensions;
+ }
+
+ public DerInteger Version
+ {
+ get { return version; }
+ }
+
+ public MessageImprint MessageImprint
+ {
+ get { return messageImprint; }
+ }
+
+ public DerObjectIdentifier ReqPolicy
+ {
+ get { return tsaPolicy; }
+ }
+
+ public DerInteger Nonce
+ {
+ get { return nonce; }
+ }
+
+ public DerBoolean CertReq
+ {
+ get { return certReq; }
+ }
+
+ public X509Extensions Extensions
+ {
+ get { return extensions; }
+ }
+
+ /**
+ *
+ * TimeStampReq ::= SEQUENCE {
+ * version INTEGER { v1(1) },
+ * messageImprint MessageImprint,
+ * --a hash algorithm OID and the hash value of the data to be
+ * --time-stamped
+ * reqPolicy TSAPolicyId OPTIONAL,
+ * nonce INTEGER OPTIONAL,
+ * certReq BOOLEAN DEFAULT FALSE,
+ * extensions [0] IMPLICIT Extensions OPTIONAL
+ * }
+ *
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(
+ version, messageImprint);
+
+ if (tsaPolicy != null)
+ {
+ v.Add(tsaPolicy);
+ }
+
+ if (nonce != null)
+ {
+ v.Add(nonce);
+ }
+
+ if (certReq != null && certReq.IsTrue)
+ {
+ v.Add(certReq);
+ }
+
+ if (extensions != null)
+ {
+ v.Add(new DerTaggedObject(false, 0, extensions));
+ }
+
+ return new DerSequence(v);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/tsp/TimeStampResp.cs b/Crypto/src/asn1/tsp/TimeStampResp.cs
new file mode 100644
index 000000000..f26fb30bd
--- /dev/null
+++ b/Crypto/src/asn1/tsp/TimeStampResp.cs
@@ -0,0 +1,80 @@
+using System;
+using System.Collections;
+
+using Org.BouncyCastle.Asn1.Cmp;
+using Org.BouncyCastle.Asn1.Cms;
+
+namespace Org.BouncyCastle.Asn1.Tsp
+{
+ public class TimeStampResp
+ : Asn1Encodable
+ {
+ private readonly PkiStatusInfo pkiStatusInfo;
+ private readonly ContentInfo timeStampToken;
+
+ public static TimeStampResp GetInstance(
+ object o)
+ {
+ if (o == null || o is TimeStampResp)
+ {
+ return (TimeStampResp) o;
+ }
+
+ if (o is Asn1Sequence)
+ {
+ return new TimeStampResp((Asn1Sequence) o);
+ }
+
+ throw new ArgumentException(
+ "Unknown object in 'TimeStampResp' factory: " + o.GetType().FullName);
+ }
+
+ private TimeStampResp(
+ Asn1Sequence seq)
+ {
+ this.pkiStatusInfo = PkiStatusInfo.GetInstance(seq[0]);
+
+ if (seq.Count > 1)
+ {
+ this.timeStampToken = ContentInfo.GetInstance(seq[1]);
+ }
+ }
+
+ public TimeStampResp(
+ PkiStatusInfo pkiStatusInfo,
+ ContentInfo timeStampToken)
+ {
+ this.pkiStatusInfo = pkiStatusInfo;
+ this.timeStampToken = timeStampToken;
+ }
+
+ public PkiStatusInfo Status
+ {
+ get { return pkiStatusInfo; }
+ }
+
+ public ContentInfo TimeStampToken
+ {
+ get { return timeStampToken; }
+ }
+
+ /**
+ *
The forward elements of the crossCertificatePair attribute of a
+ * CA's directory entry shall be used to store all, except self-issued
+ * certificates issued to this CA. Optionally, the reverse elements of the
+ * crossCertificatePair attribute, of a CA's directory entry may contain a
+ * subset of certificates issued by this CA to other CAs. When both the forward
+ * and the reverse elements are present in a single attribute value, issuer name
+ * in one certificate shall match the subject name in the other and vice versa,
+ * and the subject public key in one certificate shall be capable of verifying
+ * the digital signature on the other certificate and vice versa.
+ *
+ * When a reverse element is present, the forward element value and the reverse
+ * element value need not be stored in the same attribute value; in other words,
+ * they can be stored in either a single attribute value or two attribute
+ * values.
+ *
+ *
+ * CertificatePair ::= SEQUENCE {
+ * forward [0] Certificate OPTIONAL,
+ * reverse [1] Certificate OPTIONAL,
+ * -- at least one of the pair shall be present -- }
+ *
+ */
+ public class CertificatePair
+ : Asn1Encodable
+ {
+ private X509CertificateStructure forward, reverse;
+
+ public static CertificatePair GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is CertificatePair)
+ {
+ return (CertificatePair) obj;
+ }
+
+ if (obj is Asn1Sequence)
+ {
+ return new CertificatePair((Asn1Sequence) obj);
+ }
+
+ throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj");
+ }
+
+ /**
+ * Constructor from Asn1Sequence.
+ *
+ * The sequence is of type CertificatePair:
+ *
+ *
+ * CertificatePair ::= SEQUENCE {
+ * forward [0] Certificate OPTIONAL,
+ * reverse [1] Certificate OPTIONAL,
+ * -- at least one of the pair shall be present -- }
+ *
+ *
+ * @param seq The ASN.1 sequence.
+ */
+ private CertificatePair(
+ Asn1Sequence seq)
+ {
+ if (seq.Count != 1 && seq.Count != 2)
+ {
+ throw new ArgumentException("Bad sequence size: " + seq.Count, "seq");
+ }
+
+ foreach (object obj in seq)
+ {
+ Asn1TaggedObject o = Asn1TaggedObject.GetInstance(obj);
+ if (o.TagNo == 0)
+ {
+ forward = X509CertificateStructure.GetInstance(o, true);
+ }
+ else if (o.TagNo == 1)
+ {
+ reverse = X509CertificateStructure.GetInstance(o, true);
+ }
+ else
+ {
+ throw new ArgumentException("Bad tag number: " + o.TagNo);
+ }
+ }
+ }
+
+ /**
+ * Constructor from a given details.
+ *
+ * @param forward Certificates issued to this CA.
+ * @param reverse Certificates issued by this CA to other CAs.
+ */
+ public CertificatePair(
+ X509CertificateStructure forward,
+ X509CertificateStructure reverse)
+ {
+ this.forward = forward;
+ this.reverse = reverse;
+ }
+
+ /**
+ * Produce an object suitable for an Asn1OutputStream.
+ *
+ * Returns:
+ *
+ *
+ * CertificatePair ::= SEQUENCE {
+ * forward [0] Certificate OPTIONAL,
+ * reverse [1] Certificate OPTIONAL,
+ * -- at least one of the pair shall be present -- }
+ *
+ *
+ * @return a DERObject
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector vec = new Asn1EncodableVector();
+
+ if (forward != null)
+ {
+ vec.Add(new DerTaggedObject(0, forward));
+ }
+
+ if (reverse != null)
+ {
+ vec.Add(new DerTaggedObject(1, reverse));
+ }
+
+ return new DerSequence(vec);
+ }
+
+ /**
+ * @return Returns the forward.
+ */
+ public X509CertificateStructure Forward
+ {
+ get { return forward; }
+ }
+
+ /**
+ * @return Returns the reverse.
+ */
+ public X509CertificateStructure Reverse
+ {
+ get { return reverse; }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/x509/DSAParameter.cs b/Crypto/src/asn1/x509/DSAParameter.cs
new file mode 100644
index 000000000..b2b325f4d
--- /dev/null
+++ b/Crypto/src/asn1/x509/DSAParameter.cs
@@ -0,0 +1,77 @@
+using System;
+using System.Collections;
+
+using Org.BouncyCastle.Math;
+
+namespace Org.BouncyCastle.Asn1.X509
+{
+ public class DsaParameter
+ : Asn1Encodable
+ {
+ internal readonly DerInteger p, q, g;
+
+ public static DsaParameter GetInstance(
+ Asn1TaggedObject obj,
+ bool explicitly)
+ {
+ return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
+ }
+
+ public static DsaParameter GetInstance(
+ object obj)
+ {
+ if(obj == null || obj is DsaParameter)
+ {
+ return (DsaParameter) obj;
+ }
+
+ if(obj is Asn1Sequence)
+ {
+ return new DsaParameter((Asn1Sequence) obj);
+ }
+
+ throw new ArgumentException("Invalid DsaParameter: " + obj.GetType().Name);
+ }
+
+ public DsaParameter(
+ BigInteger p,
+ BigInteger q,
+ BigInteger g)
+ {
+ this.p = new DerInteger(p);
+ this.q = new DerInteger(q);
+ this.g = new DerInteger(g);
+ }
+
+ private DsaParameter(
+ Asn1Sequence seq)
+ {
+ if (seq.Count != 3)
+ throw new ArgumentException("Bad sequence size: " + seq.Count, "seq");
+
+ this.p = DerInteger.GetInstance(seq[0]);
+ this.q = DerInteger.GetInstance(seq[1]);
+ this.g = DerInteger.GetInstance(seq[2]);
+ }
+
+ public BigInteger P
+ {
+ get { return p.PositiveValue; }
+ }
+
+ public BigInteger Q
+ {
+ get { return q.PositiveValue; }
+ }
+
+ public BigInteger G
+ {
+ get { return g.PositiveValue; }
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerSequence(p, q, g);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/x509/DigestInfo.cs b/Crypto/src/asn1/x509/DigestInfo.cs
new file mode 100644
index 000000000..1dec227fa
--- /dev/null
+++ b/Crypto/src/asn1/x509/DigestInfo.cs
@@ -0,0 +1,76 @@
+using System;
+using System.Collections;
+
+namespace Org.BouncyCastle.Asn1.X509
+{
+ /**
+ * The DigestInfo object.
+ *
+ */
+ public class GeneralName
+ : Asn1Encodable, IAsn1Choice
+ {
+ public const int OtherName = 0;
+ public const int Rfc822Name = 1;
+ public const int DnsName = 2;
+ public const int X400Address = 3;
+ public const int DirectoryName = 4;
+ public const int EdiPartyName = 5;
+ public const int UniformResourceIdentifier = 6;
+ public const int IPAddress = 7;
+ public const int RegisteredID = 8;
+
+ internal readonly Asn1Encodable obj;
+ internal readonly int tag;
+
+ public GeneralName(
+ X509Name directoryName)
+ {
+ this.obj = directoryName;
+ this.tag = 4;
+ }
+
+ /**
+ * When the subjectAltName extension contains an Internet mail address,
+ * the address MUST be included as an rfc822Name. The format of an
+ * rfc822Name is an "addr-spec" as defined in RFC 822 [RFC 822].
+ *
+ * When the subjectAltName extension contains a domain name service
+ * label, the domain name MUST be stored in the dNSName (an IA5String).
+ * The name MUST be in the "preferred name syntax," as specified by RFC
+ * 1034 [RFC 1034].
+ *
+ * When the subjectAltName extension contains a URI, the name MUST be
+ * stored in the uniformResourceIdentifier (an IA5String). The name MUST
+ * be a non-relative URL, and MUST follow the URL syntax and encoding
+ * rules specified in [RFC 1738]. The name must include both a scheme
+ * (e.g., "http" or "ftp") and a scheme-specific-part. The scheme-
+ * specific-part must include a fully qualified domain name or IP
+ * address as the host.
+ *
+ * When the subjectAltName extension contains a iPAddress, the address
+ * MUST be stored in the octet string in "network byte order," as
+ * specified in RFC 791 [RFC 791]. The least significant bit (LSB) of
+ * each octet is the LSB of the corresponding byte in the network
+ * address. For IP Version 4, as specified in RFC 791, the octet string
+ * MUST contain exactly four octets. For IP Version 6, as specified in
+ * RFC 1883, the octet string MUST contain exactly sixteen octets [RFC
+ * 1883].
+ */
+ public GeneralName(
+ Asn1Object name,
+ int tag)
+ {
+ this.obj = name;
+ this.tag = tag;
+ }
+
+ public GeneralName(
+ int tag,
+ Asn1Encodable name)
+ {
+ this.obj = name;
+ this.tag = tag;
+ }
+
+ /**
+ * Create a GeneralName for the given tag from the passed in string.
+ *
+ * This constructor can handle:
+ *
+ *
rfc822Name
+ *
iPAddress
+ *
directoryName
+ *
dNSName
+ *
uniformResourceIdentifier
+ *
registeredID
+ *
+ * For x400Address, otherName and ediPartyName there is no common string
+ * format defined.
+ *
+ * Note: A directory name can be encoded in different ways into a byte
+ * representation. Be aware of this if the byte representation is used for
+ * comparing results.
+ *
+ *
+ * @param tag tag number
+ * @param name string representation of name
+ * @throws ArgumentException if the string encoding is not correct or
+ * not supported.
+ */
+ public GeneralName(
+ int tag,
+ string name)
+ {
+ this.tag = tag;
+
+ if (tag == Rfc822Name || tag == DnsName || tag == UniformResourceIdentifier)
+ {
+ this.obj = new DerIA5String(name);
+ }
+ else if (tag == RegisteredID)
+ {
+ this.obj = new DerObjectIdentifier(name);
+ }
+ else if (tag == DirectoryName)
+ {
+ this.obj = new X509Name(name);
+ }
+ else if (tag == IPAddress)
+ {
+ byte[] enc = toGeneralNameEncoding(name);
+ if (enc == null)
+ throw new ArgumentException("IP Address is invalid", "name");
+
+ this.obj = new DerOctetString(enc);
+ }
+ else
+ {
+ throw new ArgumentException("can't process string for tag: " + tag, "tag");
+ }
+ }
+
+ public static GeneralName GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is GeneralName)
+ {
+ return (GeneralName) obj;
+ }
+
+ if (obj is Asn1TaggedObject)
+ {
+ Asn1TaggedObject tagObj = (Asn1TaggedObject) obj;
+ int tag = tagObj.TagNo;
+
+ switch (tag)
+ {
+ case OtherName:
+ return new GeneralName(tag, Asn1Sequence.GetInstance(tagObj, false));
+ case Rfc822Name:
+ return new GeneralName(tag, DerIA5String.GetInstance(tagObj, false));
+ case DnsName:
+ return new GeneralName(tag, DerIA5String.GetInstance(tagObj, false));
+ case X400Address:
+ throw new ArgumentException("unknown tag: " + tag);
+ case DirectoryName:
+ return new GeneralName(tag, X509Name.GetInstance(tagObj, true));
+ case EdiPartyName:
+ return new GeneralName(tag, Asn1Sequence.GetInstance(tagObj, false));
+ case UniformResourceIdentifier:
+ return new GeneralName(tag, DerIA5String.GetInstance(tagObj, false));
+ case IPAddress:
+ return new GeneralName(tag, Asn1OctetString.GetInstance(tagObj, false));
+ case RegisteredID:
+ return new GeneralName(tag, DerObjectIdentifier.GetInstance(tagObj, false));
+ }
+ }
+
+ if (obj is byte[])
+ {
+ try
+ {
+ return GetInstance(Asn1Object.FromByteArray((byte[])obj));
+ }
+ catch (IOException)
+ {
+ throw new ArgumentException("unable to parse encoded general name");
+ }
+ }
+
+ throw new ArgumentException("unknown object in GetInstance: " + obj.GetType().FullName, "obj");
+ }
+
+ public static GeneralName GetInstance(
+ Asn1TaggedObject tagObj,
+ bool explicitly)
+ {
+ return GetInstance(Asn1TaggedObject.GetInstance(tagObj, true));
+ }
+
+ public int TagNo
+ {
+ get { return tag; }
+ }
+
+ public Asn1Encodable Name
+ {
+ get { return obj; }
+ }
+
+ public override string ToString()
+ {
+ StringBuilder buf = new StringBuilder();
+ buf.Append(tag);
+ buf.Append(": ");
+
+ switch (tag)
+ {
+ case Rfc822Name:
+ case DnsName:
+ case UniformResourceIdentifier:
+ buf.Append(DerIA5String.GetInstance(obj).GetString());
+ break;
+ case DirectoryName:
+ buf.Append(X509Name.GetInstance(obj).ToString());
+ break;
+ default:
+ buf.Append(obj.ToString());
+ break;
+ }
+
+ return buf.ToString();
+ }
+
+ private byte[] toGeneralNameEncoding(
+ string ip)
+ {
+ if (NetUtils.IPAddress.IsValidIPv6WithNetmask(ip) || NetUtils.IPAddress.IsValidIPv6(ip))
+ {
+ int slashIndex = ip.IndexOf('/');
+
+ if (slashIndex < 0)
+ {
+ byte[] addr = new byte[16];
+ int[] parsedIp = parseIPv6(ip);
+ copyInts(parsedIp, addr, 0);
+
+ return addr;
+ }
+ else
+ {
+ byte[] addr = new byte[32];
+ int[] parsedIp = parseIPv6(ip.Substring(0, slashIndex));
+ copyInts(parsedIp, addr, 0);
+ string mask = ip.Substring(slashIndex + 1);
+ if (mask.IndexOf(':') > 0)
+ {
+ parsedIp = parseIPv6(mask);
+ }
+ else
+ {
+ parsedIp = parseMask(mask);
+ }
+ copyInts(parsedIp, addr, 16);
+
+ return addr;
+ }
+ }
+ else if (NetUtils.IPAddress.IsValidIPv4WithNetmask(ip) || NetUtils.IPAddress.IsValidIPv4(ip))
+ {
+ int slashIndex = ip.IndexOf('/');
+
+ if (slashIndex < 0)
+ {
+ byte[] addr = new byte[4];
+
+ parseIPv4(ip, addr, 0);
+
+ return addr;
+ }
+ else
+ {
+ byte[] addr = new byte[8];
+
+ parseIPv4(ip.Substring(0, slashIndex), addr, 0);
+
+ string mask = ip.Substring(slashIndex + 1);
+ if (mask.IndexOf('.') > 0)
+ {
+ parseIPv4(mask, addr, 4);
+ }
+ else
+ {
+ parseIPv4Mask(mask, addr, 4);
+ }
+
+ return addr;
+ }
+ }
+
+ return null;
+ }
+
+ private void parseIPv4Mask(string mask, byte[] addr, int offset)
+ {
+ int maskVal = Int32.Parse(mask);
+
+ for (int i = 0; i != maskVal; i++)
+ {
+ addr[(i / 8) + offset] |= (byte)(1 << (i % 8));
+ }
+ }
+
+ private void parseIPv4(string ip, byte[] addr, int offset)
+ {
+ foreach (string token in ip.Split('.', '/'))
+ {
+ addr[offset++] = (byte)Int32.Parse(token);
+ }
+ }
+
+ private int[] parseMask(string mask)
+ {
+ int[] res = new int[8];
+ int maskVal = Int32.Parse(mask);
+
+ for (int i = 0; i != maskVal; i++)
+ {
+ res[i / 16] |= 1 << (i % 16);
+ }
+ return res;
+ }
+
+ private void copyInts(int[] parsedIp, byte[] addr, int offSet)
+ {
+ for (int i = 0; i != parsedIp.Length; i++)
+ {
+ addr[(i * 2) + offSet] = (byte)(parsedIp[i] >> 8);
+ addr[(i * 2 + 1) + offSet] = (byte)parsedIp[i];
+ }
+ }
+
+ private int[] parseIPv6(string ip)
+ {
+ if (ip.StartsWith("::"))
+ {
+ ip = ip.Substring(1);
+ }
+ else if (ip.EndsWith("::"))
+ {
+ ip = ip.Substring(0, ip.Length - 1);
+ }
+
+ IEnumerator sEnum = ip.Split(':').GetEnumerator();
+
+ int index = 0;
+ int[] val = new int[8];
+
+ int doubleColon = -1;
+
+ while (sEnum.MoveNext())
+ {
+ string e = (string) sEnum.Current;
+
+ if (e.Length == 0)
+ {
+ doubleColon = index;
+ val[index++] = 0;
+ }
+ else
+ {
+ if (e.IndexOf('.') < 0)
+ {
+ val[index++] = Int32.Parse(e, NumberStyles.AllowHexSpecifier);
+ }
+ else
+ {
+ string[] tokens = e.Split('.');
+
+ val[index++] = (Int32.Parse(tokens[0]) << 8) | Int32.Parse(tokens[1]);
+ val[index++] = (Int32.Parse(tokens[2]) << 8) | Int32.Parse(tokens[3]);
+ }
+ }
+ }
+
+ if (index != val.Length)
+ {
+ Array.Copy(val, doubleColon, val, val.Length - (index - doubleColon), index - doubleColon);
+ for (int i = doubleColon; i != val.Length - (index - doubleColon); i++)
+ {
+ val[i] = 0;
+ }
+ }
+
+ return val;
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ // Explicitly tagged if DirectoryName
+ return new DerTaggedObject(tag == DirectoryName, tag, obj);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/x509/GeneralNames.cs b/Crypto/src/asn1/x509/GeneralNames.cs
new file mode 100644
index 000000000..6c5c8e690
--- /dev/null
+++ b/Crypto/src/asn1/x509/GeneralNames.cs
@@ -0,0 +1,95 @@
+using System;
+using System.Text;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1.X509
+{
+ public class GeneralNames
+ : Asn1Encodable
+ {
+ private readonly GeneralName[] names;
+
+ public static GeneralNames GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is GeneralNames)
+ {
+ return (GeneralNames) obj;
+ }
+
+ if (obj is Asn1Sequence)
+ {
+ return new GeneralNames((Asn1Sequence) obj);
+ }
+
+ throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj");
+ }
+
+ public static GeneralNames GetInstance(
+ Asn1TaggedObject obj,
+ bool explicitly)
+ {
+ return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
+ }
+
+ /// Construct a GeneralNames object containing one GeneralName.
+ /// The name to be contained.
+ public GeneralNames(
+ GeneralName name)
+ {
+ names = new GeneralName[]{ name };
+ }
+
+ public GeneralNames(
+ GeneralName[] names)
+ {
+ this.names = (GeneralName[])names.Clone();
+ }
+
+ private GeneralNames(
+ Asn1Sequence seq)
+ {
+ this.names = new GeneralName[seq.Count];
+
+ for (int i = 0; i != seq.Count; i++)
+ {
+ names[i] = GeneralName.GetInstance(seq[i]);
+ }
+ }
+
+ public GeneralName[] GetNames()
+ {
+ return (GeneralName[]) names.Clone();
+ }
+
+ /**
+ * Produce an object suitable for an Asn1OutputStream.
+ *
+ *
+ * @return a DERObject
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector(baseName);
+
+ if (minimum != null && minimum.Value.SignValue != 0)
+ {
+ v.Add(new DerTaggedObject(false, 0, minimum));
+ }
+
+ if (maximum != null)
+ {
+ v.Add(new DerTaggedObject(false, 1, maximum));
+ }
+
+ return new DerSequence(v);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/x509/Holder.cs b/Crypto/src/asn1/x509/Holder.cs
new file mode 100644
index 000000000..d04f1cb60
--- /dev/null
+++ b/Crypto/src/asn1/x509/Holder.cs
@@ -0,0 +1,257 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.X509
+{
+ /**
+ * The Holder object.
+ *
+ * For an v2 attribute certificate this is:
+ *
+ *
+ * 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
+ * }
+ *
+ *
+ *
+ * For an v1 attribute certificate this is:
+ *
+ *
+ * subject CHOICE {
+ * baseCertificateID [0] IssuerSerial,
+ * -- associated with a Public Key Certificate
+ * subjectName [1] GeneralNames },
+ * -- associated with a name
+ *
+ *
+ */
+ public class Holder
+ : Asn1Encodable
+ {
+ internal readonly IssuerSerial baseCertificateID;
+ internal readonly GeneralNames entityName;
+ internal readonly ObjectDigestInfo objectDigestInfo;
+ private readonly int version;
+
+ public static Holder GetInstance(
+ object obj)
+ {
+ if (obj is Holder)
+ {
+ return (Holder) obj;
+ }
+
+ if (obj is Asn1Sequence)
+ {
+ return new Holder((Asn1Sequence) obj);
+ }
+
+ if (obj is Asn1TaggedObject)
+ {
+ return new Holder((Asn1TaggedObject) obj);
+ }
+
+ throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj");
+ }
+
+ /**
+ * Constructor for a holder for an v1 attribute certificate.
+ *
+ * @param tagObj The ASN.1 tagged holder object.
+ */
+ public Holder(
+ Asn1TaggedObject tagObj)
+ {
+ switch (tagObj.TagNo)
+ {
+ case 0:
+ baseCertificateID = IssuerSerial.GetInstance(tagObj, false);
+ break;
+ case 1:
+ entityName = GeneralNames.GetInstance(tagObj, false);
+ break;
+ default:
+ throw new ArgumentException("unknown tag in Holder");
+ }
+
+ this.version = 0;
+ }
+
+ /**
+ * Constructor for a holder for an v2 attribute certificate. *
+ *
+ * @param seq The ASN.1 sequence.
+ */
+ private Holder(
+ Asn1Sequence seq)
+ {
+ if (seq.Count > 3)
+ throw new ArgumentException("Bad sequence size: " + seq.Count);
+
+ for (int i = 0; i != seq.Count; i++)
+ {
+ Asn1TaggedObject tObj = Asn1TaggedObject.GetInstance(seq[i]);
+
+ switch (tObj.TagNo)
+ {
+ case 0:
+ baseCertificateID = IssuerSerial.GetInstance(tObj, false);
+ break;
+ case 1:
+ entityName = GeneralNames.GetInstance(tObj, false);
+ break;
+ case 2:
+ objectDigestInfo = ObjectDigestInfo.GetInstance(tObj, false);
+ break;
+ default:
+ throw new ArgumentException("unknown tag in Holder");
+ }
+ }
+
+ this.version = 1;
+ }
+
+ public Holder(
+ IssuerSerial baseCertificateID)
+ : this(baseCertificateID, 1)
+ {
+ }
+
+ /**
+ * Constructs a holder from a IssuerSerial.
+ * @param baseCertificateID The IssuerSerial.
+ * @param version The version of the attribute certificate.
+ */
+ public Holder(
+ IssuerSerial baseCertificateID,
+ int version)
+ {
+ this.baseCertificateID = baseCertificateID;
+ this.version = version;
+ }
+
+ /**
+ * Returns 1 for v2 attribute certificates or 0 for v1 attribute
+ * certificates.
+ * @return The version of the attribute certificate.
+ */
+ public int Version
+ {
+ get { return version; }
+ }
+
+ /**
+ * Constructs a holder with an entityName for v2 attribute certificates or
+ * with a subjectName for v1 attribute certificates.
+ *
+ * @param entityName The entity or subject name.
+ */
+ public Holder(
+ GeneralNames entityName)
+ : this(entityName, 1)
+ {
+ }
+
+ /**
+ * Constructs a holder with an entityName for v2 attribute certificates or
+ * with a subjectName for v1 attribute certificates.
+ *
+ * @param entityName The entity or subject name.
+ * @param version The version of the attribute certificate.
+ */
+ public Holder(
+ GeneralNames entityName,
+ int version)
+ {
+ this.entityName = entityName;
+ this.version = version;
+ }
+
+ /**
+ * Constructs a holder from an object digest info.
+ *
+ * @param objectDigestInfo The object digest info object.
+ */
+ public Holder(
+ ObjectDigestInfo objectDigestInfo)
+ {
+ this.objectDigestInfo = objectDigestInfo;
+ this.version = 1;
+ }
+
+ public IssuerSerial BaseCertificateID
+ {
+ get { return baseCertificateID; }
+ }
+
+ /**
+ * Returns the entityName for an v2 attribute certificate or the subjectName
+ * for an v1 attribute certificate.
+ *
+ * @return The entityname or subjectname.
+ */
+ public GeneralNames EntityName
+ {
+ get { return entityName; }
+ }
+
+ public ObjectDigestInfo ObjectDigestInfo
+ {
+ get { return objectDigestInfo; }
+ }
+
+ /**
+ * 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
+ * }
+ *
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ if (version == 1)
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+
+ if (baseCertificateID != null)
+ {
+ v.Add(new DerTaggedObject(false, 0, baseCertificateID));
+ }
+
+ if (entityName != null)
+ {
+ v.Add(new DerTaggedObject(false, 1, entityName));
+ }
+
+ if (objectDigestInfo != null)
+ {
+ v.Add(new DerTaggedObject(false, 2, objectDigestInfo));
+ }
+
+ return new DerSequence(v);
+ }
+
+ if (entityName != null)
+ {
+ return new DerTaggedObject(false, 1, entityName);
+ }
+
+ return new DerTaggedObject(false, 0, baseCertificateID);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/x509/IetfAttrSyntax.cs b/Crypto/src/asn1/x509/IetfAttrSyntax.cs
new file mode 100644
index 000000000..e719865b3
--- /dev/null
+++ b/Crypto/src/asn1/x509/IetfAttrSyntax.cs
@@ -0,0 +1,161 @@
+using System;
+using System.Collections;
+
+using Org.BouncyCastle.Asn1;
+
+namespace Org.BouncyCastle.Asn1.X509
+{
+ /**
+ * Implementation of IetfAttrSyntax as specified by RFC3281.
+ */
+ public class IetfAttrSyntax
+ : Asn1Encodable
+ {
+ public const int ValueOctets = 1;
+ public const int ValueOid = 2;
+ public const int ValueUtf8 = 3;
+
+ internal readonly GeneralNames policyAuthority;
+ internal readonly Asn1EncodableVector values = new Asn1EncodableVector();
+
+ internal int valueChoice = -1;
+
+ /**
+ *
+ */
+ public IetfAttrSyntax(
+ Asn1Sequence seq)
+ {
+ int i = 0;
+
+ if (seq[0] is Asn1TaggedObject)
+ {
+ policyAuthority = GeneralNames.GetInstance(((Asn1TaggedObject)seq[0]), false);
+ i++;
+ }
+ else if (seq.Count == 2)
+ { // VOMS fix
+ policyAuthority = GeneralNames.GetInstance(seq[0]);
+ i++;
+ }
+
+ if (!(seq[i] is Asn1Sequence))
+ {
+ throw new ArgumentException("Non-IetfAttrSyntax encoding");
+ }
+
+ seq = (Asn1Sequence) seq[i];
+
+ foreach (Asn1Object obj in seq)
+ {
+ int type;
+
+ if (obj is DerObjectIdentifier)
+ {
+ type = ValueOid;
+ }
+ else if (obj is DerUtf8String)
+ {
+ type = ValueUtf8;
+ }
+ else if (obj is DerOctetString)
+ {
+ type = ValueOctets;
+ }
+ else
+ {
+ throw new ArgumentException("Bad value type encoding IetfAttrSyntax");
+ }
+
+ if (valueChoice < 0)
+ {
+ valueChoice = type;
+ }
+
+ if (type != valueChoice)
+ {
+ throw new ArgumentException("Mix of value types in IetfAttrSyntax");
+ }
+
+ values.Add(obj);
+ }
+ }
+
+ public GeneralNames PolicyAuthority
+ {
+ get { return policyAuthority; }
+ }
+
+ public int ValueType
+ {
+ get { return valueChoice; }
+ }
+
+ public object[] GetValues()
+ {
+ if (this.ValueType == ValueOctets)
+ {
+ Asn1OctetString[] tmp = new Asn1OctetString[values.Count];
+
+ for (int i = 0; i != tmp.Length; i++)
+ {
+ tmp[i] = (Asn1OctetString) values[i];
+ }
+
+ return tmp;
+ }
+
+ if (this.ValueType == ValueOid)
+ {
+ DerObjectIdentifier[] tmp = new DerObjectIdentifier[values.Count];
+
+ for (int i = 0; i != tmp.Length; i++)
+ {
+ tmp[i] = (DerObjectIdentifier) values[i];
+ }
+
+ return tmp;
+ }
+
+ {
+ DerUtf8String[] tmp = new DerUtf8String[values.Count];
+
+ for (int i = 0; i != tmp.Length; i++)
+ {
+ tmp[i] = (DerUtf8String) values[i];
+ }
+
+ return tmp;
+ }
+ }
+
+ /**
+ *
+ *
+ */
+ public class RoleSyntax
+ : Asn1Encodable
+ {
+ private readonly GeneralNames roleAuthority;
+ private readonly GeneralName roleName;
+
+ /**
+ * RoleSyntax factory method.
+ * @param obj the object used to construct an instance of
+ * RoleSyntax. It must be an instance of RoleSyntax
+ * or Asn1Sequence.
+ * @return the instance of RoleSyntax built from the
+ * supplied object.
+ * @throws java.lang.ArgumentException if the object passed
+ * to the factory is not an instance of RoleSyntax or
+ * Asn1Sequence.
+ */
+ public static RoleSyntax GetInstance(
+ object obj)
+ {
+ if (obj is RoleSyntax)
+ return (RoleSyntax)obj;
+
+ if (obj != null)
+ return new RoleSyntax(Asn1Sequence.GetInstance(obj));
+
+ return null;
+ }
+
+ /**
+ * Constructor.
+ * @param roleAuthority the role authority of this RoleSyntax.
+ * @param roleName the role name of this RoleSyntax.
+ */
+ public RoleSyntax(
+ GeneralNames roleAuthority,
+ GeneralName roleName)
+ {
+ if (roleName == null
+ || roleName.TagNo != GeneralName.UniformResourceIdentifier
+ || ((IAsn1String) roleName.Name).GetString().Equals(""))
+ {
+ throw new ArgumentException("the role name MUST be non empty and MUST " +
+ "use the URI option of GeneralName");
+ }
+
+ this.roleAuthority = roleAuthority;
+ this.roleName = roleName;
+ }
+
+ /**
+ * Constructor. Invoking this constructor is the same as invoking
+ * new RoleSyntax(null, roleName).
+ * @param roleName the role name of this RoleSyntax.
+ */
+ public RoleSyntax(
+ GeneralName roleName)
+ : this(null, roleName)
+ {
+ }
+
+ /**
+ * Utility constructor. Takes a string argument representing
+ * the role name, builds a GeneralName to hold the role name
+ * and calls the constructor that takes a GeneralName.
+ * @param roleName
+ */
+ public RoleSyntax(
+ string roleName)
+ : this(new GeneralName(GeneralName.UniformResourceIdentifier,
+ (roleName == null)? "": roleName))
+ {
+ }
+
+ /**
+ * Constructor that builds an instance of RoleSyntax by
+ * extracting the encoded elements from the Asn1Sequence
+ * object supplied.
+ * @param seq an instance of Asn1Sequence that holds
+ * the encoded elements used to build this RoleSyntax.
+ */
+ private RoleSyntax(
+ Asn1Sequence seq)
+ {
+ if (seq.Count < 1 || seq.Count > 2)
+ {
+ throw new ArgumentException("Bad sequence size: " + seq.Count);
+ }
+
+ for (int i = 0; i != seq.Count; i++)
+ {
+ Asn1TaggedObject taggedObject = Asn1TaggedObject.GetInstance(seq[i]);
+ switch (taggedObject.TagNo)
+ {
+ case 0:
+ roleAuthority = GeneralNames.GetInstance(taggedObject, false);
+ break;
+ case 1:
+ roleName = GeneralName.GetInstance(taggedObject, true);
+ break;
+ default:
+ throw new ArgumentException("Unknown tag in RoleSyntax");
+ }
+ }
+ }
+
+ /**
+ * Gets the role authority of this RoleSyntax.
+ * @return an instance of GeneralNames holding the
+ * role authority of this RoleSyntax.
+ */
+ public GeneralNames RoleAuthority
+ {
+ get { return this.roleAuthority; }
+ }
+
+ /**
+ * Gets the role name of this RoleSyntax.
+ * @return an instance of GeneralName holding the
+ * role name of this RoleSyntax.
+ */
+ public GeneralName RoleName
+ {
+ get { return this.roleName; }
+ }
+
+ /**
+ * Gets the role name as a java.lang.string object.
+ * @return the role name of this RoleSyntax represented as a
+ * string object.
+ */
+ public string GetRoleNameAsString()
+ {
+ return ((IAsn1String) this.roleName.Name).GetString();
+ }
+
+ /**
+ * Gets the role authority as a string[] object.
+ * @return the role authority of this RoleSyntax represented as a
+ * string[] array.
+ */
+ public string[] GetRoleAuthorityAsString()
+ {
+ if (roleAuthority == null)
+ {
+ return new string[0];
+ }
+
+ GeneralName[] names = roleAuthority.GetNames();
+ string[] namesString = new string[names.Length];
+ for(int i = 0; i < names.Length; i++)
+ {
+ Asn1Encodable asn1Value = names[i].Name;
+ if (asn1Value is IAsn1String)
+ {
+ namesString[i] = ((IAsn1String) asn1Value).GetString();
+ }
+ else
+ {
+ namesString[i] = asn1Value.ToString();
+ }
+ }
+
+ return namesString;
+ }
+
+ /**
+ * Implementation of the method ToAsn1Object as
+ * required by the superclass ASN1Encodable.
+ *
+ *
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector v = new Asn1EncodableVector();
+
+ if (this.roleAuthority != null)
+ {
+ v.Add(new DerTaggedObject(false, 0, roleAuthority));
+ }
+
+ v.Add(new DerTaggedObject(true, 1, roleName));
+
+ return new DerSequence(v);
+ }
+
+ public override string ToString()
+ {
+ StringBuilder buff = new StringBuilder("Name: " + this.GetRoleNameAsString() +
+ " - Auth: ");
+
+ if (this.roleAuthority == null || roleAuthority.GetNames().Length == 0)
+ {
+ buff.Append("N/A");
+ }
+ else
+ {
+ string[] names = this.GetRoleAuthorityAsString();
+ buff.Append('[').Append(names[0]);
+ for(int i = 1; i < names.Length; i++)
+ {
+ buff.Append(", ").Append(names[i]);
+ }
+ buff.Append(']');
+ }
+
+ return buff.ToString();
+ }
+ }
+}
diff --git a/Crypto/src/asn1/x509/SubjectDirectoryAttributes.cs b/Crypto/src/asn1/x509/SubjectDirectoryAttributes.cs
new file mode 100644
index 000000000..c76d94d78
--- /dev/null
+++ b/Crypto/src/asn1/x509/SubjectDirectoryAttributes.cs
@@ -0,0 +1,142 @@
+using System;
+using System.Collections;
+
+using Org.BouncyCastle.Utilities;
+using Org.BouncyCastle.Utilities.Collections;
+
+namespace Org.BouncyCastle.Asn1.X509
+{
+ /**
+ * This extension may contain further X.500 attributes of the subject. See also
+ * RFC 3039.
+ *
+ *
+ * SubjectDirectoryAttributes ::= Attributes
+ * Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
+ * Attribute ::= SEQUENCE
+ * {
+ * type AttributeType
+ * values SET OF AttributeValue
+ * }
+ *
+ * AttributeType ::= OBJECT IDENTIFIER
+ * AttributeValue ::= ANY DEFINED BY AttributeType
+ *
+ *
+ * @see org.bouncycastle.asn1.x509.X509Name for AttributeType ObjectIdentifiers.
+ */
+ public class SubjectDirectoryAttributes
+ : Asn1Encodable
+ {
+ private readonly IList attributes;
+
+ public static SubjectDirectoryAttributes GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is SubjectDirectoryAttributes)
+ {
+ return (SubjectDirectoryAttributes) obj;
+ }
+
+ if (obj is Asn1Sequence)
+ {
+ return new SubjectDirectoryAttributes((Asn1Sequence) obj);
+ }
+
+ throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj");
+ }
+
+ /**
+ * Constructor from Asn1Sequence.
+ *
+ * The sequence is of type SubjectDirectoryAttributes:
+ *
+ *
+ * SubjectDirectoryAttributes ::= Attributes
+ * Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
+ * Attribute ::= SEQUENCE
+ * {
+ * type AttributeType
+ * values SET OF AttributeValue
+ * }
+ *
+ * AttributeType ::= OBJECT IDENTIFIER
+ * AttributeValue ::= ANY DEFINED BY AttributeType
+ *
+ *
+ * @param seq
+ * The ASN.1 sequence.
+ */
+ private SubjectDirectoryAttributes(
+ Asn1Sequence seq)
+ {
+ this.attributes = Platform.CreateArrayList();
+ foreach (object o in seq)
+ {
+ Asn1Sequence s = Asn1Sequence.GetInstance(o);
+ attributes.Add(AttributeX509.GetInstance(s));
+ }
+ }
+
+#if !(SILVERLIGHT || PORTABLE)
+ [Obsolete]
+ public SubjectDirectoryAttributes(
+ ArrayList attributes)
+ : this((IList)attributes)
+ {
+ }
+#endif
+
+ /**
+ * Constructor from an ArrayList of attributes.
+ *
+ * The ArrayList consists of attributes of type {@link Attribute Attribute}
+ *
+ * @param attributes The attributes.
+ *
+ */
+ public SubjectDirectoryAttributes(
+ IList attributes)
+ {
+ this.attributes = Platform.CreateArrayList(attributes);
+ }
+
+ /**
+ * Produce an object suitable for an Asn1OutputStream.
+ *
+ * Returns:
+ *
+ *
+ * SubjectDirectoryAttributes ::= Attributes
+ * Attributes ::= SEQUENCE SIZE (1..MAX) OF Attribute
+ * Attribute ::= SEQUENCE
+ * {
+ * type AttributeType
+ * values SET OF AttributeValue
+ * }
+ *
+ * AttributeType ::= OBJECT IDENTIFIER
+ * AttributeValue ::= ANY DEFINED BY AttributeType
+ *
+ *
+ * @return a DERObject
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ AttributeX509[] v = new AttributeX509[attributes.Count];
+ for (int i = 0; i < attributes.Count; ++i)
+ {
+ v[i] = (AttributeX509)attributes[i];
+ }
+ return new DerSequence(v);
+ }
+
+ /**
+ * @return Returns the attributes.
+ */
+ public IEnumerable Attributes
+ {
+ get { return new EnumerableProxy(attributes); }
+ }
+ }
+}
diff --git a/Crypto/src/asn1/x509/SubjectKeyIdentifier.cs b/Crypto/src/asn1/x509/SubjectKeyIdentifier.cs
new file mode 100644
index 000000000..e640760f3
--- /dev/null
+++ b/Crypto/src/asn1/x509/SubjectKeyIdentifier.cs
@@ -0,0 +1,141 @@
+using System;
+
+using Org.BouncyCastle.Crypto;
+using Org.BouncyCastle.Crypto.Digests;
+
+namespace Org.BouncyCastle.Asn1.X509
+{
+ /**
+ * The SubjectKeyIdentifier object.
+ *
+ * SubjectKeyIdentifier::= OCTET STRING
+ *
+ */
+ public class SubjectKeyIdentifier
+ : Asn1Encodable
+ {
+ private readonly byte[] keyIdentifier;
+
+ public static SubjectKeyIdentifier GetInstance(
+ Asn1TaggedObject obj,
+ bool explicitly)
+ {
+ return GetInstance(Asn1OctetString.GetInstance(obj, explicitly));
+ }
+
+ public static SubjectKeyIdentifier GetInstance(
+ object obj)
+ {
+ if (obj is SubjectKeyIdentifier)
+ {
+ return (SubjectKeyIdentifier) obj;
+ }
+
+ if (obj is SubjectPublicKeyInfo)
+ {
+ return new SubjectKeyIdentifier((SubjectPublicKeyInfo) obj);
+ }
+
+ if (obj is Asn1OctetString)
+ {
+ return new SubjectKeyIdentifier((Asn1OctetString) obj);
+ }
+
+ if (obj is X509Extension)
+ {
+ return GetInstance(X509Extension.ConvertValueToObject((X509Extension) obj));
+ }
+
+ throw new ArgumentException("Invalid SubjectKeyIdentifier: " + obj.GetType().Name);
+ }
+
+ public SubjectKeyIdentifier(
+ byte[] keyID)
+ {
+ if (keyID == null)
+ throw new ArgumentNullException("keyID");
+
+ this.keyIdentifier = keyID;
+ }
+
+ public SubjectKeyIdentifier(
+ Asn1OctetString keyID)
+ {
+ this.keyIdentifier = keyID.GetOctets();
+ }
+
+ /**
+ * Calculates the keyIdentifier using a SHA1 hash over the BIT STRING
+ * from SubjectPublicKeyInfo as defined in RFC3280.
+ *
+ * @param spki the subject public key info.
+ */
+ public SubjectKeyIdentifier(
+ SubjectPublicKeyInfo spki)
+ {
+ this.keyIdentifier = GetDigest(spki);
+ }
+
+ public byte[] GetKeyIdentifier()
+ {
+ return keyIdentifier;
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ return new DerOctetString(keyIdentifier);
+ }
+
+ /**
+ * 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 keyInfo the key info object containing the subjectPublicKey field.
+ * @return the key identifier.
+ */
+ public static SubjectKeyIdentifier CreateSha1KeyIdentifier(
+ SubjectPublicKeyInfo keyInfo)
+ {
+ return new SubjectKeyIdentifier(keyInfo);
+ }
+
+ /**
+ * 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 keyInfo the key info object containing the subjectPublicKey field.
+ * @return the key identifier.
+ */
+ public static SubjectKeyIdentifier CreateTruncatedSha1KeyIdentifier(
+ SubjectPublicKeyInfo keyInfo)
+ {
+ byte[] dig = GetDigest(keyInfo);
+ byte[] id = new byte[8];
+
+ Array.Copy(dig, dig.Length - 8, id, 0, id.Length);
+
+ id[0] &= 0x0f;
+ id[0] |= 0x40;
+
+ return new SubjectKeyIdentifier(id);
+ }
+
+ private static byte[] GetDigest(
+ SubjectPublicKeyInfo spki)
+ {
+ IDigest digest = new Sha1Digest();
+ byte[] resBuf = new byte[digest.GetDigestSize()];
+
+ byte[] bytes = spki.PublicKeyData.GetBytes();
+ digest.BlockUpdate(bytes, 0, bytes.Length);
+ digest.DoFinal(resBuf, 0);
+ return resBuf;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/x509/SubjectPublicKeyInfo.cs b/Crypto/src/asn1/x509/SubjectPublicKeyInfo.cs
new file mode 100644
index 000000000..8ce4b2762
--- /dev/null
+++ b/Crypto/src/asn1/x509/SubjectPublicKeyInfo.cs
@@ -0,0 +1,102 @@
+using System;
+using System.Collections;
+using System.IO;
+
+namespace Org.BouncyCastle.Asn1.X509
+{
+ /**
+ * The object that contains the public key stored in a certficate.
+ *
+ * The GetEncoded() method in the public keys in the JCE produces a DER
+ * encoded one of these.
+ */
+ public class SubjectPublicKeyInfo
+ : Asn1Encodable
+ {
+ private readonly AlgorithmIdentifier algID;
+ private readonly DerBitString keyData;
+
+ public static SubjectPublicKeyInfo GetInstance(
+ Asn1TaggedObject obj,
+ bool explicitly)
+ {
+ return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
+ }
+
+ public static SubjectPublicKeyInfo GetInstance(
+ object obj)
+ {
+ if (obj is SubjectPublicKeyInfo)
+ return (SubjectPublicKeyInfo) obj;
+
+ if (obj != null)
+ return new SubjectPublicKeyInfo(Asn1Sequence.GetInstance(obj));
+
+ return null;
+ }
+
+ public SubjectPublicKeyInfo(
+ AlgorithmIdentifier algID,
+ Asn1Encodable publicKey)
+ {
+ this.keyData = new DerBitString(publicKey);
+ this.algID = algID;
+ }
+
+ public SubjectPublicKeyInfo(
+ AlgorithmIdentifier algID,
+ byte[] publicKey)
+ {
+ this.keyData = new DerBitString(publicKey);
+ this.algID = algID;
+ }
+
+ private SubjectPublicKeyInfo(
+ Asn1Sequence seq)
+ {
+ if (seq.Count != 2)
+ throw new ArgumentException("Bad sequence size: " + seq.Count, "seq");
+
+ this.algID = AlgorithmIdentifier.GetInstance(seq[0]);
+ this.keyData = DerBitString.GetInstance(seq[1]);
+ }
+
+ public AlgorithmIdentifier AlgorithmID
+ {
+ get { return algID; }
+ }
+
+ /**
+ * for when the public key is an encoded object - if the bitstring
+ * can't be decoded this routine raises an IOException.
+ *
+ * @exception IOException - if the bit string doesn't represent a Der
+ * encoded object.
+ */
+ public Asn1Object GetPublicKey()
+ {
+ return Asn1Object.FromByteArray(keyData.GetBytes());
+ }
+
+ /**
+ * for when the public key is raw bits...
+ */
+ public DerBitString PublicKeyData
+ {
+ get { return keyData; }
+ }
+
+ /**
+ * Produce an object suitable for an Asn1OutputStream.
+ *
+ * Note: issuerUniqueID and subjectUniqueID are both deprecated by the IETF. This class
+ * will parse them, but you really shouldn't be creating new ones.
+ */
+ public class TbsCertificateStructure
+ : Asn1Encodable
+ {
+ internal Asn1Sequence seq;
+ internal DerInteger version;
+ internal DerInteger serialNumber;
+ internal AlgorithmIdentifier signature;
+ internal X509Name issuer;
+ internal Time startDate, endDate;
+ internal X509Name subject;
+ internal SubjectPublicKeyInfo subjectPublicKeyInfo;
+ internal DerBitString issuerUniqueID;
+ internal DerBitString subjectUniqueID;
+ internal X509Extensions extensions;
+
+ public static TbsCertificateStructure GetInstance(
+ Asn1TaggedObject obj,
+ bool explicitly)
+ {
+ return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
+ }
+
+ public static TbsCertificateStructure GetInstance(
+ object obj)
+ {
+ if (obj is TbsCertificateStructure)
+ return (TbsCertificateStructure) obj;
+
+ if (obj != null)
+ return new TbsCertificateStructure(Asn1Sequence.GetInstance(obj));
+
+ return null;
+ }
+
+ internal TbsCertificateStructure(
+ Asn1Sequence seq)
+ {
+ int seqStart = 0;
+
+ this.seq = seq;
+
+ //
+ // some certficates don't include a version number - we assume v1
+ //
+ if (seq[0] is DerTaggedObject)
+ {
+ version = DerInteger.GetInstance((Asn1TaggedObject)seq[0], true);
+ }
+ else
+ {
+ seqStart = -1; // field 0 is missing!
+ version = new DerInteger(0);
+ }
+
+ serialNumber = DerInteger.GetInstance(seq[seqStart + 1]);
+
+ signature = AlgorithmIdentifier.GetInstance(seq[seqStart + 2]);
+ issuer = X509Name.GetInstance(seq[seqStart + 3]);
+
+ //
+ // before and after dates
+ //
+ Asn1Sequence dates = (Asn1Sequence)seq[seqStart + 4];
+
+ startDate = Time.GetInstance(dates[0]);
+ endDate = Time.GetInstance(dates[1]);
+
+ subject = X509Name.GetInstance(seq[seqStart + 5]);
+
+ //
+ // public key info.
+ //
+ subjectPublicKeyInfo = SubjectPublicKeyInfo.GetInstance(seq[seqStart + 6]);
+
+ for (int extras = seq.Count - (seqStart + 6) - 1; extras > 0; extras--)
+ {
+ DerTaggedObject extra = (DerTaggedObject) seq[seqStart + 6 + extras];
+
+ switch (extra.TagNo)
+ {
+ case 1:
+ issuerUniqueID = DerBitString.GetInstance(extra, false);
+ break;
+ case 2:
+ subjectUniqueID = DerBitString.GetInstance(extra, false);
+ break;
+ case 3:
+ extensions = X509Extensions.GetInstance(extra);
+ break;
+ }
+ }
+ }
+
+ public int Version
+ {
+ get { return version.Value.IntValue + 1; }
+ }
+
+ public DerInteger VersionNumber
+ {
+ get { return version; }
+ }
+
+ public DerInteger SerialNumber
+ {
+ get { return serialNumber; }
+ }
+
+ public AlgorithmIdentifier Signature
+ {
+ get { return signature; }
+ }
+
+ public X509Name Issuer
+ {
+ get { return issuer; }
+ }
+
+ public Time StartDate
+ {
+ get { return startDate; }
+ }
+
+ public Time EndDate
+ {
+ get { return endDate; }
+ }
+
+ public X509Name Subject
+ {
+ get { return subject; }
+ }
+
+ public SubjectPublicKeyInfo SubjectPublicKeyInfo
+ {
+ get { return subjectPublicKeyInfo; }
+ }
+
+ public DerBitString IssuerUniqueID
+ {
+ get { return issuerUniqueID; }
+ }
+
+ public DerBitString SubjectUniqueID
+ {
+ get { return subjectUniqueID; }
+ }
+
+ public X509Extensions Extensions
+ {
+ get { return extensions; }
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ return seq;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/x509/Target.cs b/Crypto/src/asn1/x509/Target.cs
new file mode 100644
index 000000000..309b28c95
--- /dev/null
+++ b/Crypto/src/asn1/x509/Target.cs
@@ -0,0 +1,139 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.X509
+{
+ /**
+ * Target structure used in target information extension for attribute
+ * certificates from RFC 3281.
+ *
+ *
+ *
+ * @return an Asn1Object
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ // GeneralName is a choice already so most be explicitly tagged
+ if (targetName != null)
+ {
+ return new DerTaggedObject(true, 0, targetName);
+ }
+
+ return new DerTaggedObject(true, 1, targetGroup);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/x509/TargetInformation.cs b/Crypto/src/asn1/x509/TargetInformation.cs
new file mode 100644
index 000000000..75b18c0c9
--- /dev/null
+++ b/Crypto/src/asn1/x509/TargetInformation.cs
@@ -0,0 +1,123 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.X509
+{
+ /**
+ * Target information extension for attributes certificates according to RFC
+ * 3281.
+ *
+ *
+ * SEQUENCE OF Targets
+ *
+ *
+ */
+ public class TargetInformation
+ : Asn1Encodable
+ {
+ private readonly Asn1Sequence targets;
+
+ /**
+ * Creates an instance of a TargetInformation from the given object.
+ *
+ * obj can be a TargetInformation or a {@link Asn1Sequence}
+ *
+ * @param obj The object.
+ * @return A TargetInformation instance.
+ * @throws ArgumentException if the given object cannot be interpreted as TargetInformation.
+ */
+ public static TargetInformation GetInstance(
+ object obj)
+ {
+ if (obj is TargetInformation)
+ {
+ return (TargetInformation) obj;
+ }
+
+ if (obj is Asn1Sequence)
+ {
+ return new TargetInformation((Asn1Sequence) obj);
+ }
+
+ throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj");
+ }
+
+ /**
+ * Constructor from a Asn1Sequence.
+ *
+ * @param seq The Asn1Sequence.
+ * @throws ArgumentException if the sequence does not contain
+ * correctly encoded Targets elements.
+ */
+ private TargetInformation(
+ Asn1Sequence targets)
+ {
+ this.targets = targets;
+ }
+
+ /**
+ * Returns the targets in this target information extension.
+ *
+ * The ArrayList is cloned before it is returned.
+ *
+ * @return Returns the targets.
+ */
+ public virtual Targets[] GetTargetsObjects()
+ {
+ Targets[] result = new Targets[targets.Count];
+
+ for (int i = 0; i < targets.Count; ++i)
+ {
+ result[i] = Targets.GetInstance(targets[i]);
+ }
+
+ return result;
+ }
+
+ /**
+ * Constructs a target information from a single targets element.
+ * According to RFC 3281 only one targets element must be produced.
+ *
+ * @param targets A Targets instance.
+ */
+ public TargetInformation(
+ Targets targets)
+ {
+ this.targets = new DerSequence(targets);
+ }
+
+ /**
+ * According to RFC 3281 only one targets element must be produced. If
+ * multiple targets are given they must be merged in
+ * into one targets element.
+ *
+ * @param targets An array with {@link Targets}.
+ */
+ public TargetInformation(
+ Target[] targets)
+ : this(new Targets(targets))
+ {
+ }
+
+ /**
+ * Produce an object suitable for an Asn1OutputStream.
+ *
+ * Returns:
+ *
+ *
+ * SEQUENCE OF Targets
+ *
+ *
+ *
+ * According to RFC 3281 only one targets element must be produced. If
+ * multiple targets are given in the constructor they are merged into one
+ * targets element. If this was produced from a
+ * {@link Org.BouncyCastle.Asn1.Asn1Sequence} the encoding is kept.
+ *
+ * @return an Asn1Object
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ return targets;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/x509/Targets.cs b/Crypto/src/asn1/x509/Targets.cs
new file mode 100644
index 000000000..3e436d8d8
--- /dev/null
+++ b/Crypto/src/asn1/x509/Targets.cs
@@ -0,0 +1,121 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.X509
+{
+ /**
+ * Targets structure used in target information extension for attribute
+ * certificates from RFC 3281.
+ *
+ *
+ *
+ * @see PolicyQualifierId
+ * @see PolicyInformation
+ */
+ public class UserNotice
+ : Asn1Encodable
+ {
+ internal NoticeReference noticeRef;
+ internal DisplayText explicitText;
+
+ /**
+ * Creates a new UserNotice instance.
+ *
+ * @param noticeRef a NoticeReference value
+ * @param explicitText a DisplayText value
+ */
+ public UserNotice(
+ NoticeReference noticeRef,
+ DisplayText explicitText)
+ {
+ this.noticeRef = noticeRef;
+ this.explicitText = explicitText;
+ }
+
+ /**
+ * Creates a new UserNotice instance.
+ *
+ * @param noticeRef a NoticeReference value
+ * @param str the explicitText field as a string.
+ */
+ public UserNotice(
+ NoticeReference noticeRef,
+ string str)
+ {
+ this.noticeRef = noticeRef;
+ this.explicitText = new DisplayText(str);
+ }
+
+ /**
+ * Creates a new UserNotice instance.
+ *
Useful from reconstructing a UserNotice instance
+ * from its encodable/encoded form.
+ *
+ * @param as an ASN1Sequence value obtained from either
+ * calling @{link toASN1Object()} for a UserNotice
+ * instance or from parsing it from a DER-encoded stream.
+ */
+ public UserNotice(
+ Asn1Sequence seq)
+ {
+ if (seq.Count == 2)
+ {
+ noticeRef = NoticeReference.GetInstance(seq[0]);
+ explicitText = DisplayText.GetInstance(seq[1]);
+ }
+ else if (seq.Count == 1)
+ {
+ if (seq[0].ToAsn1Object() is Asn1Sequence)
+ {
+ noticeRef = NoticeReference.GetInstance(seq[0]);
+ }
+ else
+ {
+ explicitText = DisplayText.GetInstance(seq[0]);
+ }
+ }
+ else
+ {
+ throw new ArgumentException("Bad sequence size: " + seq.Count);
+ }
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector av = new Asn1EncodableVector();
+
+ if (noticeRef != null)
+ {
+ av.Add(noticeRef);
+ }
+
+ if (explicitText != null)
+ {
+ av.Add(explicitText);
+ }
+
+ return new DerSequence(av);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/x509/V1TBSCertificateGenerator.cs b/Crypto/src/asn1/x509/V1TBSCertificateGenerator.cs
new file mode 100644
index 000000000..20b525a48
--- /dev/null
+++ b/Crypto/src/asn1/x509/V1TBSCertificateGenerator.cs
@@ -0,0 +1,108 @@
+using System;
+
+namespace Org.BouncyCastle.Asn1.X509
+{
+ /**
+ * Generator for Version 1 TbsCertificateStructures.
+ *
+ */
+ public override Asn1Object ToAsn1Object()
+ {
+ Asn1EncodableVector vec = new Asn1EncodableVector();
+
+ foreach (DerObjectIdentifier oid in ordering)
+ {
+ X509Extension ext = (X509Extension) extensions[oid];
+ Asn1EncodableVector v = new Asn1EncodableVector(oid);
+
+ if (ext.IsCritical)
+ {
+ v.Add(DerBoolean.True);
+ }
+
+ v.Add(ext.Value);
+
+ vec.Add(new DerSequence(v));
+ }
+
+ return new DerSequence(vec);
+ }
+
+ public bool Equivalent(
+ X509Extensions other)
+ {
+ if (extensions.Count != other.extensions.Count)
+ return false;
+
+ foreach (DerObjectIdentifier oid in extensions.Keys)
+ {
+ if (!extensions[oid].Equals(other.extensions[oid]))
+ return false;
+ }
+
+ return true;
+ }
+
+ public DerObjectIdentifier[] GetExtensionOids()
+ {
+ return ToOidArray(ordering);
+ }
+
+ public DerObjectIdentifier[] GetNonCriticalExtensionOids()
+ {
+ return GetExtensionOids(false);
+ }
+
+ public DerObjectIdentifier[] GetCriticalExtensionOids()
+ {
+ return GetExtensionOids(true);
+ }
+
+ private DerObjectIdentifier[] GetExtensionOids(bool isCritical)
+ {
+ IList oids = Platform.CreateArrayList();
+
+ foreach (DerObjectIdentifier oid in this.ordering)
+ {
+ X509Extension ext = (X509Extension)extensions[oid];
+ if (ext.IsCritical == isCritical)
+ {
+ oids.Add(oid);
+ }
+ }
+
+ return ToOidArray(oids);
+ }
+
+ private static DerObjectIdentifier[] ToOidArray(IList oids)
+ {
+ DerObjectIdentifier[] oidArray = new DerObjectIdentifier[oids.Count];
+ oids.CopyTo(oidArray, 0);
+ return oidArray;
+ }
+ }
+}
diff --git a/Crypto/src/asn1/x509/X509ExtensionsGenerator.cs b/Crypto/src/asn1/x509/X509ExtensionsGenerator.cs
new file mode 100644
index 000000000..d6f567b22
--- /dev/null
+++ b/Crypto/src/asn1/x509/X509ExtensionsGenerator.cs
@@ -0,0 +1,81 @@
+using System;
+using System.Collections;
+
+using Org.BouncyCastle.Utilities;
+
+namespace Org.BouncyCastle.Asn1.X509
+{
+ /// Generator for X.509 extensions
+ public class X509ExtensionsGenerator
+ {
+ private IDictionary extensions = Platform.CreateHashtable();
+ private IList extOrdering = Platform.CreateArrayList();
+
+ /// Reset the generator
+ public void Reset()
+ {
+ extensions = Platform.CreateHashtable();
+ extOrdering = Platform.CreateArrayList();
+ }
+
+ ///
+ /// Add an extension with the given oid and the passed in value to be included
+ /// in the OCTET STRING associated with the extension.
+ ///
+ /// OID for the extension.
+ /// True if critical, false otherwise.
+ /// The ASN.1 object to be included in the extension.
+ public void AddExtension(
+ DerObjectIdentifier oid,
+ bool critical,
+ Asn1Encodable extValue)
+ {
+ byte[] encoded;
+ try
+ {
+ encoded = extValue.GetDerEncoded();
+ }
+ catch (Exception e)
+ {
+ throw new ArgumentException("error encoding value: " + e);
+ }
+
+ this.AddExtension(oid, critical, encoded);
+ }
+
+ ///
+ /// Add an extension with the given oid and the passed in byte array to be wrapped
+ /// in the OCTET STRING associated with the extension.
+ ///
+ /// OID for the extension.
+ /// True if critical, false otherwise.
+ /// The byte array to be wrapped.
+ public void AddExtension(
+ DerObjectIdentifier oid,
+ bool critical,
+ byte[] extValue)
+ {
+ if (extensions.Contains(oid))
+ {
+ throw new ArgumentException("extension " + oid + " already added");
+ }
+
+ extOrdering.Add(oid);
+ extensions.Add(oid, new X509Extension(critical, new DerOctetString(extValue)));
+ }
+
+ /// Return true if there are no extension present in this generator.
+ /// True if empty, false otherwise
+ public bool IsEmpty
+ {
+ get { return extOrdering.Count < 1; }
+ }
+
+ /// Generate an X509Extensions object based on the current state of the generator.
+ /// An X509Extensions object
+ public X509Extensions Generate()
+ {
+ return new X509Extensions(extOrdering, extensions);
+ }
+ }
+}
diff --git a/Crypto/src/asn1/x509/X509Name.cs b/Crypto/src/asn1/x509/X509Name.cs
new file mode 100644
index 000000000..b459cbe1b
--- /dev/null
+++ b/Crypto/src/asn1/x509/X509Name.cs
@@ -0,0 +1,1189 @@
+using System;
+using System.Collections;
+using System.Globalization;
+using System.IO;
+using System.Text;
+
+#if (SILVERLIGHT || PORTABLE)
+using System.Collections.Generic;
+#endif
+
+using Org.BouncyCastle.Asn1.Pkcs;
+using Org.BouncyCastle.Utilities;
+using Org.BouncyCastle.Utilities.Encoders;
+
+namespace Org.BouncyCastle.Asn1.X509
+{
+ /**
+ *
+ * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
+ *
+ * RelativeDistinguishedName ::= SET SIZE (1..MAX) OF AttributeTypeAndValue
+ *
+ * AttributeTypeAndValue ::= SEQUENCE {
+ * type OBJECT IDENTIFIER,
+ * value ANY }
+ *
+ */
+ public class X509Name
+ : Asn1Encodable
+ {
+ /**
+ * country code - StringType(SIZE(2))
+ */
+ public static readonly DerObjectIdentifier C = new DerObjectIdentifier("2.5.4.6");
+
+ /**
+ * organization - StringType(SIZE(1..64))
+ */
+ public static readonly DerObjectIdentifier O = new DerObjectIdentifier("2.5.4.10");
+
+ /**
+ * organizational unit name - StringType(SIZE(1..64))
+ */
+ public static readonly DerObjectIdentifier OU = new DerObjectIdentifier("2.5.4.11");
+
+ /**
+ * Title
+ */
+ public static readonly DerObjectIdentifier T = new DerObjectIdentifier("2.5.4.12");
+
+ /**
+ * common name - StringType(SIZE(1..64))
+ */
+ public static readonly DerObjectIdentifier CN = new DerObjectIdentifier("2.5.4.3");
+
+ /**
+ * street - StringType(SIZE(1..64))
+ */
+ public static readonly DerObjectIdentifier Street = new DerObjectIdentifier("2.5.4.9");
+
+ /**
+ * device serial number name - StringType(SIZE(1..64))
+ */
+ public static readonly DerObjectIdentifier SerialNumber = new DerObjectIdentifier("2.5.4.5");
+
+ /**
+ * locality name - StringType(SIZE(1..64))
+ */
+ public static readonly DerObjectIdentifier L = new DerObjectIdentifier("2.5.4.7");
+
+ /**
+ * state, or province name - StringType(SIZE(1..64))
+ */
+ public static readonly DerObjectIdentifier ST = new DerObjectIdentifier("2.5.4.8");
+
+ /**
+ * Naming attributes of type X520name
+ */
+ public static readonly DerObjectIdentifier Surname = new DerObjectIdentifier("2.5.4.4");
+ public static readonly DerObjectIdentifier GivenName = new DerObjectIdentifier("2.5.4.42");
+ public static readonly DerObjectIdentifier Initials = new DerObjectIdentifier("2.5.4.43");
+ public static readonly DerObjectIdentifier Generation = new DerObjectIdentifier("2.5.4.44");
+ public static readonly DerObjectIdentifier UniqueIdentifier = new DerObjectIdentifier("2.5.4.45");
+
+ /**
+ * businessCategory - DirectoryString(SIZE(1..128)
+ */
+ public static readonly DerObjectIdentifier BusinessCategory = new DerObjectIdentifier(
+ "2.5.4.15");
+
+ /**
+ * postalCode - DirectoryString(SIZE(1..40)
+ */
+ public static readonly DerObjectIdentifier PostalCode = new DerObjectIdentifier(
+ "2.5.4.17");
+
+ /**
+ * dnQualifier - DirectoryString(SIZE(1..64)
+ */
+ public static readonly DerObjectIdentifier DnQualifier = new DerObjectIdentifier(
+ "2.5.4.46");
+
+ /**
+ * RFC 3039 Pseudonym - DirectoryString(SIZE(1..64)
+ */
+ public static readonly DerObjectIdentifier Pseudonym = new DerObjectIdentifier(
+ "2.5.4.65");
+
+ /**
+ * RFC 3039 DateOfBirth - GeneralizedTime - YYYYMMDD000000Z
+ */
+ public static readonly DerObjectIdentifier DateOfBirth = new DerObjectIdentifier(
+ "1.3.6.1.5.5.7.9.1");
+
+ /**
+ * RFC 3039 PlaceOfBirth - DirectoryString(SIZE(1..128)
+ */
+ public static readonly DerObjectIdentifier PlaceOfBirth = new DerObjectIdentifier(
+ "1.3.6.1.5.5.7.9.2");
+
+ /**
+ * RFC 3039 DateOfBirth - PrintableString (SIZE(1)) -- "M", "F", "m" or "f"
+ */
+ public static readonly DerObjectIdentifier Gender = new DerObjectIdentifier(
+ "1.3.6.1.5.5.7.9.3");
+
+ /**
+ * RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166
+ * codes only
+ */
+ public static readonly DerObjectIdentifier CountryOfCitizenship = new DerObjectIdentifier(
+ "1.3.6.1.5.5.7.9.4");
+
+ /**
+ * RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166
+ * codes only
+ */
+ public static readonly DerObjectIdentifier CountryOfResidence = new DerObjectIdentifier(
+ "1.3.6.1.5.5.7.9.5");
+
+ /**
+ * ISIS-MTT NameAtBirth - DirectoryString(SIZE(1..64)
+ */
+ public static readonly DerObjectIdentifier NameAtBirth = new DerObjectIdentifier("1.3.36.8.3.14");
+
+ /**
+ * RFC 3039 PostalAddress - SEQUENCE SIZE (1..6) OF
+ * DirectoryString(SIZE(1..30))
+ */
+ public static readonly DerObjectIdentifier PostalAddress = new DerObjectIdentifier("2.5.4.16");
+
+ /**
+ * RFC 2256 dmdName
+ */
+ public static readonly DerObjectIdentifier DmdName = new DerObjectIdentifier("2.5.4.54");
+
+ /**
+ * id-at-telephoneNumber
+ */
+ public static readonly DerObjectIdentifier TelephoneNumber = X509ObjectIdentifiers.id_at_telephoneNumber;
+
+ /**
+ * id-at-name
+ */
+ public static readonly DerObjectIdentifier 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 readonly DerObjectIdentifier EmailAddress = PkcsObjectIdentifiers.Pkcs9AtEmailAddress;
+
+ /**
+ * more from PKCS#9
+ */
+ public static readonly DerObjectIdentifier UnstructuredName = PkcsObjectIdentifiers.Pkcs9AtUnstructuredName;
+ public static readonly DerObjectIdentifier UnstructuredAddress = PkcsObjectIdentifiers.Pkcs9AtUnstructuredAddress;
+
+ /**
+ * email address in Verisign certificates
+ */
+ public static readonly DerObjectIdentifier E = EmailAddress;
+
+ /*
+ * others...
+ */
+ public static readonly DerObjectIdentifier DC = new DerObjectIdentifier("0.9.2342.19200300.100.1.25");
+
+ /**
+ * LDAP User id.
+ */
+ public static readonly DerObjectIdentifier UID = new DerObjectIdentifier("0.9.2342.19200300.100.1.1");
+
+ /**
+ * determines whether or not strings should be processed and printed
+ * from back to front.
+ */
+// public static bool DefaultReverse = false;
+ public static bool DefaultReverse
+ {
+ get { return defaultReverse[0]; }
+ set { defaultReverse[0] = value; }
+ }
+
+ private static readonly bool[] defaultReverse = { false };
+
+#if (SILVERLIGHT || PORTABLE)
+ /**
+ * default look up table translating OID values into their common symbols following
+ * the convention in RFC 2253 with a few extras
+ */
+ public static readonly IDictionary DefaultSymbols = Platform.CreateHashtable();
+
+ /**
+ * look up table translating OID values into their common symbols following the convention in RFC 2253
+ */
+ public static readonly IDictionary RFC2253Symbols = Platform.CreateHashtable();
+
+ /**
+ * look up table translating OID values into their common symbols following the convention in RFC 1779
+ *
+ */
+ public static readonly IDictionary RFC1779Symbols = Platform.CreateHashtable();
+
+ /**
+ * look up table translating common symbols into their OIDS.
+ */
+ public static readonly IDictionary DefaultLookup = Platform.CreateHashtable();
+#else
+ /**
+ * default look up table translating OID values into their common symbols following
+ * the convention in RFC 2253 with a few extras
+ */
+ public static readonly Hashtable DefaultSymbols = new Hashtable();
+
+ /**
+ * look up table translating OID values into their common symbols following the convention in RFC 2253
+ */
+ public static readonly Hashtable RFC2253Symbols = new Hashtable();
+
+ /**
+ * look up table translating OID values into their common symbols following the convention in RFC 1779
+ *
+ */
+ public static readonly Hashtable RFC1779Symbols = new Hashtable();
+
+ /**
+ * look up table translating common symbols into their OIDS.
+ */
+ public static readonly Hashtable DefaultLookup = new Hashtable();
+#endif
+
+ static X509Name()
+ {
+ DefaultSymbols.Add(C, "C");
+ DefaultSymbols.Add(O, "O");
+ DefaultSymbols.Add(T, "T");
+ DefaultSymbols.Add(OU, "OU");
+ DefaultSymbols.Add(CN, "CN");
+ DefaultSymbols.Add(L, "L");
+ DefaultSymbols.Add(ST, "ST");
+ DefaultSymbols.Add(SerialNumber, "SERIALNUMBER");
+ DefaultSymbols.Add(EmailAddress, "E");
+ DefaultSymbols.Add(DC, "DC");
+ DefaultSymbols.Add(UID, "UID");
+ DefaultSymbols.Add(Street, "STREET");
+ DefaultSymbols.Add(Surname, "SURNAME");
+ DefaultSymbols.Add(GivenName, "GIVENNAME");
+ DefaultSymbols.Add(Initials, "INITIALS");
+ DefaultSymbols.Add(Generation, "GENERATION");
+ DefaultSymbols.Add(UnstructuredAddress, "unstructuredAddress");
+ DefaultSymbols.Add(UnstructuredName, "unstructuredName");
+ DefaultSymbols.Add(UniqueIdentifier, "UniqueIdentifier");
+ DefaultSymbols.Add(DnQualifier, "DN");
+ DefaultSymbols.Add(Pseudonym, "Pseudonym");
+ DefaultSymbols.Add(PostalAddress, "PostalAddress");
+ DefaultSymbols.Add(NameAtBirth, "NameAtBirth");
+ DefaultSymbols.Add(CountryOfCitizenship, "CountryOfCitizenship");
+ DefaultSymbols.Add(CountryOfResidence, "CountryOfResidence");
+ DefaultSymbols.Add(Gender, "Gender");
+ DefaultSymbols.Add(PlaceOfBirth, "PlaceOfBirth");
+ DefaultSymbols.Add(DateOfBirth, "DateOfBirth");
+ DefaultSymbols.Add(PostalCode, "PostalCode");
+ DefaultSymbols.Add(BusinessCategory, "BusinessCategory");
+ DefaultSymbols.Add(TelephoneNumber, "TelephoneNumber");
+
+ RFC2253Symbols.Add(C, "C");
+ RFC2253Symbols.Add(O, "O");
+ RFC2253Symbols.Add(OU, "OU");
+ RFC2253Symbols.Add(CN, "CN");
+ RFC2253Symbols.Add(L, "L");
+ RFC2253Symbols.Add(ST, "ST");
+ RFC2253Symbols.Add(Street, "STREET");
+ RFC2253Symbols.Add(DC, "DC");
+ RFC2253Symbols.Add(UID, "UID");
+
+ RFC1779Symbols.Add(C, "C");
+ RFC1779Symbols.Add(O, "O");
+ RFC1779Symbols.Add(OU, "OU");
+ RFC1779Symbols.Add(CN, "CN");
+ RFC1779Symbols.Add(L, "L");
+ RFC1779Symbols.Add(ST, "ST");
+ RFC1779Symbols.Add(Street, "STREET");
+
+ DefaultLookup.Add("c", C);
+ DefaultLookup.Add("o", O);
+ DefaultLookup.Add("t", T);
+ DefaultLookup.Add("ou", OU);
+ DefaultLookup.Add("cn", CN);
+ DefaultLookup.Add("l", L);
+ DefaultLookup.Add("st", ST);
+ DefaultLookup.Add("serialnumber", SerialNumber);
+ DefaultLookup.Add("street", Street);
+ DefaultLookup.Add("emailaddress", E);
+ DefaultLookup.Add("dc", DC);
+ DefaultLookup.Add("e", E);
+ DefaultLookup.Add("uid", UID);
+ DefaultLookup.Add("surname", Surname);
+ DefaultLookup.Add("givenname", GivenName);
+ DefaultLookup.Add("initials", Initials);
+ DefaultLookup.Add("generation", Generation);
+ DefaultLookup.Add("unstructuredaddress", UnstructuredAddress);
+ DefaultLookup.Add("unstructuredname", UnstructuredName);
+ DefaultLookup.Add("uniqueidentifier", UniqueIdentifier);
+ DefaultLookup.Add("dn", DnQualifier);
+ DefaultLookup.Add("pseudonym", Pseudonym);
+ DefaultLookup.Add("postaladdress", PostalAddress);
+ DefaultLookup.Add("nameofbirth", NameAtBirth);
+ DefaultLookup.Add("countryofcitizenship", CountryOfCitizenship);
+ DefaultLookup.Add("countryofresidence", CountryOfResidence);
+ DefaultLookup.Add("gender", Gender);
+ DefaultLookup.Add("placeofbirth", PlaceOfBirth);
+ DefaultLookup.Add("dateofbirth", DateOfBirth);
+ DefaultLookup.Add("postalcode", PostalCode);
+ DefaultLookup.Add("businesscategory", BusinessCategory);
+ DefaultLookup.Add("telephonenumber", TelephoneNumber);
+ }
+
+ private readonly IList ordering = Platform.CreateArrayList();
+ private readonly X509NameEntryConverter converter;
+
+ private IList values = Platform.CreateArrayList();
+ private IList added = Platform.CreateArrayList();
+ private Asn1Sequence seq;
+
+ /**
+ * Return a X509Name based on the passed in tagged object.
+ *
+ * @param obj tag object holding name.
+ * @param explicitly true if explicitly tagged false otherwise.
+ * @return the X509Name
+ */
+ public static X509Name GetInstance(
+ Asn1TaggedObject obj,
+ bool explicitly)
+ {
+ return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
+ }
+
+ public static X509Name GetInstance(
+ object obj)
+ {
+ if (obj == null || obj is X509Name)
+ return (X509Name)obj;
+
+ if (obj != null)
+ return new X509Name(Asn1Sequence.GetInstance(obj));
+
+ throw new ArgumentException("null object in factory", "obj");
+ }
+
+ protected X509Name()
+ {
+ }
+
+ /**
+ * Constructor from Asn1Sequence
+ *
+ * the principal will be a list of constructed sets, each containing an (OID, string) pair.
+ */
+ protected X509Name(
+ Asn1Sequence seq)
+ {
+ this.seq = seq;
+
+ foreach (Asn1Encodable asn1Obj in seq)
+ {
+ Asn1Set asn1Set = Asn1Set.GetInstance(asn1Obj.ToAsn1Object());
+
+ for (int i = 0; i < asn1Set.Count; i++)
+ {
+ Asn1Sequence s = Asn1Sequence.GetInstance(asn1Set[i].ToAsn1Object());
+
+ if (s.Count != 2)
+ throw new ArgumentException("badly sized pair");
+
+ ordering.Add(DerObjectIdentifier.GetInstance(s[0].ToAsn1Object()));
+
+ Asn1Object derValue = s[1].ToAsn1Object();
+ if (derValue is IAsn1String && !(derValue is DerUniversalString))
+ {
+ string v = ((IAsn1String)derValue).GetString();
+ if (v.StartsWith("#"))
+ {
+ v = "\\" + v;
+ }
+
+ values.Add(v);
+ }
+ else
+ {
+ values.Add("#" + Hex.ToHexString(derValue.GetEncoded()));
+ }
+
+ added.Add(i != 0);
+ }
+ }
+ }
+
+#if !(SILVERLIGHT || PORTABLE)
+ [Obsolete]
+ public X509Name(
+ ArrayList ordering,
+ Hashtable attributes)
+ : this(ordering, attributes, new X509DefaultEntryConverter())
+ {
+ }
+#endif
+
+ /**
+ * Constructor from a table of attributes with ordering.
+ *
+ * it's is assumed the table contains OID/string pairs, and the contents
+ * of the table are copied into an internal table as part of the
+ * construction process. The ordering ArrayList should contain the OIDs
+ * in the order they are meant to be encoded or printed in ToString.
+ */
+ public X509Name(
+ IList ordering,
+ IDictionary attributes)
+ : this(ordering, attributes, new X509DefaultEntryConverter())
+ {
+ }
+
+#if !(SILVERLIGHT || PORTABLE)
+ [Obsolete]
+ public X509Name(
+ ArrayList ordering,
+ Hashtable attributes,
+ X509NameEntryConverter converter)
+ : this((IList)ordering, (IDictionary)attributes, converter)
+ {
+ }
+#endif
+
+ /**
+ * Constructor from a table of attributes with ordering.
+ *
+ * it's is assumed the table contains OID/string pairs, and the contents
+ * of the table are copied into an internal table as part of the
+ * construction process. The ordering ArrayList should contain the OIDs
+ * in the order they are meant to be encoded or printed in ToString.
+ *
+ * The passed in converter will be used to convert the strings into their
+ * ASN.1 counterparts.
+ */
+ public X509Name(
+ IList ordering,
+ IDictionary attributes,
+ X509NameEntryConverter converter)
+ {
+ this.converter = converter;
+
+ foreach (DerObjectIdentifier oid in ordering)
+ {
+ object attribute = attributes[oid];
+ if (attribute == null)
+ {
+ throw new ArgumentException("No attribute for object id - " + oid + " - passed to distinguished name");
+ }
+
+ this.ordering.Add(oid);
+ this.added.Add(false);
+ this.values.Add(attribute); // copy the hash table
+ }
+ }
+
+#if !(SILVERLIGHT || PORTABLE)
+ [Obsolete]
+ public X509Name(
+ ArrayList oids,
+ ArrayList values)
+ : this(oids, values, new X509DefaultEntryConverter())
+ {
+ }
+#endif
+
+ /**
+ * Takes two vectors one of the oids and the other of the values.
+ */
+ public X509Name(
+ IList oids,
+ IList values)
+ : this(oids, values, new X509DefaultEntryConverter())
+ {
+ }
+
+#if !(SILVERLIGHT || PORTABLE)
+ [Obsolete]
+ public X509Name(
+ ArrayList oids,
+ ArrayList values,
+ X509NameEntryConverter converter)
+ : this((IList)oids, (IList)values, converter)
+ {
+ }
+#endif
+
+ /**
+ * Takes two vectors one of the oids and the other of the values.
+ *
+ * The passed in converter will be used to convert the strings into their
+ * ASN.1 counterparts.
+ */
+ public X509Name(
+ IList oids,
+ IList values,
+ X509NameEntryConverter converter)
+ {
+ this.converter = converter;
+
+ if (oids.Count != values.Count)
+ {
+ throw new ArgumentException("'oids' must be same length as 'values'.");
+ }
+
+ for (int i = 0; i < oids.Count; i++)
+ {
+ this.ordering.Add(oids[i]);
+ this.values.Add(values[i]);
+ this.added.Add(false);
+ }
+ }
+
+// private static bool IsEncoded(
+// string s)
+// {
+// return s.StartsWith("#");
+// }
+
+ /**
+ * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ * some such, converting it into an ordered set of name attributes.
+ */
+ public X509Name(
+ string dirName)
+ : this(DefaultReverse, (IDictionary)DefaultLookup, dirName)
+ {
+ }
+
+ /**
+ * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ * some such, converting it into an ordered set of name attributes with each
+ * string value being converted to its associated ASN.1 type using the passed
+ * in converter.
+ */
+ public X509Name(
+ string dirName,
+ X509NameEntryConverter converter)
+ : this(DefaultReverse, DefaultLookup, dirName, converter)
+ {
+ }
+
+ /**
+ * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ * some such, converting it into an ordered set of name attributes. If reverse
+ * is true, create the encoded version of the sequence starting from the
+ * last element in the string.
+ */
+ public X509Name(
+ bool reverse,
+ string dirName)
+ : this(reverse, (IDictionary)DefaultLookup, dirName)
+ {
+ }
+
+ /**
+ * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ * some such, converting it into an ordered set of name attributes with each
+ * string value being converted to its associated ASN.1 type using the passed
+ * in converter. If reverse is true the ASN.1 sequence representing the DN will
+ * be built by starting at the end of the string, rather than the start.
+ */
+ public X509Name(
+ bool reverse,
+ string dirName,
+ X509NameEntryConverter converter)
+ : this(reverse, DefaultLookup, dirName, converter)
+ {
+ }
+
+#if !(SILVERLIGHT || PORTABLE)
+ [Obsolete]
+ public X509Name(
+ bool reverse,
+ Hashtable lookUp,
+ string dirName)
+ : this(reverse, lookUp, dirName, new X509DefaultEntryConverter())
+ {
+ }
+#endif
+
+ /**
+ * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ * some such, converting it into an ordered set of name attributes. lookUp
+ * should provide a table of lookups, indexed by lowercase only strings and
+ * yielding a DerObjectIdentifier, other than that OID. and numeric oids
+ * will be processed automatically.
+ *
+ * If reverse is true, create the encoded version of the sequence
+ * starting from the last element in the string.
+ * @param reverse true if we should start scanning from the end (RFC 2553).
+ * @param lookUp table of names and their oids.
+ * @param dirName the X.500 string to be parsed.
+ */
+ public X509Name(
+ bool reverse,
+ IDictionary lookUp,
+ string dirName)
+ : this(reverse, lookUp, dirName, new X509DefaultEntryConverter())
+ {
+ }
+
+ private DerObjectIdentifier DecodeOid(
+ string name,
+ IDictionary lookUp)
+ {
+ if (name.ToUpperInvariant().StartsWith("OID."))
+ {
+ return new DerObjectIdentifier(name.Substring(4));
+ }
+ else if (name[0] >= '0' && name[0] <= '9')
+ {
+ return new DerObjectIdentifier(name);
+ }
+
+ DerObjectIdentifier oid = (DerObjectIdentifier)lookUp[name.ToLowerInvariant()];
+ if (oid == null)
+ {
+ throw new ArgumentException("Unknown object id - " + name + " - passed to distinguished name");
+ }
+
+ return oid;
+ }
+
+ /**
+ * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
+ * some such, converting it into an ordered set of name attributes. lookUp
+ * should provide a table of lookups, indexed by lowercase only strings and
+ * yielding a DerObjectIdentifier, other than that OID. and numeric oids
+ * will be processed automatically. The passed in converter is used to convert the
+ * string values to the right of each equals sign to their ASN.1 counterparts.
+ *
+ * @param reverse true if we should start scanning from the end, false otherwise.
+ * @param lookUp table of names and oids.
+ * @param dirName the string dirName
+ * @param converter the converter to convert string values into their ASN.1 equivalents
+ */
+ public X509Name(
+ bool reverse,
+ IDictionary lookUp,
+ string dirName,
+ X509NameEntryConverter converter)
+ {
+ this.converter = converter;
+ X509NameTokenizer nTok = new X509NameTokenizer(dirName);
+
+ while (nTok.HasMoreTokens())
+ {
+ string token = nTok.NextToken();
+ int index = token.IndexOf('=');
+
+ if (index == -1)
+ {
+ throw new ArgumentException("badly formated directory string");
+ }
+
+ string name = token.Substring(0, index);
+ string value = token.Substring(index + 1);
+ DerObjectIdentifier oid = DecodeOid(name, lookUp);
+
+ if (value.IndexOf('+') > 0)
+ {
+ X509NameTokenizer vTok = new X509NameTokenizer(value, '+');
+ string v = vTok.NextToken();
+
+ this.ordering.Add(oid);
+ this.values.Add(v);
+ this.added.Add(false);
+
+ while (vTok.HasMoreTokens())
+ {
+ string sv = vTok.NextToken();
+ int ndx = sv.IndexOf('=');
+
+ string nm = sv.Substring(0, ndx);
+ string vl = sv.Substring(ndx + 1);
+ this.ordering.Add(DecodeOid(nm, lookUp));
+ this.values.Add(vl);
+ this.added.Add(true);
+ }
+ }
+ else
+ {
+ this.ordering.Add(oid);
+ this.values.Add(value);
+ this.added.Add(false);
+ }
+ }
+
+ if (reverse)
+ {
+// this.ordering.Reverse();
+// this.values.Reverse();
+// this.added.Reverse();
+ IList o = Platform.CreateArrayList();
+ IList v = Platform.CreateArrayList();
+ IList a = Platform.CreateArrayList();
+ int count = 1;
+
+ for (int i = 0; i < this.ordering.Count; i++)
+ {
+ if (!((bool) this.added[i]))
+ {
+ count = 0;
+ }
+
+ int index = count++;
+
+ o.Insert(index, this.ordering[i]);
+ v.Insert(index, this.values[i]);
+ a.Insert(index, this.added[i]);
+ }
+
+ this.ordering = o;
+ this.values = v;
+ this.added = a;
+ }
+ }
+
+#if !(SILVERLIGHT || PORTABLE)
+ /**
+ * return an ArrayList of the oids in the name, in the order they were found.
+ */
+ [Obsolete("Use 'GetOidList' instead")]
+ public ArrayList GetOids()
+ {
+ return new ArrayList(ordering);
+ }
+#endif
+
+ /**
+ * return an IList of the oids in the name, in the order they were found.
+ */
+ public IList GetOidList()
+ {
+ return Platform.CreateArrayList(ordering);
+ }
+
+#if !(SILVERLIGHT || PORTABLE)
+ /**
+ * return an ArrayList of the values found in the name, in the order they
+ * were found.
+ */
+ [Obsolete("Use 'GetValueList' instead")]
+ public ArrayList GetValues()
+ {
+ return new ArrayList(values);
+ }
+#endif
+
+ /**
+ * return an IList of the values found in the name, in the order they
+ * were found.
+ */
+ public IList GetValueList()
+ {
+ return Platform.CreateArrayList(values);
+ }
+
+#if !(SILVERLIGHT || PORTABLE)
+ /**
+ * return an ArrayList of the values found in the name, in the order they
+ * were found, with the DN label corresponding to passed in oid.
+ */
+ public ArrayList GetValues(
+ DerObjectIdentifier oid)
+ {
+ ArrayList v = new ArrayList();
+ DoGetValueList(oid, v);
+ return v;
+ }
+#endif
+
+ /**
+ * return an IList of the values found in the name, in the order they
+ * were found, with the DN label corresponding to passed in oid.
+ */
+ public IList GetValueList(DerObjectIdentifier oid)
+ {
+ IList v = Platform.CreateArrayList();
+ DoGetValueList(oid, v);
+ return v;
+ }
+
+ private void DoGetValueList(DerObjectIdentifier oid, IList v)
+ {
+ for (int i = 0; i != values.Count; i++)
+ {
+ if (ordering[i].Equals(oid))
+ {
+ string val = (string)values[i];
+
+ if (val.StartsWith("\\#"))
+ {
+ val = val.Substring(1);
+ }
+
+ v.Add(val);
+ }
+ }
+ }
+
+ public override Asn1Object ToAsn1Object()
+ {
+ if (seq == null)
+ {
+ Asn1EncodableVector vec = new Asn1EncodableVector();
+ Asn1EncodableVector sVec = new Asn1EncodableVector();
+ DerObjectIdentifier lstOid = null;
+
+ for (int i = 0; i != ordering.Count; i++)
+ {
+ DerObjectIdentifier oid = (DerObjectIdentifier)ordering[i];
+ string str = (string)values[i];
+
+ if (lstOid == null
+ || ((bool)this.added[i]))
+ {
+ }
+ else
+ {
+ vec.Add(new DerSet(sVec));
+ sVec = new Asn1EncodableVector();
+ }
+
+ sVec.Add(
+ new DerSequence(
+ oid,
+ converter.GetConvertedValue(oid, str)));
+
+ lstOid = oid;
+ }
+
+ vec.Add(new DerSet(sVec));
+
+ seq = new DerSequence(vec);
+ }
+
+ return seq;
+ }
+
+ /// The X509Name object to test equivalency against.
+ /// If true, the order of elements must be the same,
+ /// as well as the values associated with each element.
+ public bool Equivalent(
+ X509Name other,
+ bool inOrder)
+ {
+ if (!inOrder)
+ return this.Equivalent(other);
+
+ if (other == null)
+ return false;
+
+ if (other == this)
+ return true;
+
+ int orderingSize = ordering.Count;
+
+ if (orderingSize != other.ordering.Count)
+ return false;
+
+ for (int i = 0; i < orderingSize; i++)
+ {
+ DerObjectIdentifier oid = (DerObjectIdentifier) ordering[i];
+ DerObjectIdentifier oOid = (DerObjectIdentifier) other.ordering[i];
+
+ if (!oid.Equals(oOid))
+ return false;
+
+ string val = (string) values[i];
+ string oVal = (string) other.values[i];
+
+ if (!equivalentStrings(val, oVal))
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * test for equivalence - note: case is ignored.
+ */
+ public bool Equivalent(
+ X509Name other)
+ {
+ if (other == null)
+ return false;
+
+ if (other == this)
+ return true;
+
+ int orderingSize = ordering.Count;
+
+ if (orderingSize != other.ordering.Count)
+ {
+ return false;
+ }
+
+ bool[] indexes = new bool[orderingSize];
+ int start, end, delta;
+
+ if (ordering[0].Equals(other.ordering[0])) // guess forward
+ {
+ start = 0;
+ end = orderingSize;
+ delta = 1;
+ }
+ else // guess reversed - most common problem
+ {
+ start = orderingSize - 1;
+ end = -1;
+ delta = -1;
+ }
+
+ for (int i = start; i != end; i += delta)
+ {
+ bool found = false;
+ DerObjectIdentifier oid = (DerObjectIdentifier)ordering[i];
+ string value = (string)values[i];
+
+ for (int j = 0; j < orderingSize; j++)
+ {
+ if (indexes[j])
+ {
+ continue;
+ }
+
+ DerObjectIdentifier oOid = (DerObjectIdentifier)other.ordering[j];
+
+ if (oid.Equals(oOid))
+ {
+ string oValue = (string)other.values[j];
+
+ if (equivalentStrings(value, oValue))
+ {
+ indexes[j] = true;
+ found = true;
+ break;
+ }
+ }
+ }
+
+ if (!found)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static bool equivalentStrings(
+ string s1,
+ string s2)
+ {
+ string v1 = canonicalize(s1);
+ string v2 = canonicalize(s2);
+
+ if (!v1.Equals(v2))
+ {
+ v1 = stripInternalSpaces(v1);
+ v2 = stripInternalSpaces(v2);
+
+ if (!v1.Equals(v2))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static string canonicalize(
+ string s)
+ {
+ string v = s.ToLowerInvariant().Trim();
+
+ if (v.StartsWith("#"))
+ {
+ Asn1Object obj = decodeObject(v);
+
+ if (obj is IAsn1String)
+ {
+ v = ((IAsn1String)obj).GetString().ToLowerInvariant().Trim();
+ }
+ }
+
+ return v;
+ }
+
+ private static Asn1Object decodeObject(
+ string v)
+ {
+ try
+ {
+ return Asn1Object.FromByteArray(Hex.Decode(v.Substring(1)));
+ }
+ catch (IOException e)
+ {
+ throw new InvalidOperationException("unknown encoding in name: " + e.Message, e);
+ }
+ }
+
+ private static string stripInternalSpaces(
+ string str)
+ {
+ StringBuilder res = new StringBuilder();
+
+ if (str.Length != 0)
+ {
+ char c1 = str[0];
+
+ res.Append(c1);
+
+ for (int k = 1; k < str.Length; k++)
+ {
+ char c2 = str[k];
+ if (!(c1 == ' ' && c2 == ' '))
+ {
+ res.Append(c2);
+ }
+ c1 = c2;
+ }
+ }
+
+ return res.ToString();
+ }
+
+ private void AppendValue(
+ StringBuilder buf,
+ IDictionary oidSymbols,
+ DerObjectIdentifier oid,
+ string val)
+ {
+ string sym = (string)oidSymbols[oid];
+
+ if (sym != null)
+ {
+ buf.Append(sym);
+ }
+ else
+ {
+ buf.Append(oid.Id);
+ }
+
+ buf.Append('=');
+
+ int index = buf.Length;
+
+ buf.Append(val);
+
+ int end = buf.Length;
+
+ if (val.StartsWith("\\#"))
+ {
+ index += 2;
+ }
+
+ while (index != end)
+ {
+ if ((buf[index] == ',')
+ || (buf[index] == '"')
+ || (buf[index] == '\\')
+ || (buf[index] == '+')
+ || (buf[index] == '=')
+ || (buf[index] == '<')
+ || (buf[index] == '>')
+ || (buf[index] == ';'))
+ {
+ buf.Insert(index++, "\\");
+ end++;
+ }
+
+ index++;
+ }
+ }
+
+#if !(SILVERLIGHT || PORTABLE)
+ [Obsolete]
+ public string ToString(
+ bool reverse,
+ Hashtable oidSymbols)
+ {
+ return ToString(reverse, (IDictionary)oidSymbols);
+ }
+#endif
+
+ /**
+ * convert the structure to a string - if reverse is true the
+ * oids and values are listed out starting with the last element
+ * in the sequence (ala RFC 2253), otherwise the string will begin
+ * with the first element of the structure. If no string definition
+ * for the oid is found in oidSymbols the string value of the oid is
+ * added. Two standard symbol tables are provided DefaultSymbols, and
+ * RFC2253Symbols as part of this class.
+ *
+ * @param reverse if true start at the end of the sequence and work back.
+ * @param oidSymbols look up table strings for oids.
+ */
+ public string ToString(
+ bool reverse,
+ IDictionary oidSymbols)
+ {
+#if (SILVERLIGHT || PORTABLE)
+ List