Commit 47ce503f 47ce503ff6f91b15a08391b1252362b49ea959ad by Christian Gerdes

Added The Bouncy Castle C# Cryptographic API as a project

1 parent 7d536c29
Showing 1000 changed files with 4872 additions and 0 deletions

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

...@@ -15,6 +15,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LIL_VSTT_Plugins", "LIL_VST ...@@ -15,6 +15,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LIL_VSTT_Plugins", "LIL_VST
15 EndProject 15 EndProject
16 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestProject1", "TestProject1\TestProject1.csproj", "{01CF59F6-F912-447A-91BC-0301FDA09C02}" 16 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestProject1", "TestProject1\TestProject1.csproj", "{01CF59F6-F912-447A-91BC-0301FDA09C02}"
17 EndProject 17 EndProject
18 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "crypto.Net45", "crypto\crypto.Net45.csproj", "{45473847-8AF8-4BAF-B768-442C6875B8CF}"
19 EndProject
18 Global 20 Global
19 GlobalSection(SolutionConfigurationPlatforms) = preSolution 21 GlobalSection(SolutionConfigurationPlatforms) = preSolution
20 Debug|Any CPU = Debug|Any CPU 22 Debug|Any CPU = Debug|Any CPU
...@@ -29,6 +31,10 @@ Global ...@@ -29,6 +31,10 @@ Global
29 {01CF59F6-F912-447A-91BC-0301FDA09C02}.Debug|Any CPU.Build.0 = Debug|Any CPU 31 {01CF59F6-F912-447A-91BC-0301FDA09C02}.Debug|Any CPU.Build.0 = Debug|Any CPU
30 {01CF59F6-F912-447A-91BC-0301FDA09C02}.Release|Any CPU.ActiveCfg = Release|Any CPU 32 {01CF59F6-F912-447A-91BC-0301FDA09C02}.Release|Any CPU.ActiveCfg = Release|Any CPU
31 {01CF59F6-F912-447A-91BC-0301FDA09C02}.Release|Any CPU.Build.0 = Release|Any CPU 33 {01CF59F6-F912-447A-91BC-0301FDA09C02}.Release|Any CPU.Build.0 = Release|Any CPU
34 {45473847-8AF8-4BAF-B768-442C6875B8CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
35 {45473847-8AF8-4BAF-B768-442C6875B8CF}.Debug|Any CPU.Build.0 = Debug|Any CPU
36 {45473847-8AF8-4BAF-B768-442C6875B8CF}.Release|Any CPU.ActiveCfg = Release|Any CPU
37 {45473847-8AF8-4BAF-B768-442C6875B8CF}.Release|Any CPU.Build.0 = Release|Any CPU
32 EndGlobalSection 38 EndGlobalSection
33 GlobalSection(SolutionProperties) = preSolution 39 GlobalSection(SolutionProperties) = preSolution
34 HideSolutionNode = FALSE 40 HideSolutionNode = FALSE
......
1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 /*
20 * This package is based on the work done by Keiron Liddle, Aftex Software
21 * <keiron@aftexsw.com> to whom the Ant project is very grateful for his
22 * great code.
23 */
24
25 using System;
26
27 namespace Org.BouncyCastle.Apache.Bzip2
28 {
29 /**
30 * Base class for both the compress and decompress classes.
31 * Holds common arrays, and static data.
32 *
33 * @author <a href="mailto:keiron@aftexsw.com">Keiron Liddle</a>
34 */
35 public class BZip2Constants {
36
37 public const int baseBlockSize = 100000;
38 public const int MAX_ALPHA_SIZE = 258;
39 public const int MAX_CODE_LEN = 23;
40 public const int RUNA = 0;
41 public const int RUNB = 1;
42 public const int N_GROUPS = 6;
43 public const int G_SIZE = 50;
44 public const int N_ITERS = 4;
45 public const int MAX_SELECTORS = (2 + (900000 / G_SIZE));
46 public const int NUM_OVERSHOOT_BYTES = 20;
47
48 public static readonly int[] rNums = {
49 619, 720, 127, 481, 931, 816, 813, 233, 566, 247,
50 985, 724, 205, 454, 863, 491, 741, 242, 949, 214,
51 733, 859, 335, 708, 621, 574, 73, 654, 730, 472,
52 419, 436, 278, 496, 867, 210, 399, 680, 480, 51,
53 878, 465, 811, 169, 869, 675, 611, 697, 867, 561,
54 862, 687, 507, 283, 482, 129, 807, 591, 733, 623,
55 150, 238, 59, 379, 684, 877, 625, 169, 643, 105,
56 170, 607, 520, 932, 727, 476, 693, 425, 174, 647,
57 73, 122, 335, 530, 442, 853, 695, 249, 445, 515,
58 909, 545, 703, 919, 874, 474, 882, 500, 594, 612,
59 641, 801, 220, 162, 819, 984, 589, 513, 495, 799,
60 161, 604, 958, 533, 221, 400, 386, 867, 600, 782,
61 382, 596, 414, 171, 516, 375, 682, 485, 911, 276,
62 98, 553, 163, 354, 666, 933, 424, 341, 533, 870,
63 227, 730, 475, 186, 263, 647, 537, 686, 600, 224,
64 469, 68, 770, 919, 190, 373, 294, 822, 808, 206,
65 184, 943, 795, 384, 383, 461, 404, 758, 839, 887,
66 715, 67, 618, 276, 204, 918, 873, 777, 604, 560,
67 951, 160, 578, 722, 79, 804, 96, 409, 713, 940,
68 652, 934, 970, 447, 318, 353, 859, 672, 112, 785,
69 645, 863, 803, 350, 139, 93, 354, 99, 820, 908,
70 609, 772, 154, 274, 580, 184, 79, 626, 630, 742,
71 653, 282, 762, 623, 680, 81, 927, 626, 789, 125,
72 411, 521, 938, 300, 821, 78, 343, 175, 128, 250,
73 170, 774, 972, 275, 999, 639, 495, 78, 352, 126,
74 857, 956, 358, 619, 580, 124, 737, 594, 701, 612,
75 669, 112, 134, 694, 363, 992, 809, 743, 168, 974,
76 944, 375, 748, 52, 600, 747, 642, 182, 862, 81,
77 344, 805, 988, 739, 511, 655, 814, 334, 249, 515,
78 897, 955, 664, 981, 649, 113, 974, 459, 893, 228,
79 433, 837, 553, 268, 926, 240, 102, 654, 459, 51,
80 686, 754, 806, 760, 493, 403, 415, 394, 687, 700,
81 946, 670, 656, 610, 738, 392, 760, 799, 887, 653,
82 978, 321, 576, 617, 626, 502, 894, 679, 243, 440,
83 680, 879, 194, 572, 640, 724, 926, 56, 204, 700,
84 707, 151, 457, 449, 797, 195, 791, 558, 945, 679,
85 297, 59, 87, 824, 713, 663, 412, 693, 342, 606,
86 134, 108, 571, 364, 631, 212, 174, 643, 304, 329,
87 343, 97, 430, 751, 497, 314, 983, 374, 822, 928,
88 140, 206, 73, 263, 980, 736, 876, 478, 430, 305,
89 170, 514, 364, 692, 829, 82, 855, 953, 676, 246,
90 369, 970, 294, 750, 807, 827, 150, 790, 288, 923,
91 804, 378, 215, 828, 592, 281, 565, 555, 710, 82,
92 896, 831, 547, 261, 524, 462, 293, 465, 502, 56,
93 661, 821, 976, 991, 658, 869, 905, 758, 745, 193,
94 768, 550, 608, 933, 378, 286, 215, 979, 792, 961,
95 61, 688, 793, 644, 986, 403, 106, 366, 905, 644,
96 372, 567, 466, 434, 645, 210, 389, 550, 919, 135,
97 780, 773, 635, 389, 707, 100, 626, 958, 165, 504,
98 920, 176, 193, 713, 857, 265, 203, 50, 668, 108,
99 645, 990, 626, 197, 510, 357, 358, 850, 858, 364,
100 936, 638
101 };
102 }
103 }
...\ No newline at end of file ...\ No newline at end of file
1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 /*
20 * This package is based on the work done by Keiron Liddle), Aftex Software
21 * <keiron@aftexsw.com> to whom the Ant project is very grateful for his
22 * great code.
23 */
24
25 using System;
26
27 namespace Org.BouncyCastle.Apache.Bzip2
28 {
29 /**
30 * A simple class the hold and calculate the CRC for sanity checking
31 * of the data.
32 *
33 * @author <a href="mailto:keiron@aftexsw.com">Keiron Liddle</a>
34 */
35 internal class CRC
36 {
37 public static readonly int[] crc32Table = {
38 unchecked((int)0x00000000), unchecked((int)0x04c11db7), unchecked((int)0x09823b6e), unchecked((int)0x0d4326d9),
39 unchecked((int)0x130476dc), unchecked((int)0x17c56b6b), unchecked((int)0x1a864db2), unchecked((int)0x1e475005),
40 unchecked((int)0x2608edb8), unchecked((int)0x22c9f00f), unchecked((int)0x2f8ad6d6), unchecked((int)0x2b4bcb61),
41 unchecked((int)0x350c9b64), unchecked((int)0x31cd86d3), unchecked((int)0x3c8ea00a), unchecked((int)0x384fbdbd),
42 unchecked((int)0x4c11db70), unchecked((int)0x48d0c6c7), unchecked((int)0x4593e01e), unchecked((int)0x4152fda9),
43 unchecked((int)0x5f15adac), unchecked((int)0x5bd4b01b), unchecked((int)0x569796c2), unchecked((int)0x52568b75),
44 unchecked((int)0x6a1936c8), unchecked((int)0x6ed82b7f), unchecked((int)0x639b0da6), unchecked((int)0x675a1011),
45 unchecked((int)0x791d4014), unchecked((int)0x7ddc5da3), unchecked((int)0x709f7b7a), unchecked((int)0x745e66cd),
46 unchecked((int)0x9823b6e0), unchecked((int)0x9ce2ab57), unchecked((int)0x91a18d8e), unchecked((int)0x95609039),
47 unchecked((int)0x8b27c03c), unchecked((int)0x8fe6dd8b), unchecked((int)0x82a5fb52), unchecked((int)0x8664e6e5),
48 unchecked((int)0xbe2b5b58), unchecked((int)0xbaea46ef), unchecked((int)0xb7a96036), unchecked((int)0xb3687d81),
49 unchecked((int)0xad2f2d84), unchecked((int)0xa9ee3033), unchecked((int)0xa4ad16ea), unchecked((int)0xa06c0b5d),
50 unchecked((int)0xd4326d90), unchecked((int)0xd0f37027), unchecked((int)0xddb056fe), unchecked((int)0xd9714b49),
51 unchecked((int)0xc7361b4c), unchecked((int)0xc3f706fb), unchecked((int)0xceb42022), unchecked((int)0xca753d95),
52 unchecked((int)0xf23a8028), unchecked((int)0xf6fb9d9f), unchecked((int)0xfbb8bb46), unchecked((int)0xff79a6f1),
53 unchecked((int)0xe13ef6f4), unchecked((int)0xe5ffeb43), unchecked((int)0xe8bccd9a), unchecked((int)0xec7dd02d),
54 unchecked((int)0x34867077), unchecked((int)0x30476dc0), unchecked((int)0x3d044b19), unchecked((int)0x39c556ae),
55 unchecked((int)0x278206ab), unchecked((int)0x23431b1c), unchecked((int)0x2e003dc5), unchecked((int)0x2ac12072),
56 unchecked((int)0x128e9dcf), unchecked((int)0x164f8078), unchecked((int)0x1b0ca6a1), unchecked((int)0x1fcdbb16),
57 unchecked((int)0x018aeb13), unchecked((int)0x054bf6a4), unchecked((int)0x0808d07d), unchecked((int)0x0cc9cdca),
58 unchecked((int)0x7897ab07), unchecked((int)0x7c56b6b0), unchecked((int)0x71159069), unchecked((int)0x75d48dde),
59 unchecked((int)0x6b93dddb), unchecked((int)0x6f52c06c), unchecked((int)0x6211e6b5), unchecked((int)0x66d0fb02),
60 unchecked((int)0x5e9f46bf), unchecked((int)0x5a5e5b08), unchecked((int)0x571d7dd1), unchecked((int)0x53dc6066),
61 unchecked((int)0x4d9b3063), unchecked((int)0x495a2dd4), unchecked((int)0x44190b0d), unchecked((int)0x40d816ba),
62 unchecked((int)0xaca5c697), unchecked((int)0xa864db20), unchecked((int)0xa527fdf9), unchecked((int)0xa1e6e04e),
63 unchecked((int)0xbfa1b04b), unchecked((int)0xbb60adfc), unchecked((int)0xb6238b25), unchecked((int)0xb2e29692),
64 unchecked((int)0x8aad2b2f), unchecked((int)0x8e6c3698), unchecked((int)0x832f1041), unchecked((int)0x87ee0df6),
65 unchecked((int)0x99a95df3), unchecked((int)0x9d684044), unchecked((int)0x902b669d), unchecked((int)0x94ea7b2a),
66 unchecked((int)0xe0b41de7), unchecked((int)0xe4750050), unchecked((int)0xe9362689), unchecked((int)0xedf73b3e),
67 unchecked((int)0xf3b06b3b), unchecked((int)0xf771768c), unchecked((int)0xfa325055), unchecked((int)0xfef34de2),
68 unchecked((int)0xc6bcf05f), unchecked((int)0xc27dede8), unchecked((int)0xcf3ecb31), unchecked((int)0xcbffd686),
69 unchecked((int)0xd5b88683), unchecked((int)0xd1799b34), unchecked((int)0xdc3abded), unchecked((int)0xd8fba05a),
70 unchecked((int)0x690ce0ee), unchecked((int)0x6dcdfd59), unchecked((int)0x608edb80), unchecked((int)0x644fc637),
71 unchecked((int)0x7a089632), unchecked((int)0x7ec98b85), unchecked((int)0x738aad5c), unchecked((int)0x774bb0eb),
72 unchecked((int)0x4f040d56), unchecked((int)0x4bc510e1), unchecked((int)0x46863638), unchecked((int)0x42472b8f),
73 unchecked((int)0x5c007b8a), unchecked((int)0x58c1663d), unchecked((int)0x558240e4), unchecked((int)0x51435d53),
74 unchecked((int)0x251d3b9e), unchecked((int)0x21dc2629), unchecked((int)0x2c9f00f0), unchecked((int)0x285e1d47),
75 unchecked((int)0x36194d42), unchecked((int)0x32d850f5), unchecked((int)0x3f9b762c), unchecked((int)0x3b5a6b9b),
76 unchecked((int)0x0315d626), unchecked((int)0x07d4cb91), unchecked((int)0x0a97ed48), unchecked((int)0x0e56f0ff),
77 unchecked((int)0x1011a0fa), unchecked((int)0x14d0bd4d), unchecked((int)0x19939b94), unchecked((int)0x1d528623),
78 unchecked((int)0xf12f560e), unchecked((int)0xf5ee4bb9), unchecked((int)0xf8ad6d60), unchecked((int)0xfc6c70d7),
79 unchecked((int)0xe22b20d2), unchecked((int)0xe6ea3d65), unchecked((int)0xeba91bbc), unchecked((int)0xef68060b),
80 unchecked((int)0xd727bbb6), unchecked((int)0xd3e6a601), unchecked((int)0xdea580d8), unchecked((int)0xda649d6f),
81 unchecked((int)0xc423cd6a), unchecked((int)0xc0e2d0dd), unchecked((int)0xcda1f604), unchecked((int)0xc960ebb3),
82 unchecked((int)0xbd3e8d7e), unchecked((int)0xb9ff90c9), unchecked((int)0xb4bcb610), unchecked((int)0xb07daba7),
83 unchecked((int)0xae3afba2), unchecked((int)0xaafbe615), unchecked((int)0xa7b8c0cc), unchecked((int)0xa379dd7b),
84 unchecked((int)0x9b3660c6), unchecked((int)0x9ff77d71), unchecked((int)0x92b45ba8), unchecked((int)0x9675461f),
85 unchecked((int)0x8832161a), unchecked((int)0x8cf30bad), unchecked((int)0x81b02d74), unchecked((int)0x857130c3),
86 unchecked((int)0x5d8a9099), unchecked((int)0x594b8d2e), unchecked((int)0x5408abf7), unchecked((int)0x50c9b640),
87 unchecked((int)0x4e8ee645), unchecked((int)0x4a4ffbf2), unchecked((int)0x470cdd2b), unchecked((int)0x43cdc09c),
88 unchecked((int)0x7b827d21), unchecked((int)0x7f436096), unchecked((int)0x7200464f), unchecked((int)0x76c15bf8),
89 unchecked((int)0x68860bfd), unchecked((int)0x6c47164a), unchecked((int)0x61043093), unchecked((int)0x65c52d24),
90 unchecked((int)0x119b4be9), unchecked((int)0x155a565e), unchecked((int)0x18197087), unchecked((int)0x1cd86d30),
91 unchecked((int)0x029f3d35), unchecked((int)0x065e2082), unchecked((int)0x0b1d065b), unchecked((int)0x0fdc1bec),
92 unchecked((int)0x3793a651), unchecked((int)0x3352bbe6), unchecked((int)0x3e119d3f), unchecked((int)0x3ad08088),
93 unchecked((int)0x2497d08d), unchecked((int)0x2056cd3a), unchecked((int)0x2d15ebe3), unchecked((int)0x29d4f654),
94 unchecked((int)0xc5a92679), unchecked((int)0xc1683bce), unchecked((int)0xcc2b1d17), unchecked((int)0xc8ea00a0),
95 unchecked((int)0xd6ad50a5), unchecked((int)0xd26c4d12), unchecked((int)0xdf2f6bcb), unchecked((int)0xdbee767c),
96 unchecked((int)0xe3a1cbc1), unchecked((int)0xe760d676), unchecked((int)0xea23f0af), unchecked((int)0xeee2ed18),
97 unchecked((int)0xf0a5bd1d), unchecked((int)0xf464a0aa), unchecked((int)0xf9278673), unchecked((int)0xfde69bc4),
98 unchecked((int)0x89b8fd09), unchecked((int)0x8d79e0be), unchecked((int)0x803ac667), unchecked((int)0x84fbdbd0),
99 unchecked((int)0x9abc8bd5), unchecked((int)0x9e7d9662), unchecked((int)0x933eb0bb), unchecked((int)0x97ffad0c),
100 unchecked((int)0xafb010b1), unchecked((int)0xab710d06), unchecked((int)0xa6322bdf), unchecked((int)0xa2f33668),
101 unchecked((int)0xbcb4666d), unchecked((int)0xb8757bda), unchecked((int)0xb5365d03), unchecked((int)0xb1f740b4)
102 };
103
104 public CRC() {
105 InitialiseCRC();
106 }
107
108 internal void InitialiseCRC() {
109 globalCrc = unchecked((int)0xffffffff);
110 }
111
112 internal int GetFinalCRC() {
113 return ~globalCrc;
114 }
115
116 internal int GetGlobalCRC() {
117 return globalCrc;
118 }
119
120 internal void SetGlobalCRC(int newCrc) {
121 globalCrc = newCrc;
122 }
123
124 internal void UpdateCRC(int inCh) {
125 int temp = (globalCrc >> 24) ^ inCh;
126 if (temp < 0) {
127 temp = 256 + temp;
128 }
129 globalCrc = (globalCrc << 8) ^ CRC.crc32Table[temp];
130 }
131
132 internal int globalCrc;
133 }
134 }
...\ No newline at end of file ...\ No newline at end of file
1 <?xml version="1.0" encoding="utf-8"?>
2 <Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3 <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
4 <PropertyGroup>
5 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
6 <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
7 <ProjectGuid>{45473847-8AF8-4BAF-B768-442C6875B8CF}</ProjectGuid>
8 <OutputType>Library</OutputType>
9 <AppDesignerFolder>Properties</AppDesignerFolder>
10 <RootNamespace>crypto</RootNamespace>
11 <AssemblyName>crypto</AssemblyName>
12 <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
13 <FileAlignment>512</FileAlignment>
14 <TargetFrameworkProfile />
15 </PropertyGroup>
16 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
17 <DebugSymbols>true</DebugSymbols>
18 <DebugType>full</DebugType>
19 <Optimize>false</Optimize>
20 <OutputPath>bin\Debug\</OutputPath>
21 <DefineConstants>TRACE;DEBUG;LIB;PCL;SILVERLIGHT</DefineConstants>
22 <ErrorReport>prompt</ErrorReport>
23 <WarningLevel>4</WarningLevel>
24 <Prefer32Bit>false</Prefer32Bit>
25 </PropertyGroup>
26 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
27 <DebugType>pdbonly</DebugType>
28 <Optimize>true</Optimize>
29 <OutputPath>bin\Release\</OutputPath>
30 <DefineConstants>TRACE;LIB;PCL;SILVERLIGHT</DefineConstants>
31 <ErrorReport>prompt</ErrorReport>
32 <WarningLevel>4</WarningLevel>
33 <Prefer32Bit>false</Prefer32Bit>
34 </PropertyGroup>
35 <ItemGroup>
36 <Reference Include="System" />
37 <Reference Include="System.Core" />
38 <Reference Include="System.Xml.Linq" />
39 <Reference Include="System.Data.DataSetExtensions" />
40 <Reference Include="Microsoft.CSharp" />
41 <Reference Include="System.Data" />
42 <Reference Include="System.Xml" />
43 </ItemGroup>
44 <ItemGroup>
45 <Compile Include="src\**\*.cs" />
46 <Compile Include="bzip2\**\*.cs" />
47 </ItemGroup>
48 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
49 <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
50 Other similar extension points exist, see Microsoft.Common.targets.
51 <Target Name="BeforeBuild">
52 </Target>
53 <Target Name="AfterBuild">
54 </Target>
55 -->
56 </Project>
...\ No newline at end of file ...\ No newline at end of file
1 using System;
2 using System.Reflection;
3 //using System.Security.Permissions;
4
5 #if PORTABLE
6 using System.Linq;
7 #else
8 using System.Runtime.InteropServices;
9 #endif
10
11 //
12 // General Information about an assembly is controlled through the following
13 // set of attributes. Change these attribute values to modify the information
14 // associated with an assembly.
15 //
16 [assembly: AssemblyTitle("BouncyCastle.Crypto")]
17 [assembly: AssemblyDescription("Bouncy Castle Cryptography API")]
18 [assembly: AssemblyConfiguration("")]
19 [assembly: AssemblyCompany("The Legion of the Bouncy Castle Inc.")]
20 [assembly: AssemblyProduct("Bouncy Castle for .NET")]
21 [assembly: AssemblyCopyright("Copyright (C) 2000-2015")]
22 [assembly: AssemblyTrademark("")]
23 [assembly: AssemblyCulture("")]
24
25 //
26 // Version information for an assembly consists of the following four values:
27 //
28 // Major Version
29 // Minor Version
30 // Build Number
31 // Revision
32 //
33 // You can specify all the values or you can default the Revision and Build Numbers
34 // by using the '*' as shown below:
35
36 [assembly: AssemblyVersion("1.8.1.0")]
37 [assembly: AssemblyFileVersion("1.8.15362.1")]
38 [assembly: AssemblyInformationalVersion("1.8.1")]
39
40 //
41 // In order to sign your assembly you must specify a key to use. Refer to the
42 // Microsoft .NET Framework documentation for more information on assembly signing.
43 //
44 // Use the attributes below to control which key is used for signing.
45 //
46 // Notes:
47 // (*) If no key is specified, the assembly is not signed.
48 // (*) KeyName refers to a key that has been installed in the Crypto Service
49 // Provider (CSP) on your machine. KeyFile refers to a file which contains
50 // a key.
51 // (*) If the KeyFile and the KeyName values are both specified, the
52 // following processing occurs:
53 // (1) If the KeyName can be found in the CSP, that key is used.
54 // (2) If the KeyName does not exist and the KeyFile does exist, the key
55 // in the KeyFile is installed into the CSP and used.
56 // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
57 // When specifying the KeyFile, the location of the KeyFile should be
58 // relative to the project output directory which is
59 // %Project Directory%\obj\<configuration>. For example, if your KeyFile is
60 // located in the project directory, you would specify the AssemblyKeyFile
61 // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
62 // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
63 // documentation for more information on this.
64 //
65 [assembly: AssemblyDelaySign(false)]
66 #if STRONG_NAME
67 [assembly: AssemblyKeyFile(@"../BouncyCastle.snk")]
68 #endif
69
70 [assembly: CLSCompliant(true)]
71 #if !PORTABLE
72 [assembly: ComVisible(false)]
73 #endif
74
75 // Start with no permissions
76 //[assembly: PermissionSet(SecurityAction.RequestOptional, Unrestricted=false)]
77 //...and explicitly add those we need
78
79 // see Org.BouncyCastle.Crypto.Encodings.Pkcs1Encoding.StrictLengthEnabledProperty
80 //[assembly: EnvironmentPermission(SecurityAction.RequestOptional, Read="Org.BouncyCastle.Pkcs1.Strict")]
81
82 internal class AssemblyInfo
83 {
84 private static string version = null;
85
86 public static string Version
87 {
88 get
89 {
90 if (version == null)
91 {
92 #if PORTABLE
93 #if NEW_REFLECTION
94 var a = typeof(AssemblyInfo).GetTypeInfo().Assembly;
95 var c = a.GetCustomAttributes(typeof(AssemblyVersionAttribute));
96 #else
97 var a = typeof(AssemblyInfo).Assembly;
98 var c = a.GetCustomAttributes(typeof(AssemblyVersionAttribute), false);
99 #endif
100 var v = (AssemblyVersionAttribute)c.FirstOrDefault();
101 if (v != null)
102 {
103 version = v.Version;
104 }
105 #else
106 version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
107 #endif
108
109 // if we're still here, then don't try again
110 if (version == null)
111 {
112 version = string.Empty;
113 }
114 }
115
116 return version;
117 }
118 }
119 }
1 using System.Collections;
2 using System.IO;
3
4 namespace Org.BouncyCastle.Asn1
5 {
6 public abstract class Asn1Generator
7 {
8 private Stream _out;
9
10 protected Asn1Generator(
11 Stream outStream)
12 {
13 _out = outStream;
14 }
15
16 protected Stream Out
17 {
18 get { return _out; }
19 }
20
21 public abstract void AddObject(Asn1Encodable obj);
22
23 public abstract Stream GetRawOutputStream();
24
25 public abstract void Close();
26 }
27 }
1 using System.IO;
2
3 namespace Org.BouncyCastle.Asn1
4 {
5 public interface Asn1OctetStringParser
6 : IAsn1Convertible
7 {
8 Stream GetOctetStream();
9 }
10 }
1 namespace Org.BouncyCastle.Asn1
2 {
3 public interface Asn1SequenceParser
4 : IAsn1Convertible
5 {
6 IAsn1Convertible ReadObject();
7 }
8 }
1 namespace Org.BouncyCastle.Asn1
2 {
3 public interface Asn1SetParser
4 : IAsn1Convertible
5 {
6 IAsn1Convertible ReadObject();
7 }
8 }
1 using System;
2 using System.IO;
3
4 namespace Org.BouncyCastle.Asn1
5 {
6 public class Asn1StreamParser
7 {
8 private readonly Stream _in;
9 private readonly int _limit;
10
11 private readonly byte[][] tmpBuffers;
12
13 public Asn1StreamParser(
14 Stream inStream)
15 : this(inStream, Asn1InputStream.FindLimit(inStream))
16 {
17 }
18
19 public Asn1StreamParser(
20 Stream inStream,
21 int limit)
22 {
23 if (!inStream.CanRead)
24 throw new ArgumentException("Expected stream to be readable", "inStream");
25
26 this._in = inStream;
27 this._limit = limit;
28 this.tmpBuffers = new byte[16][];
29 }
30
31 public Asn1StreamParser(
32 byte[] encoding)
33 : this(new MemoryStream(encoding, false), encoding.Length)
34 {
35 }
36
37 internal IAsn1Convertible ReadIndef(int tagValue)
38 {
39 // Note: INDEF => CONSTRUCTED
40
41 // TODO There are other tags that may be constructed (e.g. BIT_STRING)
42 switch (tagValue)
43 {
44 case Asn1Tags.External:
45 return new DerExternalParser(this);
46 case Asn1Tags.OctetString:
47 return new BerOctetStringParser(this);
48 case Asn1Tags.Sequence:
49 return new BerSequenceParser(this);
50 case Asn1Tags.Set:
51 return new BerSetParser(this);
52 default:
53 throw new Asn1Exception("unknown BER object encountered: 0x" + tagValue.ToString("X"));
54 }
55 }
56
57 internal IAsn1Convertible ReadImplicit(bool constructed, int tag)
58 {
59 if (_in is IndefiniteLengthInputStream)
60 {
61 if (!constructed)
62 throw new IOException("indefinite length primitive encoding encountered");
63
64 return ReadIndef(tag);
65 }
66
67 if (constructed)
68 {
69 switch (tag)
70 {
71 case Asn1Tags.Set:
72 return new DerSetParser(this);
73 case Asn1Tags.Sequence:
74 return new DerSequenceParser(this);
75 case Asn1Tags.OctetString:
76 return new BerOctetStringParser(this);
77 }
78 }
79 else
80 {
81 switch (tag)
82 {
83 case Asn1Tags.Set:
84 throw new Asn1Exception("sequences must use constructed encoding (see X.690 8.9.1/8.10.1)");
85 case Asn1Tags.Sequence:
86 throw new Asn1Exception("sets must use constructed encoding (see X.690 8.11.1/8.12.1)");
87 case Asn1Tags.OctetString:
88 return new DerOctetStringParser((DefiniteLengthInputStream)_in);
89 }
90 }
91
92 throw new Asn1Exception("implicit tagging not implemented");
93 }
94
95 internal Asn1Object ReadTaggedObject(bool constructed, int tag)
96 {
97 if (!constructed)
98 {
99 // Note: !CONSTRUCTED => IMPLICIT
100 DefiniteLengthInputStream defIn = (DefiniteLengthInputStream)_in;
101 return new DerTaggedObject(false, tag, new DerOctetString(defIn.ToArray()));
102 }
103
104 Asn1EncodableVector v = ReadVector();
105
106 if (_in is IndefiniteLengthInputStream)
107 {
108 return v.Count == 1
109 ? new BerTaggedObject(true, tag, v[0])
110 : new BerTaggedObject(false, tag, BerSequence.FromVector(v));
111 }
112
113 return v.Count == 1
114 ? new DerTaggedObject(true, tag, v[0])
115 : new DerTaggedObject(false, tag, DerSequence.FromVector(v));
116 }
117
118 public virtual IAsn1Convertible ReadObject()
119 {
120 int tag = _in.ReadByte();
121 if (tag == -1)
122 return null;
123
124 // turn of looking for "00" while we resolve the tag
125 Set00Check(false);
126
127 //
128 // calculate tag number
129 //
130 int tagNo = Asn1InputStream.ReadTagNumber(_in, tag);
131
132 bool isConstructed = (tag & Asn1Tags.Constructed) != 0;
133
134 //
135 // calculate length
136 //
137 int length = Asn1InputStream.ReadLength(_in, _limit);
138
139 if (length < 0) // indefinite length method
140 {
141 if (!isConstructed)
142 throw new IOException("indefinite length primitive encoding encountered");
143
144 IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(_in, _limit);
145 Asn1StreamParser sp = new Asn1StreamParser(indIn, _limit);
146
147 if ((tag & Asn1Tags.Application) != 0)
148 {
149 return new BerApplicationSpecificParser(tagNo, sp);
150 }
151
152 if ((tag & Asn1Tags.Tagged) != 0)
153 {
154 return new BerTaggedObjectParser(true, tagNo, sp);
155 }
156
157 return sp.ReadIndef(tagNo);
158 }
159 else
160 {
161 DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(_in, length);
162
163 if ((tag & Asn1Tags.Application) != 0)
164 {
165 return new DerApplicationSpecific(isConstructed, tagNo, defIn.ToArray());
166 }
167
168 if ((tag & Asn1Tags.Tagged) != 0)
169 {
170 return new BerTaggedObjectParser(isConstructed, tagNo, new Asn1StreamParser(defIn));
171 }
172
173 if (isConstructed)
174 {
175 // TODO There are other tags that may be constructed (e.g. BitString)
176 switch (tagNo)
177 {
178 case Asn1Tags.OctetString:
179 //
180 // yes, people actually do this...
181 //
182 return new BerOctetStringParser(new Asn1StreamParser(defIn));
183 case Asn1Tags.Sequence:
184 return new DerSequenceParser(new Asn1StreamParser(defIn));
185 case Asn1Tags.Set:
186 return new DerSetParser(new Asn1StreamParser(defIn));
187 case Asn1Tags.External:
188 return new DerExternalParser(new Asn1StreamParser(defIn));
189 default:
190 throw new IOException("unknown tag " + tagNo + " encountered");
191 }
192 }
193
194 // Some primitive encodings can be handled by parsers too...
195 switch (tagNo)
196 {
197 case Asn1Tags.OctetString:
198 return new DerOctetStringParser(defIn);
199 }
200
201 try
202 {
203 return Asn1InputStream.CreatePrimitiveDerObject(tagNo, defIn, tmpBuffers);
204 }
205 catch (ArgumentException e)
206 {
207 throw new Asn1Exception("corrupted stream detected", e);
208 }
209 }
210 }
211
212 private void Set00Check(
213 bool enabled)
214 {
215 if (_in is IndefiniteLengthInputStream)
216 {
217 ((IndefiniteLengthInputStream) _in).SetEofOn00(enabled);
218 }
219 }
220
221 internal Asn1EncodableVector ReadVector()
222 {
223 Asn1EncodableVector v = new Asn1EncodableVector();
224
225 IAsn1Convertible obj;
226 while ((obj = ReadObject()) != null)
227 {
228 v.Add(obj.ToAsn1Object());
229 }
230
231 return v;
232 }
233 }
234 }
1 namespace Org.BouncyCastle.Asn1
2 {
3 public interface Asn1TaggedObjectParser
4 : IAsn1Convertible
5 {
6 int TagNo { get; }
7
8 IAsn1Convertible GetObjectParser(int tag, bool isExplicit);
9 }
10 }
1 using System.IO;
2
3 namespace Org.BouncyCastle.Asn1
4 {
5 public abstract class Asn1Encodable
6 : IAsn1Convertible
7 {
8 public const string Der = "DER";
9 public const string Ber = "BER";
10
11 public byte[] GetEncoded()
12 {
13 MemoryStream bOut = new MemoryStream();
14 Asn1OutputStream aOut = new Asn1OutputStream(bOut);
15
16 aOut.WriteObject(this);
17
18 return bOut.ToArray();
19 }
20
21 public byte[] GetEncoded(
22 string encoding)
23 {
24 if (encoding.Equals(Der))
25 {
26 MemoryStream bOut = new MemoryStream();
27 DerOutputStream dOut = new DerOutputStream(bOut);
28
29 dOut.WriteObject(this);
30
31 return bOut.ToArray();
32 }
33
34 return GetEncoded();
35 }
36
37 /**
38 * Return the DER encoding of the object, null if the DER encoding can not be made.
39 *
40 * @return a DER byte array, null otherwise.
41 */
42 public byte[] GetDerEncoded()
43 {
44 try
45 {
46 return GetEncoded(Der);
47 }
48 catch (IOException)
49 {
50 return null;
51 }
52 }
53
54 public sealed override int GetHashCode()
55 {
56 return ToAsn1Object().CallAsn1GetHashCode();
57 }
58
59 public sealed override bool Equals(
60 object obj)
61 {
62 if (obj == this)
63 return true;
64
65 IAsn1Convertible other = obj as IAsn1Convertible;
66
67 if (other == null)
68 return false;
69
70 Asn1Object o1 = ToAsn1Object();
71 Asn1Object o2 = other.ToAsn1Object();
72
73 return o1 == o2 || o1.CallAsn1Equals(o2);
74 }
75
76 public abstract Asn1Object ToAsn1Object();
77 }
78 }
1 using System;
2 using System.Collections;
3
4 using Org.BouncyCastle.Utilities;
5
6 namespace Org.BouncyCastle.Asn1
7 {
8 public class Asn1EncodableVector
9 : IEnumerable
10 {
11 private IList v = Platform.CreateArrayList();
12
13 public static Asn1EncodableVector FromEnumerable(
14 IEnumerable e)
15 {
16 Asn1EncodableVector v = new Asn1EncodableVector();
17 foreach (Asn1Encodable obj in e)
18 {
19 v.Add(obj);
20 }
21 return v;
22 }
23
24 // public Asn1EncodableVector()
25 // {
26 // }
27
28 public Asn1EncodableVector(
29 params Asn1Encodable[] v)
30 {
31 Add(v);
32 }
33
34 // public void Add(
35 // Asn1Encodable obj)
36 // {
37 // v.Add(obj);
38 // }
39
40 public void Add(
41 params Asn1Encodable[] objs)
42 {
43 foreach (Asn1Encodable obj in objs)
44 {
45 v.Add(obj);
46 }
47 }
48
49 public void AddOptional(
50 params Asn1Encodable[] objs)
51 {
52 if (objs != null)
53 {
54 foreach (Asn1Encodable obj in objs)
55 {
56 if (obj != null)
57 {
58 v.Add(obj);
59 }
60 }
61 }
62 }
63
64 public Asn1Encodable this[
65 int index]
66 {
67 get { return (Asn1Encodable) v[index]; }
68 }
69
70 [Obsolete("Use 'object[index]' syntax instead")]
71 public Asn1Encodable Get(
72 int index)
73 {
74 return this[index];
75 }
76
77 [Obsolete("Use 'Count' property instead")]
78 public int Size
79 {
80 get { return v.Count; }
81 }
82
83 public int Count
84 {
85 get { return v.Count; }
86 }
87
88 public IEnumerator GetEnumerator()
89 {
90 return v.GetEnumerator();
91 }
92 }
93 }
1 using System;
2 using System.IO;
3
4 namespace Org.BouncyCastle.Asn1
5 {
6 #if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE)
7 [Serializable]
8 #endif
9 public class Asn1Exception
10 : IOException
11 {
12 public Asn1Exception()
13 : base()
14 {
15 }
16
17 public Asn1Exception(
18 string message)
19 : base(message)
20 {
21 }
22
23 public Asn1Exception(
24 string message,
25 Exception exception)
26 : base(message, exception)
27 {
28 }
29 }
30 }
1 namespace Org.BouncyCastle.Asn1
2 {
3 /**
4 * A Null object.
5 */
6 public abstract class Asn1Null
7 : Asn1Object
8 {
9 internal Asn1Null()
10 {
11 }
12
13 public override string ToString()
14 {
15 return "NULL";
16 }
17 }
18 }
1 using System;
2 using System.IO;
3
4 namespace Org.BouncyCastle.Asn1
5 {
6 public abstract class Asn1Object
7 : Asn1Encodable
8 {
9 /// <summary>Create a base ASN.1 object from a byte array.</summary>
10 /// <param name="data">The byte array to parse.</param>
11 /// <returns>The base ASN.1 object represented by the byte array.</returns>
12 /// <exception cref="IOException">If there is a problem parsing the data.</exception>
13 public static Asn1Object FromByteArray(
14 byte[] data)
15 {
16 try
17 {
18 MemoryStream input = new MemoryStream(data, false);
19 Asn1InputStream asn1 = new Asn1InputStream(input, data.Length);
20 Asn1Object result = asn1.ReadObject();
21 if (input.Position != input.Length)
22 throw new IOException("extra data found after object");
23 return result;
24 }
25 catch (InvalidCastException)
26 {
27 throw new IOException("cannot recognise object in byte array");
28 }
29 }
30
31 /// <summary>Read a base ASN.1 object from a stream.</summary>
32 /// <param name="inStr">The stream to parse.</param>
33 /// <returns>The base ASN.1 object represented by the byte array.</returns>
34 /// <exception cref="IOException">If there is a problem parsing the data.</exception>
35 public static Asn1Object FromStream(
36 Stream inStr)
37 {
38 try
39 {
40 return new Asn1InputStream(inStr).ReadObject();
41 }
42 catch (InvalidCastException)
43 {
44 throw new IOException("cannot recognise object in stream");
45 }
46 }
47
48 public sealed override Asn1Object ToAsn1Object()
49 {
50 return this;
51 }
52
53 internal abstract void Encode(DerOutputStream derOut);
54
55 protected abstract bool Asn1Equals(Asn1Object asn1Object);
56 protected abstract int Asn1GetHashCode();
57
58 internal bool CallAsn1Equals(Asn1Object obj)
59 {
60 return Asn1Equals(obj);
61 }
62
63 internal int CallAsn1GetHashCode()
64 {
65 return Asn1GetHashCode();
66 }
67 }
68 }
1 using System;
2 using System.Collections;
3 using System.IO;
4
5 using Org.BouncyCastle.Utilities;
6 using Org.BouncyCastle.Utilities.Encoders;
7
8 namespace Org.BouncyCastle.Asn1
9 {
10 public abstract class Asn1OctetString
11 : Asn1Object, Asn1OctetStringParser
12 {
13 internal byte[] str;
14
15 /**
16 * return an Octet string from a tagged object.
17 *
18 * @param obj the tagged object holding the object we want.
19 * @param explicitly true if the object is meant to be explicitly
20 * tagged false otherwise.
21 * @exception ArgumentException if the tagged object cannot
22 * be converted.
23 */
24 public static Asn1OctetString GetInstance(
25 Asn1TaggedObject obj,
26 bool isExplicit)
27 {
28 Asn1Object o = obj.GetObject();
29
30 if (isExplicit || o is Asn1OctetString)
31 {
32 return GetInstance(o);
33 }
34
35 return BerOctetString.FromSequence(Asn1Sequence.GetInstance(o));
36 }
37
38 /**
39 * return an Octet string from the given object.
40 *
41 * @param obj the object we want converted.
42 * @exception ArgumentException if the object cannot be converted.
43 */
44 public static Asn1OctetString GetInstance(object obj)
45 {
46 if (obj == null || obj is Asn1OctetString)
47 {
48 return (Asn1OctetString)obj;
49 }
50
51 // TODO: this needs to be deleted in V2
52 if (obj is Asn1TaggedObject)
53 return GetInstance(((Asn1TaggedObject)obj).GetObject());
54
55 throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj));
56 }
57
58 /**
59 * @param string the octets making up the octet string.
60 */
61 internal Asn1OctetString(
62 byte[] str)
63 {
64 if (str == null)
65 throw new ArgumentNullException("str");
66
67 this.str = str;
68 }
69
70 internal Asn1OctetString(
71 Asn1Encodable obj)
72 {
73 try
74 {
75 this.str = obj.GetEncoded(Asn1Encodable.Der);
76 }
77 catch (IOException e)
78 {
79 throw new ArgumentException("Error processing object : " + e.ToString());
80 }
81 }
82
83 public Stream GetOctetStream()
84 {
85 return new MemoryStream(str, false);
86 }
87
88 public Asn1OctetStringParser Parser
89 {
90 get { return this; }
91 }
92
93 public virtual byte[] GetOctets()
94 {
95 return str;
96 }
97
98 protected override int Asn1GetHashCode()
99 {
100 return Arrays.GetHashCode(GetOctets());
101 }
102
103 protected override bool Asn1Equals(
104 Asn1Object asn1Object)
105 {
106 DerOctetString other = asn1Object as DerOctetString;
107
108 if (other == null)
109 return false;
110
111 return Arrays.AreEqual(GetOctets(), other.GetOctets());
112 }
113
114 public override string ToString()
115 {
116 return "#" + Hex.ToHexString(str);
117 }
118 }
119 }
1 using System;
2 using System.IO;
3
4 namespace Org.BouncyCastle.Asn1
5 {
6 public class Asn1OutputStream
7 : DerOutputStream
8 {
9 public Asn1OutputStream(Stream os) : base(os)
10 {
11 }
12
13 [Obsolete("Use version taking an Asn1Encodable arg instead")]
14 public override void WriteObject(
15 object obj)
16 {
17 if (obj == null)
18 {
19 WriteNull();
20 }
21 else if (obj is Asn1Object)
22 {
23 ((Asn1Object)obj).Encode(this);
24 }
25 else if (obj is Asn1Encodable)
26 {
27 ((Asn1Encodable)obj).ToAsn1Object().Encode(this);
28 }
29 else
30 {
31 throw new IOException("object not Asn1Encodable");
32 }
33 }
34 }
35 }
1 using System;
2
3 namespace Org.BouncyCastle.Asn1
4 {
5 #if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE)
6 [Serializable]
7 #endif
8 public class Asn1ParsingException
9 : InvalidOperationException
10 {
11 public Asn1ParsingException()
12 : base()
13 {
14 }
15
16 public Asn1ParsingException(
17 string message)
18 : base(message)
19 {
20 }
21
22 public Asn1ParsingException(
23 string message,
24 Exception exception)
25 : base(message, exception)
26 {
27 }
28 }
29 }
1 using System;
2 using System.Collections;
3 using System.IO;
4
5 using Org.BouncyCastle.Utilities;
6 using Org.BouncyCastle.Utilities.Collections;
7
8 namespace Org.BouncyCastle.Asn1
9 {
10 public abstract class Asn1Sequence
11 : Asn1Object, IEnumerable
12 {
13 private readonly IList seq;
14
15 /**
16 * return an Asn1Sequence from the given object.
17 *
18 * @param obj the object we want converted.
19 * @exception ArgumentException if the object cannot be converted.
20 */
21 public static Asn1Sequence GetInstance(
22 object obj)
23 {
24 if (obj == null || obj is Asn1Sequence)
25 {
26 return (Asn1Sequence)obj;
27 }
28 else if (obj is Asn1SequenceParser)
29 {
30 return Asn1Sequence.GetInstance(((Asn1SequenceParser)obj).ToAsn1Object());
31 }
32 else if (obj is byte[])
33 {
34 try
35 {
36 return Asn1Sequence.GetInstance(FromByteArray((byte[])obj));
37 }
38 catch (IOException e)
39 {
40 throw new ArgumentException("failed to construct sequence from byte[]: " + e.Message);
41 }
42 }
43 else if (obj is Asn1Encodable)
44 {
45 Asn1Object primitive = ((Asn1Encodable)obj).ToAsn1Object();
46
47 if (primitive is Asn1Sequence)
48 {
49 return (Asn1Sequence)primitive;
50 }
51 }
52
53 throw new ArgumentException("Unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj");
54 }
55
56 /**
57 * Return an ASN1 sequence from a tagged object. There is a special
58 * case here, if an object appears to have been explicitly tagged on
59 * reading but we were expecting it to be implicitly tagged in the
60 * normal course of events it indicates that we lost the surrounding
61 * sequence - so we need to add it back (this will happen if the tagged
62 * object is a sequence that contains other sequences). If you are
63 * dealing with implicitly tagged sequences you really <b>should</b>
64 * be using this method.
65 *
66 * @param obj the tagged object.
67 * @param explicitly true if the object is meant to be explicitly tagged,
68 * false otherwise.
69 * @exception ArgumentException if the tagged object cannot
70 * be converted.
71 */
72 public static Asn1Sequence GetInstance(
73 Asn1TaggedObject obj,
74 bool explicitly)
75 {
76 Asn1Object inner = obj.GetObject();
77
78 if (explicitly)
79 {
80 if (!obj.IsExplicit())
81 throw new ArgumentException("object implicit - explicit expected.");
82
83 return (Asn1Sequence) inner;
84 }
85
86 //
87 // constructed object which appears to be explicitly tagged
88 // when it should be implicit means we have to add the
89 // surrounding sequence.
90 //
91 if (obj.IsExplicit())
92 {
93 if (obj is BerTaggedObject)
94 {
95 return new BerSequence(inner);
96 }
97
98 return new DerSequence(inner);
99 }
100
101 if (inner is Asn1Sequence)
102 {
103 return (Asn1Sequence) inner;
104 }
105
106 throw new ArgumentException("Unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj");
107 }
108
109 protected internal Asn1Sequence(
110 int capacity)
111 {
112 seq = Platform.CreateArrayList(capacity);
113 }
114
115 public virtual IEnumerator GetEnumerator()
116 {
117 return seq.GetEnumerator();
118 }
119
120 [Obsolete("Use GetEnumerator() instead")]
121 public IEnumerator GetObjects()
122 {
123 return GetEnumerator();
124 }
125
126 private class Asn1SequenceParserImpl
127 : Asn1SequenceParser
128 {
129 private readonly Asn1Sequence outer;
130 private readonly int max;
131 private int index;
132
133 public Asn1SequenceParserImpl(
134 Asn1Sequence outer)
135 {
136 this.outer = outer;
137 this.max = outer.Count;
138 }
139
140 public IAsn1Convertible ReadObject()
141 {
142 if (index == max)
143 return null;
144
145 Asn1Encodable obj = outer[index++];
146
147 if (obj is Asn1Sequence)
148 return ((Asn1Sequence)obj).Parser;
149
150 if (obj is Asn1Set)
151 return ((Asn1Set)obj).Parser;
152
153 // NB: Asn1OctetString implements Asn1OctetStringParser directly
154 // if (obj is Asn1OctetString)
155 // return ((Asn1OctetString)obj).Parser;
156
157 return obj;
158 }
159
160 public Asn1Object ToAsn1Object()
161 {
162 return outer;
163 }
164 }
165
166 public virtual Asn1SequenceParser Parser
167 {
168 get { return new Asn1SequenceParserImpl(this); }
169 }
170
171 /**
172 * return the object at the sequence position indicated by index.
173 *
174 * @param index the sequence number (starting at zero) of the object
175 * @return the object at the sequence position indicated by index.
176 */
177 public virtual Asn1Encodable this[int index]
178 {
179 get { return (Asn1Encodable) seq[index]; }
180 }
181
182 [Obsolete("Use 'object[index]' syntax instead")]
183 public Asn1Encodable GetObjectAt(
184 int index)
185 {
186 return this[index];
187 }
188
189 [Obsolete("Use 'Count' property instead")]
190 public int Size
191 {
192 get { return Count; }
193 }
194
195 public virtual int Count
196 {
197 get { return seq.Count; }
198 }
199
200 protected override int Asn1GetHashCode()
201 {
202 int hc = Count;
203
204 foreach (object o in this)
205 {
206 hc *= 17;
207 if (o == null)
208 {
209 hc ^= DerNull.Instance.GetHashCode();
210 }
211 else
212 {
213 hc ^= o.GetHashCode();
214 }
215 }
216
217 return hc;
218 }
219
220 protected override bool Asn1Equals(
221 Asn1Object asn1Object)
222 {
223 Asn1Sequence other = asn1Object as Asn1Sequence;
224
225 if (other == null)
226 return false;
227
228 if (Count != other.Count)
229 return false;
230
231 IEnumerator s1 = GetEnumerator();
232 IEnumerator s2 = other.GetEnumerator();
233
234 while (s1.MoveNext() && s2.MoveNext())
235 {
236 Asn1Object o1 = GetCurrent(s1).ToAsn1Object();
237 Asn1Object o2 = GetCurrent(s2).ToAsn1Object();
238
239 if (!o1.Equals(o2))
240 return false;
241 }
242
243 return true;
244 }
245
246 private Asn1Encodable GetCurrent(IEnumerator e)
247 {
248 Asn1Encodable encObj = (Asn1Encodable)e.Current;
249
250 // unfortunately null was allowed as a substitute for DER null
251 if (encObj == null)
252 return DerNull.Instance;
253
254 return encObj;
255 }
256
257 protected internal void AddObject(
258 Asn1Encodable obj)
259 {
260 seq.Add(obj);
261 }
262
263 public override string ToString()
264 {
265 return CollectionUtilities.ToString(seq);
266 }
267 }
268 }
1 using System;
2
3 using Org.BouncyCastle.Utilities;
4
5 namespace Org.BouncyCastle.Asn1
6 {
7 /**
8 * ASN.1 TaggedObject - in ASN.1 notation this is any object preceded by
9 * a [n] where n is some number - these are assumed to follow the construction
10 * rules (as with sequences).
11 */
12 public abstract class Asn1TaggedObject
13 : Asn1Object, Asn1TaggedObjectParser
14 {
15 internal static bool IsConstructed(bool isExplicit, Asn1Object obj)
16 {
17 if (isExplicit || obj is Asn1Sequence || obj is Asn1Set)
18 return true;
19 Asn1TaggedObject tagged = obj as Asn1TaggedObject;
20 if (tagged == null)
21 return false;
22 return IsConstructed(tagged.IsExplicit(), tagged.GetObject());
23 }
24
25 internal int tagNo;
26 // internal bool empty;
27 internal bool explicitly = true;
28 internal Asn1Encodable obj;
29
30 static public Asn1TaggedObject GetInstance(
31 Asn1TaggedObject obj,
32 bool explicitly)
33 {
34 if (explicitly)
35 {
36 return (Asn1TaggedObject) obj.GetObject();
37 }
38
39 throw new ArgumentException("implicitly tagged tagged object");
40 }
41
42 static public Asn1TaggedObject GetInstance(
43 object obj)
44 {
45 if (obj == null || obj is Asn1TaggedObject)
46 {
47 return (Asn1TaggedObject) obj;
48 }
49
50 throw new ArgumentException("Unknown object in GetInstance: " + Platform.GetTypeName(obj), "obj");
51 }
52
53 /**
54 * @param tagNo the tag number for this object.
55 * @param obj the tagged object.
56 */
57 protected Asn1TaggedObject(
58 int tagNo,
59 Asn1Encodable obj)
60 {
61 this.explicitly = true;
62 this.tagNo = tagNo;
63 this.obj = obj;
64 }
65
66 /**
67 * @param explicitly true if the object is explicitly tagged.
68 * @param tagNo the tag number for this object.
69 * @param obj the tagged object.
70 */
71 protected Asn1TaggedObject(
72 bool explicitly,
73 int tagNo,
74 Asn1Encodable obj)
75 {
76 // IAsn1Choice marker interface 'insists' on explicit tagging
77 this.explicitly = explicitly || (obj is IAsn1Choice);
78 this.tagNo = tagNo;
79 this.obj = obj;
80 }
81
82 protected override bool Asn1Equals(
83 Asn1Object asn1Object)
84 {
85 Asn1TaggedObject other = asn1Object as Asn1TaggedObject;
86
87 if (other == null)
88 return false;
89
90 return this.tagNo == other.tagNo
91 // && this.empty == other.empty
92 && this.explicitly == other.explicitly // TODO Should this be part of equality?
93 && Platform.Equals(GetObject(), other.GetObject());
94 }
95
96 protected override int Asn1GetHashCode()
97 {
98 int code = tagNo.GetHashCode();
99
100 // TODO: actually this is wrong - the problem is that a re-encoded
101 // object may end up with a different hashCode due to implicit
102 // tagging. As implicit tagging is ambiguous if a sequence is involved
103 // it seems the only correct method for both equals and hashCode is to
104 // compare the encodings...
105 // code ^= explicitly.GetHashCode();
106
107 if (obj != null)
108 {
109 code ^= obj.GetHashCode();
110 }
111
112 return code;
113 }
114
115 public int TagNo
116 {
117 get { return tagNo; }
118 }
119
120 /**
121 * return whether or not the object may be explicitly tagged.
122 * <p>
123 * Note: if the object has been read from an input stream, the only
124 * time you can be sure if isExplicit is returning the true state of
125 * affairs is if it returns false. An implicitly tagged object may appear
126 * to be explicitly tagged, so you need to understand the context under
127 * which the reading was done as well, see GetObject below.</p>
128 */
129 public bool IsExplicit()
130 {
131 return explicitly;
132 }
133
134 public bool IsEmpty()
135 {
136 return false; //empty;
137 }
138
139 /**
140 * return whatever was following the tag.
141 * <p>
142 * Note: tagged objects are generally context dependent if you're
143 * trying to extract a tagged object you should be going via the
144 * appropriate GetInstance method.</p>
145 */
146 public Asn1Object GetObject()
147 {
148 if (obj != null)
149 {
150 return obj.ToAsn1Object();
151 }
152
153 return null;
154 }
155
156 /**
157 * Return the object held in this tagged object as a parser assuming it has
158 * the type of the passed in tag. If the object doesn't have a parser
159 * associated with it, the base object is returned.
160 */
161 public IAsn1Convertible GetObjectParser(
162 int tag,
163 bool isExplicit)
164 {
165 switch (tag)
166 {
167 case Asn1Tags.Set:
168 return Asn1Set.GetInstance(this, isExplicit).Parser;
169 case Asn1Tags.Sequence:
170 return Asn1Sequence.GetInstance(this, isExplicit).Parser;
171 case Asn1Tags.OctetString:
172 return Asn1OctetString.GetInstance(this, isExplicit).Parser;
173 }
174
175 if (isExplicit)
176 {
177 return GetObject();
178 }
179
180 throw Platform.CreateNotImplementedException("implicit tagging for tag: " + tag);
181 }
182
183 public override string ToString()
184 {
185 return "[" + tagNo + "]" + obj;
186 }
187 }
188 }
1 namespace Org.BouncyCastle.Asn1
2 {
3 public class Asn1Tags
4 {
5 public const int Boolean = 0x01;
6 public const int Integer = 0x02;
7 public const int BitString = 0x03;
8 public const int OctetString = 0x04;
9 public const int Null = 0x05;
10 public const int ObjectIdentifier = 0x06;
11 public const int External = 0x08;
12 public const int Enumerated = 0x0a;
13 public const int Sequence = 0x10;
14 public const int SequenceOf = 0x10; // for completeness
15 public const int Set = 0x11;
16 public const int SetOf = 0x11; // for completeness
17
18 public const int NumericString = 0x12;
19 public const int PrintableString = 0x13;
20 public const int T61String = 0x14;
21 public const int VideotexString = 0x15;
22 public const int IA5String = 0x16;
23 public const int UtcTime = 0x17;
24 public const int GeneralizedTime = 0x18;
25 public const int GraphicString = 0x19;
26 public const int VisibleString = 0x1a;
27 public const int GeneralString = 0x1b;
28 public const int UniversalString = 0x1c;
29 public const int BmpString = 0x1e;
30 public const int Utf8String = 0x0c;
31
32 public const int Constructed = 0x20;
33 public const int Application = 0x40;
34 public const int Tagged = 0x80;
35 }
36 }
1 using System;
2
3 using Org.BouncyCastle.Utilities;
4
5 namespace Org.BouncyCastle.Asn1
6 {
7 public class BerBitString
8 : DerBitString
9 {
10 public BerBitString(byte[] data, int padBits)
11 : base(data, padBits)
12 {
13 }
14
15 public BerBitString(byte[] data)
16 : base(data)
17 {
18 }
19
20 public BerBitString(int namedBits)
21 : base(namedBits)
22 {
23 }
24
25 public BerBitString(Asn1Encodable obj)
26 : base(obj)
27 {
28 }
29
30 internal override void Encode(
31 DerOutputStream derOut)
32 {
33 if (derOut is Asn1OutputStream || derOut is BerOutputStream)
34 {
35 derOut.WriteEncoded(Asn1Tags.BitString, (byte)mPadBits, mData);
36 }
37 else
38 {
39 base.Encode(derOut);
40 }
41 }
42 }
43 }
1 using System.IO;
2
3 using Org.BouncyCastle.Utilities.IO;
4
5 namespace Org.BouncyCastle.Asn1
6 {
7 public class BerGenerator
8 : Asn1Generator
9 {
10 private bool _tagged = false;
11 private bool _isExplicit;
12 private int _tagNo;
13
14 protected BerGenerator(
15 Stream outStream)
16 : base(outStream)
17 {
18 }
19
20 public BerGenerator(
21 Stream outStream,
22 int tagNo,
23 bool isExplicit)
24 : base(outStream)
25 {
26 _tagged = true;
27 _isExplicit = isExplicit;
28 _tagNo = tagNo;
29 }
30
31 public override void AddObject(
32 Asn1Encodable obj)
33 {
34 new BerOutputStream(Out).WriteObject(obj);
35 }
36
37 public override Stream GetRawOutputStream()
38 {
39 return Out;
40 }
41
42 public override void Close()
43 {
44 WriteBerEnd();
45 }
46
47 private void WriteHdr(
48 int tag)
49 {
50 Out.WriteByte((byte) tag);
51 Out.WriteByte(0x80);
52 }
53
54 protected void WriteBerHeader(
55 int tag)
56 {
57 if (_tagged)
58 {
59 int tagNum = _tagNo | Asn1Tags.Tagged;
60
61 if (_isExplicit)
62 {
63 WriteHdr(tagNum | Asn1Tags.Constructed);
64 WriteHdr(tag);
65 }
66 else
67 {
68 if ((tag & Asn1Tags.Constructed) != 0)
69 {
70 WriteHdr(tagNum | Asn1Tags.Constructed);
71 }
72 else
73 {
74 WriteHdr(tagNum);
75 }
76 }
77 }
78 else
79 {
80 WriteHdr(tag);
81 }
82 }
83
84 protected void WriteBerBody(
85 Stream contentStream)
86 {
87 Streams.PipeAll(contentStream, Out);
88 }
89
90 protected void WriteBerEnd()
91 {
92 Out.WriteByte(0x00);
93 Out.WriteByte(0x00);
94
95 if (_tagged && _isExplicit) // write extra end for tag header
96 {
97 Out.WriteByte(0x00);
98 Out.WriteByte(0x00);
99 }
100 }
101 }
102 }
1 using System;
2 using System.IO;
3
4 using Org.BouncyCastle.Utilities.IO;
5
6 namespace Org.BouncyCastle.Asn1
7 {
8 public class BerOctetStringGenerator
9 : BerGenerator
10 {
11 public BerOctetStringGenerator(Stream outStream)
12 : base(outStream)
13 {
14 WriteBerHeader(Asn1Tags.Constructed | Asn1Tags.OctetString);
15 }
16
17 public BerOctetStringGenerator(
18 Stream outStream,
19 int tagNo,
20 bool isExplicit)
21 : base(outStream, tagNo, isExplicit)
22 {
23 WriteBerHeader(Asn1Tags.Constructed | Asn1Tags.OctetString);
24 }
25
26 public Stream GetOctetOutputStream()
27 {
28 return GetOctetOutputStream(new byte[1000]); // limit for CER encoding.
29 }
30
31 public Stream GetOctetOutputStream(
32 int bufSize)
33 {
34 return bufSize < 1
35 ? GetOctetOutputStream()
36 : GetOctetOutputStream(new byte[bufSize]);
37 }
38
39 public Stream GetOctetOutputStream(
40 byte[] buf)
41 {
42 return new BufferedBerOctetStream(this, buf);
43 }
44
45 private class BufferedBerOctetStream
46 : BaseOutputStream
47 {
48 private byte[] _buf;
49 private int _off;
50 private readonly BerOctetStringGenerator _gen;
51 private readonly DerOutputStream _derOut;
52
53 internal BufferedBerOctetStream(
54 BerOctetStringGenerator gen,
55 byte[] buf)
56 {
57 _gen = gen;
58 _buf = buf;
59 _off = 0;
60 _derOut = new DerOutputStream(_gen.Out);
61 }
62
63 public override void WriteByte(
64 byte b)
65 {
66 _buf[_off++] = b;
67
68 if (_off == _buf.Length)
69 {
70 DerOctetString.Encode(_derOut, _buf, 0, _off);
71 _off = 0;
72 }
73 }
74
75 public override void Write(
76 byte[] buf,
77 int offset,
78 int len)
79 {
80 while (len > 0)
81 {
82 int numToCopy = System.Math.Min(len, _buf.Length - _off);
83
84 if (numToCopy == _buf.Length)
85 {
86 DerOctetString.Encode(_derOut, buf, offset, numToCopy);
87 }
88 else
89 {
90 Array.Copy(buf, offset, _buf, _off, numToCopy);
91
92 _off += numToCopy;
93 if (_off < _buf.Length)
94 break;
95
96 DerOctetString.Encode(_derOut, _buf, 0, _off);
97 _off = 0;
98 }
99
100 offset += numToCopy;
101 len -= numToCopy;
102 }
103 }
104
105 #if PORTABLE
106 protected override void Dispose(bool disposing)
107 {
108 if (disposing)
109 {
110 if (_off != 0)
111 {
112 DerOctetString.Encode(_derOut, _buf, 0, _off);
113 }
114
115 _gen.WriteBerEnd();
116 }
117 base.Dispose(disposing);
118 }
119 #else
120 public override void Close()
121 {
122 if (_off != 0)
123 {
124 DerOctetString.Encode(_derOut, _buf, 0, _off);
125 }
126
127 _gen.WriteBerEnd();
128 base.Close();
129 }
130 #endif
131 }
132 }
133 }
1 using System;
2 using System.IO;
3
4 using Org.BouncyCastle.Utilities.IO;
5
6 namespace Org.BouncyCastle.Asn1
7 {
8 public class BerOctetStringParser
9 : Asn1OctetStringParser
10 {
11 private readonly Asn1StreamParser _parser;
12
13 internal BerOctetStringParser(
14 Asn1StreamParser parser)
15 {
16 _parser = parser;
17 }
18
19 public Stream GetOctetStream()
20 {
21 return new ConstructedOctetStream(_parser);
22 }
23
24 public Asn1Object ToAsn1Object()
25 {
26 try
27 {
28 return new BerOctetString(Streams.ReadAll(GetOctetStream()));
29 }
30 catch (IOException e)
31 {
32 throw new Asn1ParsingException("IOException converting stream to byte array: " + e.Message, e);
33 }
34 }
35 }
36 }
1 using System.IO;
2
3 namespace Org.BouncyCastle.Asn1
4 {
5 public class BerSequenceGenerator
6 : BerGenerator
7 {
8 public BerSequenceGenerator(
9 Stream outStream)
10 : base(outStream)
11 {
12 WriteBerHeader(Asn1Tags.Constructed | Asn1Tags.Sequence);
13 }
14
15 public BerSequenceGenerator(
16 Stream outStream,
17 int tagNo,
18 bool isExplicit)
19 : base(outStream, tagNo, isExplicit)
20 {
21 WriteBerHeader(Asn1Tags.Constructed | Asn1Tags.Sequence);
22 }
23 }
24 }
1 namespace Org.BouncyCastle.Asn1
2 {
3 public class BerSequenceParser
4 : Asn1SequenceParser
5 {
6 private readonly Asn1StreamParser _parser;
7
8 internal BerSequenceParser(
9 Asn1StreamParser parser)
10 {
11 this._parser = parser;
12 }
13
14 public IAsn1Convertible ReadObject()
15 {
16 return _parser.ReadObject();
17 }
18
19 public Asn1Object ToAsn1Object()
20 {
21 return new BerSequence(_parser.ReadVector());
22 }
23 }
24 }
1 using System.IO;
2
3 namespace Org.BouncyCastle.Asn1
4 {
5 public class BerSetGenerator
6 : BerGenerator
7 {
8 public BerSetGenerator(
9 Stream outStream)
10 : base(outStream)
11 {
12 WriteBerHeader(Asn1Tags.Constructed | Asn1Tags.Set);
13 }
14
15 public BerSetGenerator(
16 Stream outStream,
17 int tagNo,
18 bool isExplicit)
19 : base(outStream, tagNo, isExplicit)
20 {
21 WriteBerHeader(Asn1Tags.Constructed | Asn1Tags.Set);
22 }
23 }
24 }
1 namespace Org.BouncyCastle.Asn1
2 {
3 public class BerSetParser
4 : Asn1SetParser
5 {
6 private readonly Asn1StreamParser _parser;
7
8 internal BerSetParser(
9 Asn1StreamParser parser)
10 {
11 this._parser = parser;
12 }
13
14 public IAsn1Convertible ReadObject()
15 {
16 return _parser.ReadObject();
17 }
18
19 public Asn1Object ToAsn1Object()
20 {
21 return new BerSet(_parser.ReadVector(), false);
22 }
23 }
24 }
1 using System;
2 using System.IO;
3
4 using Org.BouncyCastle.Utilities;
5
6 namespace Org.BouncyCastle.Asn1
7 {
8 public class BerTaggedObjectParser
9 : Asn1TaggedObjectParser
10 {
11 private bool _constructed;
12 private int _tagNumber;
13 private Asn1StreamParser _parser;
14
15 [Obsolete]
16 internal BerTaggedObjectParser(
17 int baseTag,
18 int tagNumber,
19 Stream contentStream)
20 : this((baseTag & Asn1Tags.Constructed) != 0, tagNumber, new Asn1StreamParser(contentStream))
21 {
22 }
23
24 internal BerTaggedObjectParser(
25 bool constructed,
26 int tagNumber,
27 Asn1StreamParser parser)
28 {
29 _constructed = constructed;
30 _tagNumber = tagNumber;
31 _parser = parser;
32 }
33
34 public bool IsConstructed
35 {
36 get { return _constructed; }
37 }
38
39 public int TagNo
40 {
41 get { return _tagNumber; }
42 }
43
44 public IAsn1Convertible GetObjectParser(
45 int tag,
46 bool isExplicit)
47 {
48 if (isExplicit)
49 {
50 if (!_constructed)
51 throw new IOException("Explicit tags must be constructed (see X.690 8.14.2)");
52
53 return _parser.ReadObject();
54 }
55
56 return _parser.ReadImplicit(_constructed, tag);
57 }
58
59 public Asn1Object ToAsn1Object()
60 {
61 try
62 {
63 return _parser.ReadTaggedObject(_constructed, _tagNumber);
64 }
65 catch (IOException e)
66 {
67 throw new Asn1ParsingException(e.Message);
68 }
69 }
70 }
71 }
1 using System;
2
3 namespace Org.BouncyCastle.Asn1
4 {
5 public class BerApplicationSpecific
6 : DerApplicationSpecific
7 {
8 public BerApplicationSpecific(
9 int tagNo,
10 Asn1EncodableVector vec)
11 : base(tagNo, vec)
12 {
13 }
14 }
15 }
1 using System;
2
3 namespace Org.BouncyCastle.Asn1
4 {
5 public class BerApplicationSpecificParser
6 : IAsn1ApplicationSpecificParser
7 {
8 private readonly int tag;
9 private readonly Asn1StreamParser parser;
10
11 internal BerApplicationSpecificParser(
12 int tag,
13 Asn1StreamParser parser)
14 {
15 this.tag = tag;
16 this.parser = parser;
17 }
18
19 public IAsn1Convertible ReadObject()
20 {
21 return parser.ReadObject();
22 }
23
24 public Asn1Object ToAsn1Object()
25 {
26 return new BerApplicationSpecific(tag, parser.ReadVector());
27 }
28 }
29 }
1 using System;
2
3 namespace Org.BouncyCastle.Asn1
4 {
5 /**
6 * A BER Null object.
7 */
8 public class BerNull
9 : DerNull
10 {
11 public static new readonly BerNull Instance = new BerNull(0);
12
13 [Obsolete("Use static Instance object")]
14 public BerNull()
15 {
16 }
17
18 private BerNull(int dummy) : base(dummy)
19 {
20 }
21
22 internal override void Encode(
23 DerOutputStream derOut)
24 {
25 if (derOut is Asn1OutputStream || derOut is BerOutputStream)
26 {
27 derOut.WriteByte(Asn1Tags.Null);
28 }
29 else
30 {
31 base.Encode(derOut);
32 }
33 }
34 }
35 }
1 using System;
2 using System.Collections;
3 using System.IO;
4
5 using Org.BouncyCastle.Utilities;
6
7 namespace Org.BouncyCastle.Asn1
8 {
9 public class BerOctetString
10 : DerOctetString, IEnumerable
11 {
12 public static BerOctetString FromSequence(Asn1Sequence seq)
13 {
14 IList v = Platform.CreateArrayList();
15
16 foreach (Asn1Encodable obj in seq)
17 {
18 v.Add(obj);
19 }
20
21 return new BerOctetString(v);
22 }
23
24 private const int MaxLength = 1000;
25
26 /**
27 * convert a vector of octet strings into a single byte string
28 */
29 private static byte[] ToBytes(
30 IEnumerable octs)
31 {
32 MemoryStream bOut = new MemoryStream();
33 foreach (DerOctetString o in octs)
34 {
35 byte[] octets = o.GetOctets();
36 bOut.Write(octets, 0, octets.Length);
37 }
38 return bOut.ToArray();
39 }
40
41 private readonly IEnumerable octs;
42
43 /// <param name="str">The octets making up the octet string.</param>
44 public BerOctetString(
45 byte[] str)
46 : base(str)
47 {
48 }
49
50 public BerOctetString(
51 IEnumerable octets)
52 : base(ToBytes(octets))
53 {
54 this.octs = octets;
55 }
56
57 public BerOctetString(
58 Asn1Object obj)
59 : base(obj)
60 {
61 }
62
63 public BerOctetString(
64 Asn1Encodable obj)
65 : base(obj.ToAsn1Object())
66 {
67 }
68
69 public override byte[] GetOctets()
70 {
71 return str;
72 }
73
74 /**
75 * return the DER octets that make up this string.
76 */
77 public IEnumerator GetEnumerator()
78 {
79 if (octs == null)
80 {
81 return GenerateOcts().GetEnumerator();
82 }
83
84 return octs.GetEnumerator();
85 }
86
87 [Obsolete("Use GetEnumerator() instead")]
88 public IEnumerator GetObjects()
89 {
90 return GetEnumerator();
91 }
92
93 private IList GenerateOcts()
94 {
95 IList vec = Platform.CreateArrayList();
96 for (int i = 0; i < str.Length; i += MaxLength)
97 {
98 int end = System.Math.Min(str.Length, i + MaxLength);
99
100 byte[] nStr = new byte[end - i];
101
102 Array.Copy(str, i, nStr, 0, nStr.Length);
103
104 vec.Add(new DerOctetString(nStr));
105 }
106 return vec;
107 }
108
109 internal override void Encode(
110 DerOutputStream derOut)
111 {
112 if (derOut is Asn1OutputStream || derOut is BerOutputStream)
113 {
114 derOut.WriteByte(Asn1Tags.Constructed | Asn1Tags.OctetString);
115
116 derOut.WriteByte(0x80);
117
118 //
119 // write out the octet array
120 //
121 foreach (DerOctetString oct in this)
122 {
123 derOut.WriteObject(oct);
124 }
125
126 derOut.WriteByte(0x00);
127 derOut.WriteByte(0x00);
128 }
129 else
130 {
131 base.Encode(derOut);
132 }
133 }
134 }
135 }
1 using System;
2 using System.IO;
3
4 namespace Org.BouncyCastle.Asn1
5 {
6 // TODO Make Obsolete in favour of Asn1OutputStream?
7 public class BerOutputStream
8 : DerOutputStream
9 {
10 public BerOutputStream(Stream os) : base(os)
11 {
12 }
13
14 [Obsolete("Use version taking an Asn1Encodable arg instead")]
15 public override void WriteObject(
16 object obj)
17 {
18 if (obj == null)
19 {
20 WriteNull();
21 }
22 else if (obj is Asn1Object)
23 {
24 ((Asn1Object)obj).Encode(this);
25 }
26 else if (obj is Asn1Encodable)
27 {
28 ((Asn1Encodable)obj).ToAsn1Object().Encode(this);
29 }
30 else
31 {
32 throw new IOException("object not BerEncodable");
33 }
34 }
35 }
36 }
1 namespace Org.BouncyCastle.Asn1
2 {
3 public class BerSequence
4 : DerSequence
5 {
6 public static new readonly BerSequence Empty = new BerSequence();
7
8 public static new BerSequence FromVector(
9 Asn1EncodableVector v)
10 {
11 return v.Count < 1 ? Empty : new BerSequence(v);
12 }
13
14 /**
15 * create an empty sequence
16 */
17 public BerSequence()
18 {
19 }
20
21 /**
22 * create a sequence containing one object
23 */
24 public BerSequence(
25 Asn1Encodable obj)
26 : base(obj)
27 {
28 }
29
30 public BerSequence(
31 params Asn1Encodable[] v)
32 : base(v)
33 {
34 }
35
36 /**
37 * create a sequence containing a vector of objects.
38 */
39 public BerSequence(
40 Asn1EncodableVector v)
41 : base(v)
42 {
43 }
44
45 /*
46 */
47 internal override void Encode(
48 DerOutputStream derOut)
49 {
50 if (derOut is Asn1OutputStream || derOut is BerOutputStream)
51 {
52 derOut.WriteByte(Asn1Tags.Sequence | Asn1Tags.Constructed);
53 derOut.WriteByte(0x80);
54
55 foreach (Asn1Encodable o in this)
56 {
57 derOut.WriteObject(o);
58 }
59
60 derOut.WriteByte(0x00);
61 derOut.WriteByte(0x00);
62 }
63 else
64 {
65 base.Encode(derOut);
66 }
67 }
68 }
69 }
1 namespace Org.BouncyCastle.Asn1
2 {
3 public class BerSet
4 : DerSet
5 {
6 public static new readonly BerSet Empty = new BerSet();
7
8 public static new BerSet FromVector(
9 Asn1EncodableVector v)
10 {
11 return v.Count < 1 ? Empty : new BerSet(v);
12 }
13
14 internal static new BerSet FromVector(
15 Asn1EncodableVector v,
16 bool needsSorting)
17 {
18 return v.Count < 1 ? Empty : new BerSet(v, needsSorting);
19 }
20
21 /**
22 * create an empty sequence
23 */
24 public BerSet()
25 {
26 }
27
28 /**
29 * create a set containing one object
30 */
31 public BerSet(Asn1Encodable obj) : base(obj)
32 {
33 }
34
35 /**
36 * create a set containing a vector of objects.
37 */
38 public BerSet(Asn1EncodableVector v) : base(v, false)
39 {
40 }
41
42 internal BerSet(Asn1EncodableVector v, bool needsSorting) : base(v, needsSorting)
43 {
44 }
45
46 /*
47 */
48 internal override void Encode(
49 DerOutputStream derOut)
50 {
51 if (derOut is Asn1OutputStream || derOut is BerOutputStream)
52 {
53 derOut.WriteByte(Asn1Tags.Set | Asn1Tags.Constructed);
54 derOut.WriteByte(0x80);
55
56 foreach (Asn1Encodable o in this)
57 {
58 derOut.WriteObject(o);
59 }
60
61 derOut.WriteByte(0x00);
62 derOut.WriteByte(0x00);
63 }
64 else
65 {
66 base.Encode(derOut);
67 }
68 }
69 }
70 }
1 using System;
2 using System.Collections;
3
4 using Org.BouncyCastle.Utilities;
5
6 namespace Org.BouncyCastle.Asn1
7 {
8 /**
9 * BER TaggedObject - in ASN.1 notation this is any object preceded by
10 * a [n] where n is some number - these are assumed to follow the construction
11 * rules (as with sequences).
12 */
13 public class BerTaggedObject
14 : DerTaggedObject
15 {
16 /**
17 * @param tagNo the tag number for this object.
18 * @param obj the tagged object.
19 */
20 public BerTaggedObject(
21 int tagNo,
22 Asn1Encodable obj)
23 : base(tagNo, obj)
24 {
25 }
26
27 /**
28 * @param explicitly true if an explicitly tagged object.
29 * @param tagNo the tag number for this object.
30 * @param obj the tagged object.
31 */
32 public BerTaggedObject(
33 bool explicitly,
34 int tagNo,
35 Asn1Encodable obj)
36 : base(explicitly, tagNo, obj)
37 {
38 }
39
40 /**
41 * create an implicitly tagged object that contains a zero
42 * length sequence.
43 */
44 public BerTaggedObject(
45 int tagNo)
46 : base(false, tagNo, BerSequence.Empty)
47 {
48 }
49
50 internal override void Encode(
51 DerOutputStream derOut)
52 {
53 if (derOut is Asn1OutputStream || derOut is BerOutputStream)
54 {
55 derOut.WriteTag((byte)(Asn1Tags.Constructed | Asn1Tags.Tagged), tagNo);
56 derOut.WriteByte(0x80);
57
58 if (!IsEmpty())
59 {
60 if (!explicitly)
61 {
62 IEnumerable eObj;
63 if (obj is Asn1OctetString)
64 {
65 if (obj is BerOctetString)
66 {
67 eObj = (BerOctetString) obj;
68 }
69 else
70 {
71 Asn1OctetString octs = (Asn1OctetString)obj;
72 eObj = new BerOctetString(octs.GetOctets());
73 }
74 }
75 else if (obj is Asn1Sequence)
76 {
77 eObj = (Asn1Sequence) obj;
78 }
79 else if (obj is Asn1Set)
80 {
81 eObj = (Asn1Set) obj;
82 }
83 else
84 {
85 throw Platform.CreateNotImplementedException(Platform.GetTypeName(obj));
86 }
87
88 foreach (Asn1Encodable o in eObj)
89 {
90 derOut.WriteObject(o);
91 }
92 }
93 else
94 {
95 derOut.WriteObject(obj);
96 }
97 }
98
99 derOut.WriteByte(0x00);
100 derOut.WriteByte(0x00);
101 }
102 else
103 {
104 base.Encode(derOut);
105 }
106 }
107 }
108 }
1 using System.IO;
2
3 using Org.BouncyCastle.Utilities.IO;
4
5 namespace Org.BouncyCastle.Asn1
6 {
7 internal class ConstructedOctetStream
8 : BaseInputStream
9 {
10 private readonly Asn1StreamParser _parser;
11
12 private bool _first = true;
13 private Stream _currentStream;
14
15 internal ConstructedOctetStream(
16 Asn1StreamParser parser)
17 {
18 _parser = parser;
19 }
20
21 public override int Read(byte[] buffer, int offset, int count)
22 {
23 if (_currentStream == null)
24 {
25 if (!_first)
26 return 0;
27
28 Asn1OctetStringParser s = (Asn1OctetStringParser)_parser.ReadObject();
29
30 if (s == null)
31 return 0;
32
33 _first = false;
34 _currentStream = s.GetOctetStream();
35 }
36
37 int totalRead = 0;
38
39 for (;;)
40 {
41 int numRead = _currentStream.Read(buffer, offset + totalRead, count - totalRead);
42
43 if (numRead > 0)
44 {
45 totalRead += numRead;
46
47 if (totalRead == count)
48 return totalRead;
49 }
50 else
51 {
52 Asn1OctetStringParser aos = (Asn1OctetStringParser)_parser.ReadObject();
53
54 if (aos == null)
55 {
56 _currentStream = null;
57 return totalRead;
58 }
59
60 _currentStream = aos.GetOctetStream();
61 }
62 }
63 }
64
65 public override int ReadByte()
66 {
67 if (_currentStream == null)
68 {
69 if (!_first)
70 return 0;
71
72 Asn1OctetStringParser s = (Asn1OctetStringParser)_parser.ReadObject();
73
74 if (s == null)
75 return 0;
76
77 _first = false;
78 _currentStream = s.GetOctetStream();
79 }
80
81 for (;;)
82 {
83 int b = _currentStream.ReadByte();
84
85 if (b >= 0)
86 {
87 return b;
88 }
89
90 Asn1OctetStringParser aos = (Asn1OctetStringParser)_parser.ReadObject();
91
92 if (aos == null)
93 {
94 _currentStream = null;
95 return -1;
96 }
97
98 _currentStream = aos.GetOctetStream();
99 }
100 }
101 }
102 }
1 using System;
2 using System.IO;
3
4 using Org.BouncyCastle.Utilities;
5
6 namespace Org.BouncyCastle.Asn1
7 {
8 /**
9 * Class representing the DER-type External
10 */
11 public class DerExternal
12 : Asn1Object
13 {
14 private DerObjectIdentifier directReference;
15 private DerInteger indirectReference;
16 private Asn1Object dataValueDescriptor;
17 private int encoding;
18 private Asn1Object externalContent;
19
20 public DerExternal(
21 Asn1EncodableVector vector)
22 {
23 int offset = 0;
24 Asn1Object enc = GetObjFromVector(vector, offset);
25 if (enc is DerObjectIdentifier)
26 {
27 directReference = (DerObjectIdentifier)enc;
28 offset++;
29 enc = GetObjFromVector(vector, offset);
30 }
31 if (enc is DerInteger)
32 {
33 indirectReference = (DerInteger) enc;
34 offset++;
35 enc = GetObjFromVector(vector, offset);
36 }
37 if (!(enc is Asn1TaggedObject))
38 {
39 dataValueDescriptor = enc;
40 offset++;
41 enc = GetObjFromVector(vector, offset);
42 }
43
44 if (vector.Count != offset + 1)
45 throw new ArgumentException("input vector too large", "vector");
46
47 if (!(enc is Asn1TaggedObject))
48 throw new ArgumentException("No tagged object found in vector. Structure doesn't seem to be of type External", "vector");
49
50 Asn1TaggedObject obj = (Asn1TaggedObject)enc;
51
52 // Use property accessor to include check on value
53 Encoding = obj.TagNo;
54
55 if (encoding < 0 || encoding > 2)
56 throw new InvalidOperationException("invalid encoding value");
57
58 externalContent = obj.GetObject();
59 }
60
61 /**
62 * Creates a new instance of DerExternal
63 * See X.690 for more informations about the meaning of these parameters
64 * @param directReference The direct reference or <code>null</code> if not set.
65 * @param indirectReference The indirect reference or <code>null</code> if not set.
66 * @param dataValueDescriptor The data value descriptor or <code>null</code> if not set.
67 * @param externalData The external data in its encoded form.
68 */
69 public DerExternal(DerObjectIdentifier directReference, DerInteger indirectReference, Asn1Object dataValueDescriptor, DerTaggedObject externalData)
70 : this(directReference, indirectReference, dataValueDescriptor, externalData.TagNo, externalData.ToAsn1Object())
71 {
72 }
73
74 /**
75 * Creates a new instance of DerExternal.
76 * See X.690 for more informations about the meaning of these parameters
77 * @param directReference The direct reference or <code>null</code> if not set.
78 * @param indirectReference The indirect reference or <code>null</code> if not set.
79 * @param dataValueDescriptor The data value descriptor or <code>null</code> if not set.
80 * @param encoding The encoding to be used for the external data
81 * @param externalData The external data
82 */
83 public DerExternal(DerObjectIdentifier directReference, DerInteger indirectReference, Asn1Object dataValueDescriptor, int encoding, Asn1Object externalData)
84 {
85 DirectReference = directReference;
86 IndirectReference = indirectReference;
87 DataValueDescriptor = dataValueDescriptor;
88 Encoding = encoding;
89 ExternalContent = externalData.ToAsn1Object();
90 }
91
92 internal override void Encode(DerOutputStream derOut)
93 {
94 MemoryStream ms = new MemoryStream();
95 WriteEncodable(ms, directReference);
96 WriteEncodable(ms, indirectReference);
97 WriteEncodable(ms, dataValueDescriptor);
98 WriteEncodable(ms, new DerTaggedObject(Asn1Tags.External, externalContent));
99
100 derOut.WriteEncoded(Asn1Tags.Constructed, Asn1Tags.External, ms.ToArray());
101 }
102
103 protected override int Asn1GetHashCode()
104 {
105 int ret = externalContent.GetHashCode();
106 if (directReference != null)
107 {
108 ret ^= directReference.GetHashCode();
109 }
110 if (indirectReference != null)
111 {
112 ret ^= indirectReference.GetHashCode();
113 }
114 if (dataValueDescriptor != null)
115 {
116 ret ^= dataValueDescriptor.GetHashCode();
117 }
118 return ret;
119 }
120
121 protected override bool Asn1Equals(
122 Asn1Object asn1Object)
123 {
124 if (this == asn1Object)
125 return true;
126
127 DerExternal other = asn1Object as DerExternal;
128
129 if (other == null)
130 return false;
131
132 return Platform.Equals(directReference, other.directReference)
133 && Platform.Equals(indirectReference, other.indirectReference)
134 && Platform.Equals(dataValueDescriptor, other.dataValueDescriptor)
135 && externalContent.Equals(other.externalContent);
136 }
137
138 public Asn1Object DataValueDescriptor
139 {
140 get { return dataValueDescriptor; }
141 set { this.dataValueDescriptor = value; }
142 }
143
144 public DerObjectIdentifier DirectReference
145 {
146 get { return directReference; }
147 set { this.directReference = value; }
148 }
149
150 /**
151 * The encoding of the content. Valid values are
152 * <ul>
153 * <li><code>0</code> single-ASN1-type</li>
154 * <li><code>1</code> OCTET STRING</li>
155 * <li><code>2</code> BIT STRING</li>
156 * </ul>
157 */
158 public int Encoding
159 {
160 get
161 {
162 return encoding;
163 }
164 set
165 {
166 if (encoding < 0 || encoding > 2)
167 throw new InvalidOperationException("invalid encoding value: " + encoding);
168
169 this.encoding = value;
170 }
171 }
172
173 public Asn1Object ExternalContent
174 {
175 get { return externalContent; }
176 set { this.externalContent = value; }
177 }
178
179 public DerInteger IndirectReference
180 {
181 get { return indirectReference; }
182 set { this.indirectReference = value; }
183 }
184
185 private static Asn1Object GetObjFromVector(Asn1EncodableVector v, int index)
186 {
187 if (v.Count <= index)
188 throw new ArgumentException("too few objects in input vector", "v");
189
190 return v[index].ToAsn1Object();
191 }
192
193 private static void WriteEncodable(MemoryStream ms, Asn1Encodable e)
194 {
195 if (e != null)
196 {
197 byte[] bs = e.GetDerEncoded();
198 ms.Write(bs, 0, bs.Length);
199 }
200 }
201 }
202 }
1 using System;
2 using System.IO;
3
4 namespace Org.BouncyCastle.Asn1
5 {
6 public class DerExternalParser
7 : Asn1Encodable
8 {
9 private readonly Asn1StreamParser _parser;
10
11 public DerExternalParser(Asn1StreamParser parser)
12 {
13 this._parser = parser;
14 }
15
16 public IAsn1Convertible ReadObject()
17 {
18 return _parser.ReadObject();
19 }
20
21 public override Asn1Object ToAsn1Object()
22 {
23 return new DerExternal(_parser.ReadVector());
24 }
25 }
26 }
1 using System.IO;
2
3 using Org.BouncyCastle.Utilities.IO;
4
5 namespace Org.BouncyCastle.Asn1
6 {
7 public abstract class DerGenerator
8 : Asn1Generator
9 {
10 private bool _tagged = false;
11 private bool _isExplicit;
12 private int _tagNo;
13
14 protected DerGenerator(
15 Stream outStream)
16 : base(outStream)
17 {
18 }
19
20 protected DerGenerator(
21 Stream outStream,
22 int tagNo,
23 bool isExplicit)
24 : base(outStream)
25 {
26 _tagged = true;
27 _isExplicit = isExplicit;
28 _tagNo = tagNo;
29 }
30
31 private static void WriteLength(
32 Stream outStr,
33 int length)
34 {
35 if (length > 127)
36 {
37 int size = 1;
38 int val = length;
39
40 while ((val >>= 8) != 0)
41 {
42 size++;
43 }
44
45 outStr.WriteByte((byte)(size | 0x80));
46
47 for (int i = (size - 1) * 8; i >= 0; i -= 8)
48 {
49 outStr.WriteByte((byte)(length >> i));
50 }
51 }
52 else
53 {
54 outStr.WriteByte((byte)length);
55 }
56 }
57
58 internal static void WriteDerEncoded(
59 Stream outStream,
60 int tag,
61 byte[] bytes)
62 {
63 outStream.WriteByte((byte) tag);
64 WriteLength(outStream, bytes.Length);
65 outStream.Write(bytes, 0, bytes.Length);
66 }
67
68 internal void WriteDerEncoded(
69 int tag,
70 byte[] bytes)
71 {
72 if (_tagged)
73 {
74 int tagNum = _tagNo | Asn1Tags.Tagged;
75
76 if (_isExplicit)
77 {
78 int newTag = _tagNo | Asn1Tags.Constructed | Asn1Tags.Tagged;
79 MemoryStream bOut = new MemoryStream();
80 WriteDerEncoded(bOut, tag, bytes);
81 WriteDerEncoded(Out, newTag, bOut.ToArray());
82 }
83 else
84 {
85 if ((tag & Asn1Tags.Constructed) != 0)
86 {
87 tagNum |= Asn1Tags.Constructed;
88 }
89
90 WriteDerEncoded(Out, tagNum, bytes);
91 }
92 }
93 else
94 {
95 WriteDerEncoded(Out, tag, bytes);
96 }
97 }
98
99 internal static void WriteDerEncoded(
100 Stream outStr,
101 int tag,
102 Stream inStr)
103 {
104 WriteDerEncoded(outStr, tag, Streams.ReadAll(inStr));
105 }
106 }
107 }
1 using System;
2 using System.IO;
3
4 using Org.BouncyCastle.Utilities.IO;
5
6 namespace Org.BouncyCastle.Asn1
7 {
8 public class DerOctetStringParser
9 : Asn1OctetStringParser
10 {
11 private readonly DefiniteLengthInputStream stream;
12
13 internal DerOctetStringParser(
14 DefiniteLengthInputStream stream)
15 {
16 this.stream = stream;
17 }
18
19 public Stream GetOctetStream()
20 {
21 return stream;
22 }
23
24 public Asn1Object ToAsn1Object()
25 {
26 try
27 {
28 return new DerOctetString(stream.ToArray());
29 }
30 catch (IOException e)
31 {
32 throw new InvalidOperationException("IOException converting stream to byte array: " + e.Message, e);
33 }
34 }
35 }
36 }
1 using System.IO;
2
3 namespace Org.BouncyCastle.Asn1
4 {
5 public class DerSequenceGenerator
6 : DerGenerator
7 {
8 private readonly MemoryStream _bOut = new MemoryStream();
9
10 public DerSequenceGenerator(
11 Stream outStream)
12 : base(outStream)
13 {
14 }
15
16 public DerSequenceGenerator(
17 Stream outStream,
18 int tagNo,
19 bool isExplicit)
20 : base(outStream, tagNo, isExplicit)
21 {
22 }
23
24 public override void AddObject(
25 Asn1Encodable obj)
26 {
27 new DerOutputStream(_bOut).WriteObject(obj);
28 }
29
30 public override Stream GetRawOutputStream()
31 {
32 return _bOut;
33 }
34
35 public override void Close()
36 {
37 WriteDerEncoded(Asn1Tags.Constructed | Asn1Tags.Sequence, _bOut.ToArray());
38 }
39 }
40 }
1 namespace Org.BouncyCastle.Asn1
2 {
3 public class DerSequenceParser
4 : Asn1SequenceParser
5 {
6 private readonly Asn1StreamParser _parser;
7
8 internal DerSequenceParser(
9 Asn1StreamParser parser)
10 {
11 this._parser = parser;
12 }
13
14 public IAsn1Convertible ReadObject()
15 {
16 return _parser.ReadObject();
17 }
18
19 public Asn1Object ToAsn1Object()
20 {
21 return new DerSequence(_parser.ReadVector());
22 }
23 }
24 }
1 using System.IO;
2
3 namespace Org.BouncyCastle.Asn1
4 {
5 public class DerSetGenerator
6 : DerGenerator
7 {
8 private readonly MemoryStream _bOut = new MemoryStream();
9
10 public DerSetGenerator(
11 Stream outStream)
12 : base(outStream)
13 {
14 }
15
16 public DerSetGenerator(
17 Stream outStream,
18 int tagNo,
19 bool isExplicit)
20 : base(outStream, tagNo, isExplicit)
21 {
22 }
23
24 public override void AddObject(
25 Asn1Encodable obj)
26 {
27 new DerOutputStream(_bOut).WriteObject(obj);
28 }
29
30 public override Stream GetRawOutputStream()
31 {
32 return _bOut;
33 }
34
35 public override void Close()
36 {
37 WriteDerEncoded(Asn1Tags.Constructed | Asn1Tags.Set, _bOut.ToArray());
38 }
39 }
40 }
1 namespace Org.BouncyCastle.Asn1
2 {
3 public class DerSetParser
4 : Asn1SetParser
5 {
6 private readonly Asn1StreamParser _parser;
7
8 internal DerSetParser(
9 Asn1StreamParser parser)
10 {
11 this._parser = parser;
12 }
13
14 public IAsn1Convertible ReadObject()
15 {
16 return _parser.ReadObject();
17 }
18
19 public Asn1Object ToAsn1Object()
20 {
21 return new DerSet(_parser.ReadVector(), false);
22 }
23 }
24 }
1 using System;
2 using System.IO;
3
4 using Org.BouncyCastle.Utilities.IO;
5
6 namespace Org.BouncyCastle.Asn1
7 {
8 class DefiniteLengthInputStream
9 : LimitedInputStream
10 {
11 private static readonly byte[] EmptyBytes = new byte[0];
12
13 private readonly int _originalLength;
14 private int _remaining;
15
16 internal DefiniteLengthInputStream(
17 Stream inStream,
18 int length)
19 : base(inStream, length)
20 {
21 if (length < 0)
22 throw new ArgumentException("negative lengths not allowed", "length");
23
24 this._originalLength = length;
25 this._remaining = length;
26
27 if (length == 0)
28 {
29 SetParentEofDetect(true);
30 }
31 }
32
33 internal int Remaining
34 {
35 get { return _remaining; }
36 }
37
38 public override int ReadByte()
39 {
40 if (_remaining == 0)
41 return -1;
42
43 int b = _in.ReadByte();
44
45 if (b < 0)
46 throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining);
47
48 if (--_remaining == 0)
49 {
50 SetParentEofDetect(true);
51 }
52
53 return b;
54 }
55
56 public override int Read(
57 byte[] buf,
58 int off,
59 int len)
60 {
61 if (_remaining == 0)
62 return 0;
63
64 int toRead = System.Math.Min(len, _remaining);
65 int numRead = _in.Read(buf, off, toRead);
66
67 if (numRead < 1)
68 throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining);
69
70 if ((_remaining -= numRead) == 0)
71 {
72 SetParentEofDetect(true);
73 }
74
75 return numRead;
76 }
77
78 internal void ReadAllIntoByteArray(byte[] buf)
79 {
80 if (_remaining != buf.Length)
81 throw new ArgumentException("buffer length not right for data");
82
83 if ((_remaining -= Streams.ReadFully(_in, buf)) != 0)
84 throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining);
85 SetParentEofDetect(true);
86 }
87
88 internal byte[] ToArray()
89 {
90 if (_remaining == 0)
91 return EmptyBytes;
92
93 byte[] bytes = new byte[_remaining];
94 if ((_remaining -= Streams.ReadFully(_in, bytes)) != 0)
95 throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining);
96 SetParentEofDetect(true);
97 return bytes;
98 }
99 }
100 }
1 using System;
2 using System.IO;
3
4 using Org.BouncyCastle.Utilities;
5
6 namespace Org.BouncyCastle.Asn1
7 {
8 /**
9 * Base class for an application specific object
10 */
11 public class DerApplicationSpecific
12 : Asn1Object
13 {
14 private readonly bool isConstructed;
15 private readonly int tag;
16 private readonly byte[] octets;
17
18 internal DerApplicationSpecific(
19 bool isConstructed,
20 int tag,
21 byte[] octets)
22 {
23 this.isConstructed = isConstructed;
24 this.tag = tag;
25 this.octets = octets;
26 }
27
28 public DerApplicationSpecific(
29 int tag,
30 byte[] octets)
31 : this(false, tag, octets)
32 {
33 }
34
35 public DerApplicationSpecific(
36 int tag,
37 Asn1Encodable obj)
38 : this(true, tag, obj)
39 {
40 }
41
42 public DerApplicationSpecific(
43 bool isExplicit,
44 int tag,
45 Asn1Encodable obj)
46 {
47 Asn1Object asn1Obj = obj.ToAsn1Object();
48
49 byte[] data = asn1Obj.GetDerEncoded();
50
51 this.isConstructed = Asn1TaggedObject.IsConstructed(isExplicit, asn1Obj);
52 this.tag = tag;
53
54 if (isExplicit)
55 {
56 this.octets = data;
57 }
58 else
59 {
60 int lenBytes = GetLengthOfHeader(data);
61 byte[] tmp = new byte[data.Length - lenBytes];
62 Array.Copy(data, lenBytes, tmp, 0, tmp.Length);
63 this.octets = tmp;
64 }
65 }
66
67 public DerApplicationSpecific(
68 int tagNo,
69 Asn1EncodableVector vec)
70 {
71 this.tag = tagNo;
72 this.isConstructed = true;
73 MemoryStream bOut = new MemoryStream();
74
75 for (int i = 0; i != vec.Count; i++)
76 {
77 try
78 {
79 byte[] bs = vec[i].GetDerEncoded();
80 bOut.Write(bs, 0, bs.Length);
81 }
82 catch (IOException e)
83 {
84 throw new InvalidOperationException("malformed object", e);
85 }
86 }
87 this.octets = bOut.ToArray();
88 }
89
90 private int GetLengthOfHeader(
91 byte[] data)
92 {
93 int length = data[1]; // TODO: assumes 1 byte tag
94
95 if (length == 0x80)
96 {
97 return 2; // indefinite-length encoding
98 }
99
100 if (length > 127)
101 {
102 int size = length & 0x7f;
103
104 // Note: The invalid long form "0xff" (see X.690 8.1.3.5c) will be caught here
105 if (size > 4)
106 {
107 throw new InvalidOperationException("DER length more than 4 bytes: " + size);
108 }
109
110 return size + 2;
111 }
112
113 return 2;
114 }
115
116 public bool IsConstructed()
117 {
118 return isConstructed;
119 }
120
121 public byte[] GetContents()
122 {
123 return octets;
124 }
125
126 public int ApplicationTag
127 {
128 get { return tag; }
129 }
130
131 /**
132 * Return the enclosed object assuming explicit tagging.
133 *
134 * @return the resulting object
135 * @throws IOException if reconstruction fails.
136 */
137 public Asn1Object GetObject()
138 {
139 return FromByteArray(GetContents());
140 }
141
142 /**
143 * Return the enclosed object assuming implicit tagging.
144 *
145 * @param derTagNo the type tag that should be applied to the object's contents.
146 * @return the resulting object
147 * @throws IOException if reconstruction fails.
148 */
149 public Asn1Object GetObject(
150 int derTagNo)
151 {
152 if (derTagNo >= 0x1f)
153 throw new IOException("unsupported tag number");
154
155 byte[] orig = this.GetEncoded();
156 byte[] tmp = ReplaceTagNumber(derTagNo, orig);
157
158 if ((orig[0] & Asn1Tags.Constructed) != 0)
159 {
160 tmp[0] |= Asn1Tags.Constructed;
161 }
162
163 return FromByteArray(tmp);
164 }
165
166 internal override void Encode(
167 DerOutputStream derOut)
168 {
169 int classBits = Asn1Tags.Application;
170 if (isConstructed)
171 {
172 classBits |= Asn1Tags.Constructed;
173 }
174
175 derOut.WriteEncoded(classBits, tag, octets);
176 }
177
178 protected override bool Asn1Equals(
179 Asn1Object asn1Object)
180 {
181 DerApplicationSpecific other = asn1Object as DerApplicationSpecific;
182
183 if (other == null)
184 return false;
185
186 return this.isConstructed == other.isConstructed
187 && this.tag == other.tag
188 && Arrays.AreEqual(this.octets, other.octets);
189 }
190
191 protected override int Asn1GetHashCode()
192 {
193 return isConstructed.GetHashCode() ^ tag.GetHashCode() ^ Arrays.GetHashCode(octets);
194 }
195
196 private byte[] ReplaceTagNumber(
197 int newTag,
198 byte[] input)
199 {
200 int tagNo = input[0] & 0x1f;
201 int index = 1;
202 //
203 // with tagged object tag number is bottom 5 bits, or stored at the start of the content
204 //
205 if (tagNo == 0x1f)
206 {
207 tagNo = 0;
208
209 int b = input[index++] & 0xff;
210
211 // X.690-0207 8.1.2.4.2
212 // "c) bits 7 to 1 of the first subsequent octet shall not all be zero."
213 if ((b & 0x7f) == 0) // Note: -1 will pass
214 {
215 throw new InvalidOperationException("corrupted stream - invalid high tag number found");
216 }
217
218 while ((b >= 0) && ((b & 0x80) != 0))
219 {
220 tagNo |= (b & 0x7f);
221 tagNo <<= 7;
222 b = input[index++] & 0xff;
223 }
224
225 tagNo |= (b & 0x7f);
226 }
227
228 byte[] tmp = new byte[input.Length - index + 1];
229
230 Array.Copy(input, index, tmp, 1, tmp.Length - 1);
231
232 tmp[0] = (byte)newTag;
233
234 return tmp;
235 }
236 }
237 }
1 using System;
2
3 using Org.BouncyCastle.Utilities;
4
5 namespace Org.BouncyCastle.Asn1
6 {
7 /**
8 * Der BMPString object.
9 */
10 public class DerBmpString
11 : DerStringBase
12 {
13 private readonly string str;
14
15 /**
16 * return a BMP string from the given object.
17 *
18 * @param obj the object we want converted.
19 * @exception ArgumentException if the object cannot be converted.
20 */
21 public static DerBmpString GetInstance(
22 object obj)
23 {
24 if (obj == null || obj is DerBmpString)
25 {
26 return (DerBmpString)obj;
27 }
28
29 throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj));
30 }
31
32 /**
33 * return a BMP string from a tagged object.
34 *
35 * @param obj the tagged object holding the object we want
36 * @param explicitly true if the object is meant to be explicitly
37 * tagged false otherwise.
38 * @exception ArgumentException if the tagged object cannot
39 * be converted.
40 */
41 public static DerBmpString GetInstance(
42 Asn1TaggedObject obj,
43 bool isExplicit)
44 {
45 Asn1Object o = obj.GetObject();
46
47 if (isExplicit || o is DerBmpString)
48 {
49 return GetInstance(o);
50 }
51
52 return new DerBmpString(Asn1OctetString.GetInstance(o).GetOctets());
53 }
54
55 /**
56 * basic constructor - byte encoded string.
57 */
58 public DerBmpString(
59 byte[] str)
60 {
61 if (str == null)
62 throw new ArgumentNullException("str");
63
64 char[] cs = new char[str.Length / 2];
65
66 for (int i = 0; i != cs.Length; i++)
67 {
68 cs[i] = (char)((str[2 * i] << 8) | (str[2 * i + 1] & 0xff));
69 }
70
71 this.str = new string(cs);
72 }
73
74 /**
75 * basic constructor
76 */
77 public DerBmpString(
78 string str)
79 {
80 if (str == null)
81 throw new ArgumentNullException("str");
82
83 this.str = str;
84 }
85
86 public override string GetString()
87 {
88 return str;
89 }
90
91 protected override bool Asn1Equals(
92 Asn1Object asn1Object)
93 {
94 DerBmpString other = asn1Object as DerBmpString;
95
96 if (other == null)
97 return false;
98
99 return this.str.Equals(other.str);
100 }
101
102 internal override void Encode(
103 DerOutputStream derOut)
104 {
105 char[] c = str.ToCharArray();
106 byte[] b = new byte[c.Length * 2];
107
108 for (int i = 0; i != c.Length; i++)
109 {
110 b[2 * i] = (byte)(c[i] >> 8);
111 b[2 * i + 1] = (byte)c[i];
112 }
113
114 derOut.WriteEncoded(Asn1Tags.BmpString, b);
115 }
116 }
117 }
1 using System;
2 using System.Diagnostics;
3 using System.Text;
4
5 using Org.BouncyCastle.Math;
6 using Org.BouncyCastle.Utilities;
7
8 namespace Org.BouncyCastle.Asn1
9 {
10 public class DerBitString
11 : DerStringBase
12 {
13 private static readonly char[] table
14 = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
15
16 protected readonly byte[] mData;
17 protected readonly int mPadBits;
18
19 /**
20 * return a Bit string from the passed in object
21 *
22 * @exception ArgumentException if the object cannot be converted.
23 */
24 public static DerBitString GetInstance(
25 object obj)
26 {
27 if (obj == null || obj is DerBitString)
28 {
29 return (DerBitString) obj;
30 }
31
32 throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj));
33 }
34
35 /**
36 * return a Bit string from a tagged object.
37 *
38 * @param obj the tagged object holding the object we want
39 * @param explicitly true if the object is meant to be explicitly
40 * tagged false otherwise.
41 * @exception ArgumentException if the tagged object cannot
42 * be converted.
43 */
44 public static DerBitString GetInstance(
45 Asn1TaggedObject obj,
46 bool isExplicit)
47 {
48 Asn1Object o = obj.GetObject();
49
50 if (isExplicit || o is DerBitString)
51 {
52 return GetInstance(o);
53 }
54
55 return FromAsn1Octets(((Asn1OctetString)o).GetOctets());
56 }
57
58 /**
59 * @param data the octets making up the bit string.
60 * @param padBits the number of extra bits at the end of the string.
61 */
62 public DerBitString(
63 byte[] data,
64 int padBits)
65 {
66 if (data == null)
67 throw new ArgumentNullException("data");
68 if (padBits < 0 || padBits > 7)
69 throw new ArgumentException("must be in the range 0 to 7", "padBits");
70 if (data.Length == 0 && padBits != 0)
71 throw new ArgumentException("if 'data' is empty, 'padBits' must be 0");
72
73 this.mData = Arrays.Clone(data);
74 this.mPadBits = padBits;
75 }
76
77 public DerBitString(
78 byte[] data)
79 : this(data, 0)
80 {
81 }
82
83 public DerBitString(
84 int namedBits)
85 {
86 if (namedBits == 0)
87 {
88 this.mData = new byte[0];
89 this.mPadBits = 0;
90 return;
91 }
92
93 int bits = BigInteger.BitLen(namedBits);
94 int bytes = (bits + 7) / 8;
95
96 Debug.Assert(0 < bytes && bytes <= 4);
97
98 byte[] data = new byte[bytes];
99 --bytes;
100
101 for (int i = 0; i < bytes; i++)
102 {
103 data[i] = (byte)namedBits;
104 namedBits >>= 8;
105 }
106
107 Debug.Assert((namedBits & 0xFF) != 0);
108
109 data[bytes] = (byte)namedBits;
110
111 int padBits = 0;
112 while ((namedBits & (1 << padBits)) == 0)
113 {
114 ++padBits;
115 }
116
117 Debug.Assert(padBits < 8);
118
119 this.mData = data;
120 this.mPadBits = padBits;
121 }
122
123 public DerBitString(
124 Asn1Encodable obj)
125 : this(obj.GetDerEncoded())
126 {
127 }
128
129 /**
130 * Return the octets contained in this BIT STRING, checking that this BIT STRING really
131 * does represent an octet aligned string. Only use this method when the standard you are
132 * following dictates that the BIT STRING will be octet aligned.
133 *
134 * @return a copy of the octet aligned data.
135 */
136 public virtual byte[] GetOctets()
137 {
138 if (mPadBits != 0)
139 throw new InvalidOperationException("attempt to get non-octet aligned data from BIT STRING");
140
141 return Arrays.Clone(mData);
142 }
143
144 public virtual byte[] GetBytes()
145 {
146 byte[] data = Arrays.Clone(mData);
147
148 // DER requires pad bits be zero
149 if (mPadBits > 0)
150 {
151 data[data.Length - 1] &= (byte)(0xFF << mPadBits);
152 }
153
154 return data;
155 }
156
157 public virtual int PadBits
158 {
159 get { return mPadBits; }
160 }
161
162 /**
163 * @return the value of the bit string as an int (truncating if necessary)
164 */
165 public virtual int IntValue
166 {
167 get
168 {
169 int value = 0, length = System.Math.Min(4, mData.Length);
170 for (int i = 0; i < length; ++i)
171 {
172 value |= (int)mData[i] << (8 * i);
173 }
174 if (mPadBits > 0 && length == mData.Length)
175 {
176 int mask = (1 << mPadBits) - 1;
177 value &= ~(mask << (8 * (length - 1)));
178 }
179 return value;
180 }
181 }
182
183 internal override void Encode(
184 DerOutputStream derOut)
185 {
186 if (mPadBits > 0)
187 {
188 int last = mData[mData.Length - 1];
189 int mask = (1 << mPadBits) - 1;
190 int unusedBits = last & mask;
191
192 if (unusedBits != 0)
193 {
194 byte[] contents = Arrays.Prepend(mData, (byte)mPadBits);
195
196 /*
197 * X.690-0207 11.2.1: Each unused bit in the final octet of the encoding of a bit string value shall be set to zero.
198 */
199 contents[contents.Length - 1] = (byte)(last ^ unusedBits);
200
201 derOut.WriteEncoded(Asn1Tags.BitString, contents);
202 return;
203 }
204 }
205
206 derOut.WriteEncoded(Asn1Tags.BitString, (byte)mPadBits, mData);
207 }
208
209 protected override int Asn1GetHashCode()
210 {
211 return mPadBits.GetHashCode() ^ Arrays.GetHashCode(mData);
212 }
213
214 protected override bool Asn1Equals(
215 Asn1Object asn1Object)
216 {
217 DerBitString other = asn1Object as DerBitString;
218
219 if (other == null)
220 return false;
221
222 return this.mPadBits == other.mPadBits
223 && Arrays.AreEqual(this.mData, other.mData);
224 }
225
226 public override string GetString()
227 {
228 StringBuilder buffer = new StringBuilder("#");
229
230 byte[] str = GetDerEncoded();
231
232 for (int i = 0; i != str.Length; i++)
233 {
234 uint ubyte = str[i];
235 buffer.Append(table[(ubyte >> 4) & 0xf]);
236 buffer.Append(table[str[i] & 0xf]);
237 }
238
239 return buffer.ToString();
240 }
241
242 internal static DerBitString FromAsn1Octets(byte[] octets)
243 {
244 if (octets.Length < 1)
245 throw new ArgumentException("truncated BIT STRING detected", "octets");
246
247 int padBits = octets[0];
248 byte[] data = Arrays.CopyOfRange(octets, 1, octets.Length);
249
250 if (padBits > 0 && padBits < 8 && data.Length > 0)
251 {
252 int last = data[data.Length - 1];
253 int mask = (1 << padBits) - 1;
254
255 if ((last & mask) != 0)
256 {
257 return new BerBitString(data, padBits);
258 }
259 }
260
261 return new DerBitString(data, padBits);
262 }
263 }
264 }
265
1 using System;
2
3 using Org.BouncyCastle.Utilities;
4
5 namespace Org.BouncyCastle.Asn1
6 {
7 public class DerBoolean
8 : Asn1Object
9 {
10 private readonly byte value;
11
12 public static readonly DerBoolean False = new DerBoolean(false);
13 public static readonly DerBoolean True = new DerBoolean(true);
14
15 /**
16 * return a bool from the passed in object.
17 *
18 * @exception ArgumentException if the object cannot be converted.
19 */
20 public static DerBoolean GetInstance(
21 object obj)
22 {
23 if (obj == null || obj is DerBoolean)
24 {
25 return (DerBoolean) obj;
26 }
27
28 throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj));
29 }
30
31 /**
32 * return a DerBoolean from the passed in bool.
33 */
34 public static DerBoolean GetInstance(
35 bool value)
36 {
37 return value ? True : False;
38 }
39
40 /**
41 * return a Boolean from a tagged object.
42 *
43 * @param obj the tagged object holding the object we want
44 * @param explicitly true if the object is meant to be explicitly
45 * tagged false otherwise.
46 * @exception ArgumentException if the tagged object cannot
47 * be converted.
48 */
49 public static DerBoolean GetInstance(
50 Asn1TaggedObject obj,
51 bool isExplicit)
52 {
53 Asn1Object o = obj.GetObject();
54
55 if (isExplicit || o is DerBoolean)
56 {
57 return GetInstance(o);
58 }
59
60 return FromOctetString(((Asn1OctetString)o).GetOctets());
61 }
62
63 public DerBoolean(
64 byte[] val)
65 {
66 if (val.Length != 1)
67 throw new ArgumentException("byte value should have 1 byte in it", "val");
68
69 // TODO Are there any constraints on the possible byte values?
70 this.value = val[0];
71 }
72
73 private DerBoolean(
74 bool value)
75 {
76 this.value = value ? (byte)0xff : (byte)0;
77 }
78
79 public bool IsTrue
80 {
81 get { return value != 0; }
82 }
83
84 internal override void Encode(
85 DerOutputStream derOut)
86 {
87 // TODO Should we make sure the byte value is one of '0' or '0xff' here?
88 derOut.WriteEncoded(Asn1Tags.Boolean, new byte[]{ value });
89 }
90
91 protected override bool Asn1Equals(
92 Asn1Object asn1Object)
93 {
94 DerBoolean other = asn1Object as DerBoolean;
95
96 if (other == null)
97 return false;
98
99 return IsTrue == other.IsTrue;
100 }
101
102 protected override int Asn1GetHashCode()
103 {
104 return IsTrue.GetHashCode();
105 }
106
107 public override string ToString()
108 {
109 return IsTrue ? "TRUE" : "FALSE";
110 }
111
112 internal static DerBoolean FromOctetString(byte[] value)
113 {
114 if (value.Length != 1)
115 {
116 throw new ArgumentException("BOOLEAN value should have 1 byte in it", "value");
117 }
118
119 byte b = value[0];
120
121 return b == 0 ? False : b == 0xFF ? True : new DerBoolean(value);
122 }
123 }
124 }
1 using System;
2
3 using Org.BouncyCastle.Math;
4 using Org.BouncyCastle.Utilities;
5
6 namespace Org.BouncyCastle.Asn1
7 {
8 public class DerEnumerated
9 : Asn1Object
10 {
11 private readonly byte[] bytes;
12
13 /**
14 * return an integer from the passed in object
15 *
16 * @exception ArgumentException if the object cannot be converted.
17 */
18 public static DerEnumerated GetInstance(
19 object obj)
20 {
21 if (obj == null || obj is DerEnumerated)
22 {
23 return (DerEnumerated)obj;
24 }
25
26 throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj));
27 }
28
29 /**
30 * return an Enumerated from a tagged object.
31 *
32 * @param obj the tagged object holding the object we want
33 * @param explicitly true if the object is meant to be explicitly
34 * tagged false otherwise.
35 * @exception ArgumentException if the tagged object cannot
36 * be converted.
37 */
38 public static DerEnumerated GetInstance(
39 Asn1TaggedObject obj,
40 bool isExplicit)
41 {
42 Asn1Object o = obj.GetObject();
43
44 if (isExplicit || o is DerEnumerated)
45 {
46 return GetInstance(o);
47 }
48
49 return FromOctetString(((Asn1OctetString)o).GetOctets());
50 }
51
52 public DerEnumerated(
53 int val)
54 {
55 bytes = BigInteger.ValueOf(val).ToByteArray();
56 }
57
58 public DerEnumerated(
59 BigInteger val)
60 {
61 bytes = val.ToByteArray();
62 }
63
64 public DerEnumerated(
65 byte[] bytes)
66 {
67 this.bytes = bytes;
68 }
69
70 public BigInteger Value
71 {
72 get { return new BigInteger(bytes); }
73 }
74
75 internal override void Encode(
76 DerOutputStream derOut)
77 {
78 derOut.WriteEncoded(Asn1Tags.Enumerated, bytes);
79 }
80
81 protected override bool Asn1Equals(
82 Asn1Object asn1Object)
83 {
84 DerEnumerated other = asn1Object as DerEnumerated;
85
86 if (other == null)
87 return false;
88
89 return Arrays.AreEqual(this.bytes, other.bytes);
90 }
91
92 protected override int Asn1GetHashCode()
93 {
94 return Arrays.GetHashCode(bytes);
95 }
96
97 private static readonly DerEnumerated[] cache = new DerEnumerated[12];
98
99 internal static DerEnumerated FromOctetString(byte[] enc)
100 {
101 if (enc.Length == 0)
102 {
103 throw new ArgumentException("ENUMERATED has zero length", "enc");
104 }
105
106 if (enc.Length == 1)
107 {
108 int value = enc[0];
109 if (value < cache.Length)
110 {
111 DerEnumerated cached = cache[value];
112 if (cached != null)
113 {
114 return cached;
115 }
116
117 return cache[value] = new DerEnumerated(Arrays.Clone(enc));
118 }
119 }
120
121 return new DerEnumerated(Arrays.Clone(enc));
122 }
123 }
124 }
1 using System;
2 using System.Text;
3
4 using Org.BouncyCastle.Utilities;
5
6 namespace Org.BouncyCastle.Asn1
7 {
8 public class DerGeneralString
9 : DerStringBase
10 {
11 private readonly string str;
12
13 public static DerGeneralString GetInstance(
14 object obj)
15 {
16 if (obj == null || obj is DerGeneralString)
17 {
18 return (DerGeneralString) obj;
19 }
20
21 throw new ArgumentException("illegal object in GetInstance: "
22 + Platform.GetTypeName(obj));
23 }
24
25 public static DerGeneralString GetInstance(
26 Asn1TaggedObject obj,
27 bool isExplicit)
28 {
29 Asn1Object o = obj.GetObject();
30
31 if (isExplicit || o is DerGeneralString)
32 {
33 return GetInstance(o);
34 }
35
36 return new DerGeneralString(((Asn1OctetString)o).GetOctets());
37 }
38
39 public DerGeneralString(
40 byte[] str)
41 : this(Strings.FromAsciiByteArray(str))
42 {
43 }
44
45 public DerGeneralString(
46 string str)
47 {
48 if (str == null)
49 throw new ArgumentNullException("str");
50
51 this.str = str;
52 }
53
54 public override string GetString()
55 {
56 return str;
57 }
58
59 public byte[] GetOctets()
60 {
61 return Strings.ToAsciiByteArray(str);
62 }
63
64 internal override void Encode(
65 DerOutputStream derOut)
66 {
67 derOut.WriteEncoded(Asn1Tags.GeneralString, GetOctets());
68 }
69
70 protected override bool Asn1Equals(
71 Asn1Object asn1Object)
72 {
73 DerGeneralString other = asn1Object as DerGeneralString;
74
75 if (other == null)
76 return false;
77
78 return this.str.Equals(other.str);
79 }
80 }
81 }
1 using System;
2 using System.Globalization;
3 using System.Text;
4
5 using Org.BouncyCastle.Utilities;
6
7 namespace Org.BouncyCastle.Asn1
8 {
9 /**
10 * Generalized time object.
11 */
12 public class DerGeneralizedTime
13 : Asn1Object
14 {
15 private readonly string time;
16
17 /**
18 * return a generalized time from the passed in object
19 *
20 * @exception ArgumentException if the object cannot be converted.
21 */
22 public static DerGeneralizedTime GetInstance(
23 object obj)
24 {
25 if (obj == null || obj is DerGeneralizedTime)
26 {
27 return (DerGeneralizedTime)obj;
28 }
29
30 throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj), "obj");
31 }
32
33 /**
34 * return a Generalized Time object from a tagged object.
35 *
36 * @param obj the tagged object holding the object we want
37 * @param explicitly true if the object is meant to be explicitly
38 * tagged false otherwise.
39 * @exception ArgumentException if the tagged object cannot
40 * be converted.
41 */
42 public static DerGeneralizedTime GetInstance(
43 Asn1TaggedObject obj,
44 bool isExplicit)
45 {
46 Asn1Object o = obj.GetObject();
47
48 if (isExplicit || o is DerGeneralizedTime)
49 {
50 return GetInstance(o);
51 }
52
53 return new DerGeneralizedTime(((Asn1OctetString)o).GetOctets());
54 }
55
56 /**
57 * The correct format for this is YYYYMMDDHHMMSS[.f]Z, or without the Z
58 * for local time, or Z+-HHMM on the end, for difference between local
59 * time and UTC time. The fractional second amount f must consist of at
60 * least one number with trailing zeroes removed.
61 *
62 * @param time the time string.
63 * @exception ArgumentException if string is an illegal format.
64 */
65 public DerGeneralizedTime(
66 string time)
67 {
68 this.time = time;
69
70 try
71 {
72 ToDateTime();
73 }
74 catch (FormatException e)
75 {
76 throw new ArgumentException("invalid date string: " + e.Message);
77 }
78 }
79
80 /**
81 * base constructor from a local time object
82 */
83 public DerGeneralizedTime(
84 DateTime time)
85 {
86 #if PORTABLE
87 this.time = time.ToUniversalTime().ToString(@"yyyyMMddHHmmss\Z");
88 #else
89 this.time = time.ToString(@"yyyyMMddHHmmss\Z");
90 #endif
91 }
92
93 internal DerGeneralizedTime(
94 byte[] bytes)
95 {
96 //
97 // explicitly convert to characters
98 //
99 this.time = Strings.FromAsciiByteArray(bytes);
100 }
101
102 /**
103 * Return the time.
104 * @return The time string as it appeared in the encoded object.
105 */
106 public string TimeString
107 {
108 get { return time; }
109 }
110
111 /**
112 * return the time - always in the form of
113 * YYYYMMDDhhmmssGMT(+hh:mm|-hh:mm).
114 * <p>
115 * Normally in a certificate we would expect "Z" rather than "GMT",
116 * however adding the "GMT" means we can just use:
117 * <pre>
118 * dateF = new SimpleDateFormat("yyyyMMddHHmmssz");
119 * </pre>
120 * To read in the time and Get a date which is compatible with our local
121 * time zone.</p>
122 */
123 public string GetTime()
124 {
125 //
126 // standardise the format.
127 //
128 if (time[time.Length - 1] == 'Z')
129 {
130 return time.Substring(0, time.Length - 1) + "GMT+00:00";
131 }
132 else
133 {
134 int signPos = time.Length - 5;
135 char sign = time[signPos];
136 if (sign == '-' || sign == '+')
137 {
138 return time.Substring(0, signPos)
139 + "GMT"
140 + time.Substring(signPos, 3)
141 + ":"
142 + time.Substring(signPos + 3);
143 }
144 else
145 {
146 signPos = time.Length - 3;
147 sign = time[signPos];
148 if (sign == '-' || sign == '+')
149 {
150 return time.Substring(0, signPos)
151 + "GMT"
152 + time.Substring(signPos)
153 + ":00";
154 }
155 }
156 }
157
158 return time + CalculateGmtOffset();
159 }
160
161 private string CalculateGmtOffset()
162 {
163 char sign = '+';
164 DateTime time = ToDateTime();
165
166 #if SILVERLIGHT || PORTABLE
167 long offset = time.Ticks - time.ToUniversalTime().Ticks;
168 if (offset < 0)
169 {
170 sign = '-';
171 offset = -offset;
172 }
173 int hours = (int)(offset / TimeSpan.TicksPerHour);
174 int minutes = (int)(offset / TimeSpan.TicksPerMinute) % 60;
175 #else
176 // Note: GetUtcOffset incorporates Daylight Savings offset
177 TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset(time);
178 if (offset.CompareTo(TimeSpan.Zero) < 0)
179 {
180 sign = '-';
181 offset = offset.Duration();
182 }
183 int hours = offset.Hours;
184 int minutes = offset.Minutes;
185 #endif
186
187 return "GMT" + sign + Convert(hours) + ":" + Convert(minutes);
188 }
189
190 private static string Convert(
191 int time)
192 {
193 if (time < 10)
194 {
195 return "0" + time;
196 }
197
198 return time.ToString();
199 }
200
201 public DateTime ToDateTime()
202 {
203 string formatStr;
204 string d = time;
205 bool makeUniversal = false;
206
207 if (Platform.EndsWith(d, "Z"))
208 {
209 if (HasFractionalSeconds)
210 {
211 int fCount = d.Length - d.IndexOf('.') - 2;
212 formatStr = @"yyyyMMddHHmmss." + FString(fCount) + @"\Z";
213 }
214 else
215 {
216 formatStr = @"yyyyMMddHHmmss\Z";
217 }
218 }
219 else if (time.IndexOf('-') > 0 || time.IndexOf('+') > 0)
220 {
221 d = GetTime();
222 makeUniversal = true;
223
224 if (HasFractionalSeconds)
225 {
226 int fCount = Platform.IndexOf(d, "GMT") - 1 - d.IndexOf('.');
227 formatStr = @"yyyyMMddHHmmss." + FString(fCount) + @"'GMT'zzz";
228 }
229 else
230 {
231 formatStr = @"yyyyMMddHHmmss'GMT'zzz";
232 }
233 }
234 else
235 {
236 if (HasFractionalSeconds)
237 {
238 int fCount = d.Length - 1 - d.IndexOf('.');
239 formatStr = @"yyyyMMddHHmmss." + FString(fCount);
240 }
241 else
242 {
243 formatStr = @"yyyyMMddHHmmss";
244 }
245
246 // TODO?
247 // dateF.setTimeZone(new SimpleTimeZone(0, TimeZone.getDefault().getID()));
248 }
249
250 return ParseDateString(d, formatStr, makeUniversal);
251 }
252
253 private string FString(
254 int count)
255 {
256 StringBuilder sb = new StringBuilder();
257 for (int i = 0; i < count; ++i)
258 {
259 sb.Append('f');
260 }
261 return sb.ToString();
262 }
263
264 private DateTime ParseDateString(string s, string format, bool makeUniversal)
265 {
266 /*
267 * NOTE: DateTime.Kind and DateTimeStyles.AssumeUniversal not available in .NET 1.1
268 */
269 DateTimeStyles style = DateTimeStyles.None;
270 if (Platform.EndsWith(format, "Z"))
271 {
272 try
273 {
274 style = (DateTimeStyles)Enums.GetEnumValue(typeof(DateTimeStyles), "AssumeUniversal");
275 }
276 catch (Exception)
277 {
278 }
279
280 style |= DateTimeStyles.AdjustToUniversal;
281 }
282
283 DateTime dt = DateTime.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, style);
284
285 return makeUniversal ? dt.ToUniversalTime() : dt;
286 }
287
288 private bool HasFractionalSeconds
289 {
290 get { return time.IndexOf('.') == 14; }
291 }
292
293 private byte[] GetOctets()
294 {
295 return Strings.ToAsciiByteArray(time);
296 }
297
298 internal override void Encode(
299 DerOutputStream derOut)
300 {
301 derOut.WriteEncoded(Asn1Tags.GeneralizedTime, GetOctets());
302 }
303
304 protected override bool Asn1Equals(
305 Asn1Object asn1Object)
306 {
307 DerGeneralizedTime other = asn1Object as DerGeneralizedTime;
308
309 if (other == null)
310 return false;
311
312 return this.time.Equals(other.time);
313 }
314
315 protected override int Asn1GetHashCode()
316 {
317 return time.GetHashCode();
318 }
319 }
320 }
1 using System;
2
3 using Org.BouncyCastle.Utilities;
4
5 namespace Org.BouncyCastle.Asn1
6 {
7 public class DerGraphicString
8 : DerStringBase
9 {
10 private readonly byte[] mString;
11
12 /**
13 * return a Graphic String from the passed in object
14 *
15 * @param obj a DerGraphicString or an object that can be converted into one.
16 * @exception IllegalArgumentException if the object cannot be converted.
17 * @return a DerGraphicString instance, or null.
18 */
19 public static DerGraphicString GetInstance(object obj)
20 {
21 if (obj == null || obj is DerGraphicString)
22 {
23 return (DerGraphicString)obj;
24 }
25
26 if (obj is byte[])
27 {
28 try
29 {
30 return (DerGraphicString)FromByteArray((byte[])obj);
31 }
32 catch (Exception e)
33 {
34 throw new ArgumentException("encoding error in GetInstance: " + e.ToString(), "obj");
35 }
36 }
37
38 throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj), "obj");
39 }
40
41 /**
42 * return a Graphic String from a tagged object.
43 *
44 * @param obj the tagged object holding the object we want
45 * @param explicit true if the object is meant to be explicitly
46 * tagged false otherwise.
47 * @exception IllegalArgumentException if the tagged object cannot
48 * be converted.
49 * @return a DerGraphicString instance, or null.
50 */
51 public static DerGraphicString GetInstance(Asn1TaggedObject obj, bool isExplicit)
52 {
53 Asn1Object o = obj.GetObject();
54
55 if (isExplicit || o is DerGraphicString)
56 {
57 return GetInstance(o);
58 }
59
60 return new DerGraphicString(((Asn1OctetString)o).GetOctets());
61 }
62
63 /**
64 * basic constructor - with bytes.
65 * @param string the byte encoding of the characters making up the string.
66 */
67 public DerGraphicString(byte[] encoding)
68 {
69 this.mString = Arrays.Clone(encoding);
70 }
71
72 public override string GetString()
73 {
74 return Strings.FromByteArray(mString);
75 }
76
77 public byte[] GetOctets()
78 {
79 return Arrays.Clone(mString);
80 }
81
82 internal override void Encode(DerOutputStream derOut)
83 {
84 derOut.WriteEncoded(Asn1Tags.GraphicString, mString);
85 }
86
87 protected override int Asn1GetHashCode()
88 {
89 return Arrays.GetHashCode(mString);
90 }
91
92 protected override bool Asn1Equals(
93 Asn1Object asn1Object)
94 {
95 DerGraphicString other = asn1Object as DerGraphicString;
96
97 if (other == null)
98 return false;
99
100 return Arrays.AreEqual(mString, other.mString);
101 }
102 }
103 }
1 using System;
2 using System.Text;
3
4 using Org.BouncyCastle.Utilities;
5
6 namespace Org.BouncyCastle.Asn1
7 {
8 /**
9 * Der IA5String object - this is an ascii string.
10 */
11 public class DerIA5String
12 : DerStringBase
13 {
14 private readonly string str;
15
16 /**
17 * return a IA5 string from the passed in object
18 *
19 * @exception ArgumentException if the object cannot be converted.
20 */
21 public static DerIA5String GetInstance(
22 object obj)
23 {
24 if (obj == null || obj is DerIA5String)
25 {
26 return (DerIA5String)obj;
27 }
28
29 throw new ArgumentException("illegal object in GetInstance: " + Platform.GetTypeName(obj));
30 }
31
32 /**
33 * return an IA5 string from a tagged object.
34 *
35 * @param obj the tagged object holding the object we want
36 * @param explicitly true if the object is meant to be explicitly
37 * tagged false otherwise.
38 * @exception ArgumentException if the tagged object cannot
39 * be converted.
40 */
41 public static DerIA5String GetInstance(
42 Asn1TaggedObject obj,
43 bool isExplicit)
44 {
45 Asn1Object o = obj.GetObject();
46
47 if (isExplicit || o is DerIA5String)
48 {
49 return GetInstance(o);
50 }
51
52 return new DerIA5String(((Asn1OctetString)o).GetOctets());
53 }
54
55 /**
56 * basic constructor - with bytes.
57 */
58 public DerIA5String(
59 byte[] str)
60 : this(Strings.FromAsciiByteArray(str), false)
61 {
62 }
63
64 /**
65 * basic constructor - without validation.
66 */
67 public DerIA5String(
68 string str)
69 : this(str, false)
70 {
71 }
72
73 /**
74 * Constructor with optional validation.
75 *
76 * @param string the base string to wrap.
77 * @param validate whether or not to check the string.
78 * @throws ArgumentException if validate is true and the string
79 * contains characters that should not be in an IA5String.
80 */
81 public DerIA5String(
82 string str,
83 bool validate)
84 {
85 if (str == null)
86 throw new ArgumentNullException("str");
87 if (validate && !IsIA5String(str))
88 throw new ArgumentException("string contains illegal characters", "str");
89
90 this.str = str;
91 }
92
93 public override string GetString()
94 {
95 return str;
96 }
97
98 public byte[] GetOctets()
99 {
100 return Strings.ToAsciiByteArray(str);
101 }
102
103 internal override void Encode(
104 DerOutputStream derOut)
105 {
106 derOut.WriteEncoded(Asn1Tags.IA5String, GetOctets());
107 }
108
109 protected override int Asn1GetHashCode()
110 {
111 return this.str.GetHashCode();
112 }
113
114 protected override bool Asn1Equals(
115 Asn1Object asn1Object)
116 {
117 DerIA5String other = asn1Object as DerIA5String;
118
119 if (other == null)
120 return false;
121
122 return this.str.Equals(other.str);
123 }
124
125 /**
126 * return true if the passed in String can be represented without
127 * loss as an IA5String, false otherwise.
128 *
129 * @return true if in printable set, false otherwise.
130 */
131 public static bool IsIA5String(
132 string str)
133 {
134 foreach (char ch in str)
135 {
136 if (ch > 0x007f)
137 {
138 return false;
139 }
140 }
141
142 return true;
143 }
144 }
145 }