blob: 0a3c4aa406cf1f4d51ed0e677c4eeb9d03160690 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
package org.bouncycastle.asn1;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
class StreamUtil
{
private static final long MAX_MEMORY = Runtime.getRuntime().maxMemory();
/**
* Find out possible longest length...
*
* @param in input stream of interest
* @return length calculation or MAX_VALUE.
*/
static int findLimit(InputStream in)
{
if (in instanceof LimitedInputStream)
{
return ((LimitedInputStream)in).getRemaining();
}
else if (in instanceof ASN1InputStream)
{
return ((ASN1InputStream)in).getLimit();
}
else if (in instanceof ByteArrayInputStream)
{
return ((ByteArrayInputStream)in).available();
}
else if (in instanceof FileInputStream)
{
try
{
long size = ((FileInputStream)in).getChannel().size();
if (size < Integer.MAX_VALUE)
{
return (int)size;
}
}
catch (IOException e)
{
// ignore - they'll find out soon enough!
}
}
if (MAX_MEMORY > Integer.MAX_VALUE)
{
return Integer.MAX_VALUE;
}
return (int)MAX_MEMORY;
}
static int calculateBodyLength(
int length)
{
int count = 1;
if (length > 127)
{
int size = 1;
int val = length;
while ((val >>>= 8) != 0)
{
size++;
}
for (int i = (size - 1) * 8; i >= 0; i -= 8)
{
count++;
}
}
return count;
}
static int calculateTagLength(int tagNo)
throws IOException
{
int length = 1;
if (tagNo >= 31)
{
if (tagNo < 128)
{
length++;
}
else
{
byte[] stack = new byte[5];
int pos = stack.length;
stack[--pos] = (byte)(tagNo & 0x7F);
do
{
tagNo >>= 7;
stack[--pos] = (byte)(tagNo & 0x7F | 0x80);
}
while (tagNo > 127);
length += stack.length - pos;
}
}
return length;
}
}
|