forked from processing/processing-android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJarSigner.java
More file actions
289 lines (240 loc) · 9.76 KB
/
JarSigner.java
File metadata and controls
289 lines (240 loc) · 9.76 KB
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2014-16 The Processing Foundation
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.mode.android;
import java.io.*;
import java.security.*;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import sun.misc.BASE64Encoder;
import sun.security.pkcs.ContentInfo;
import sun.security.pkcs.PKCS7;
import sun.security.pkcs.SignerInfo;
import sun.security.x509.AlgorithmId;
import sun.security.x509.X500Name;
/**
* Created by ibziy_000 on 17.08.2014.
*/
public class JarSigner {
private static final String DIGEST_ALGORITHM = "SHA1";
private static final String DIGEST_ATTR = "SHA1-Digest";
private static final String DIGEST_MANIFEST_ATTR = "SHA1-Digest-Manifest";
private static SignatureOutputStream certFileContents = null;
private static byte[] buffer;
public static void signJar(File jarToSign, File outputJar, String alias,
String keypass, String keystore, String storepass)
throws GeneralSecurityException, IOException, NoSuchAlgorithmException {
PrivateKey privateKey = null;
X509Certificate x509Cert = null;
Manifest manifest = null;
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream fis = new FileInputStream(keystore);
keyStore.load(fis, storepass.toCharArray());
fis.close();
KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(
alias, new KeyStore.PasswordProtection(keypass.toCharArray()));
if (entry != null) {
privateKey = entry.getPrivateKey();
x509Cert = (X509Certificate) entry.getCertificate();
} else {
throw new KeyStoreException("Couldn't get key");
}
JarOutputStream signedJar = new JarOutputStream(new FileOutputStream(outputJar, false));
signedJar.setLevel(9);
if (privateKey != null && x509Cert != null) {
manifest = new Manifest();
Attributes main = manifest.getMainAttributes();
main.putValue("Manifest-Version", "1.0");
main.putValue("Created-By", "1.0 (Android)");
}
writeZip(new FileInputStream(jarToSign), signedJar, manifest);
closeJar(signedJar, manifest, privateKey, x509Cert);
}
private static void writeZip(InputStream input, JarOutputStream output, Manifest manifest)
throws IOException, NoSuchAlgorithmException {
BASE64Encoder base64Encoder = new BASE64Encoder();
MessageDigest messageDigest = MessageDigest.getInstance(DIGEST_ALGORITHM);
buffer = new byte[4096];
ZipInputStream zis = new ZipInputStream(input);
try {
// loop on the entries of the intermediary package and put them in the final package.
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
String name = entry.getName();
// do not take directories or anything inside a potential META-INF folder.
if (entry.isDirectory() || name.startsWith("META-INF/")) {
continue;
}
JarEntry newEntry;
// Preserve the STORED method of the input entry.
if (entry.getMethod() == JarEntry.STORED) {
newEntry = new JarEntry(entry);
} else {
// Create a new entry so that the compressed len is recomputed.
newEntry = new JarEntry(name);
}
writeEntry(output, zis, newEntry, messageDigest, manifest, base64Encoder);
zis.closeEntry();
}
} finally {
zis.close();
}
}
private static void writeEntry(JarOutputStream output, InputStream input, JarEntry entry,
MessageDigest digest, Manifest manifest, BASE64Encoder encoder) throws IOException {
output.putNextEntry(entry);
// Write input stream to the jar output.
int count;
while ((count = input.read(buffer)) != -1) {
output.write(buffer, 0, count);
if (digest != null) digest.update(buffer, 0, count);
}
output.closeEntry();
if (manifest != null) {
Attributes attr = manifest.getAttributes(entry.getName());
if (attr == null) {
attr = new Attributes();
manifest.getEntries().put(entry.getName(), attr);
}
attr.putValue(DIGEST_ATTR, encoder.encode(digest.digest()));
}
}
private static void closeJar(JarOutputStream jar, Manifest manifest,
PrivateKey key, X509Certificate cert)
throws IOException, GeneralSecurityException {
if (manifest != null) {
// write the manifest to the jar file
jar.putNextEntry(new JarEntry(JarFile.MANIFEST_NAME));
manifest.write(jar);
// CERT.SF
Signature signature = Signature.getInstance("SHA1with" + key.getAlgorithm());
signature.initSign(key);
jar.putNextEntry(new JarEntry("META-INF/CERT.SF"));
//Caching the SignatureOutputStream object for future use by the signature provider extensions.
certFileContents = new SignatureOutputStream(jar, signature);
writeSignatureFile(certFileContents, manifest);
// CERT.*
jar.putNextEntry(new JarEntry("META-INF/CERT." + key.getAlgorithm()));
writeSignature(jar, signature, cert, key);
}
jar.close();
}
// Writes a .SF file with a digest to the manifest.
private static void writeSignatureFile(SignatureOutputStream out, Manifest manifest)
throws IOException, GeneralSecurityException {
Manifest sf = new Manifest();
Attributes main = sf.getMainAttributes();
main.putValue("Signature-Version", "1.0");
main.putValue("Created-By", "1.0 (Android)");
BASE64Encoder base64 = new BASE64Encoder();
MessageDigest md = MessageDigest.getInstance(DIGEST_ALGORITHM);
PrintStream print = new PrintStream(
new DigestOutputStream(new ByteArrayOutputStream(), md),
true, "UTF-8");
// Digest of the entire manifest
manifest.write(print);
print.flush();
main.putValue(DIGEST_MANIFEST_ATTR, base64.encode(md.digest()));
Map<String, Attributes> entries = manifest.getEntries();
for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
// Digest of the manifest stanza for this entry.
print.print("Name: " + entry.getKey() + "\r\n");
for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
print.print(att.getKey() + ": " + att.getValue() + "\r\n");
}
print.print("\r\n");
print.flush();
Attributes sfAttr = new Attributes();
sfAttr.putValue(DIGEST_ATTR, base64.encode(md.digest()));
sf.getEntries().put(entry.getKey(), sfAttr);
}
sf.write(out);
// A bug in the java.util.jar implementation of Android platforms
// up to version 1.6 will cause a spurious IOException to be thrown
// if the length of the signature file is a multiple of 1024 bytes.
// As a workaround, add an extra CRLF in this case.
if ((out.size() % 1024) == 0) {
out.write('\r');
out.write('\n');
}
}
private static void writeSignature(JarOutputStream outputJar,
Signature signature, X509Certificate publicKey, PrivateKey privateKey)
throws IOException, GeneralSecurityException{
writeSignatureBlock(outputJar, signature, publicKey, privateKey);
}
// Write the certificate file with a digital signature.
private static void writeSignatureBlock(JarOutputStream outputJar,
Signature signature, X509Certificate publicKey, PrivateKey privateKey)
throws IOException, GeneralSecurityException {
SignerInfo signerInfo = new SignerInfo(
new X500Name(publicKey.getIssuerX500Principal().getName()),
publicKey.getSerialNumber(),
AlgorithmId.get(DIGEST_ALGORITHM),
AlgorithmId.get(privateKey.getAlgorithm()),
signature.sign());
PKCS7 pkcs7 = new PKCS7(
new AlgorithmId[] { AlgorithmId.get(DIGEST_ALGORITHM) },
new ContentInfo(ContentInfo.DATA_OID, null),
new X509Certificate[] { publicKey },
new SignerInfo[] { signerInfo });
pkcs7.encodeSignedData(outputJar);
}
private static class SignatureOutputStream extends FilterOutputStream {
private Signature signature;
private int count = 0;
private List<Byte> contents = new ArrayList<Byte>();
public SignatureOutputStream(OutputStream out, Signature sig) {
super(out);
signature = sig;
}
@Override
public void write(int b) throws IOException {
try {
signature.update((byte) b);
contents.add((byte)b);
} catch (SignatureException e) {
throw new IOException("SignatureException: " + e);
}
super.write(b);
count++;
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
try {
signature.update(b, off, len);
for (byte myByte: b) {
contents.add(myByte);
}
} catch (SignatureException e) {
throw new IOException("SignatureException: " + e);
}
super.write(b, off, len);
count += len;
}
public int size() {
return count;
}
}
}