1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.eclipse.jgit.gpg.bc.internal.keys;
24
25
26
27 import java.io.IOException;
28 import java.io.InputStream;
29
30 import org.bouncycastle.bcpg.HashAlgorithmTags;
31 import org.bouncycastle.bcpg.S2K;
32 import org.bouncycastle.util.io.Streams;
33
34
35
36
37
38
39
40
41
42 class SXprUtils {
43 private static int readLength(InputStream in, int ch) throws IOException {
44 int len = ch - '0';
45
46 while ((ch = in.read()) >= 0 && ch != ':') {
47 len = len * 10 + ch - '0';
48 }
49
50 return len;
51 }
52
53 static String readString(InputStream in, int ch) throws IOException {
54 int len = readLength(in, ch);
55
56 char[] chars = new char[len];
57
58 for (int i = 0; i != chars.length; i++) {
59 chars[i] = (char) in.read();
60 }
61
62 return new String(chars);
63 }
64
65 static byte[] readBytes(InputStream in, int ch) throws IOException {
66 int len = readLength(in, ch);
67
68 byte[] data = new byte[len];
69
70 Streams.readFully(in, data);
71
72 return data;
73 }
74
75 static S2K parseS2K(InputStream in) throws IOException {
76 skipOpenParenthesis(in);
77
78
79 readString(in, in.read());
80 byte[] iv = readBytes(in, in.read());
81 final long iterationCount = Long.parseLong(readString(in, in.read()));
82
83 skipCloseParenthesis(in);
84
85
86 S2K s2k = new S2K(HashAlgorithmTags.SHA1, iv, (int) iterationCount) {
87 @Override
88 public long getIterationCount() {
89 return iterationCount;
90 }
91 };
92
93 return s2k;
94 }
95
96 static void skipOpenParenthesis(InputStream in) throws IOException {
97 int ch = in.read();
98 if (ch != '(') {
99 throw new IOException(
100 "unknown character encountered: " + (char) ch);
101 }
102 }
103
104 static void skipCloseParenthesis(InputStream in) throws IOException {
105 int ch = in.read();
106 if (ch != ')') {
107 throw new IOException("unknown character encountered");
108 }
109 }
110 }