Debian Codegraph @

sdk-common/src/main/java/com/android/ide/common/signing/KeystoreHelper.java

raw
1 /*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.android.ide.common.signing;
18
19 import com.android.annotations.NonNull;
20 import com.android.annotations.Nullable;
21 import com.android.prefs.AndroidLocation;
22 import com.android.prefs.AndroidLocation.AndroidLocationException;
23 import com.android.utils.ILogger;
24 import com.android.utils.Pair;
25 import com.google.common.base.Preconditions;
26 import com.google.common.base.Verify;
27 import com.google.common.io.Closeables;
28
29 import org.bouncycastle.asn1.x500.X500Name;
30 import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
31 import org.bouncycastle.cert.X509CertificateHolder;
32 import org.bouncycastle.cert.X509v1CertificateBuilder;
33 import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
34 import org.bouncycastle.jce.provider.BouncyCastleProvider;
35 import org.bouncycastle.operator.ContentSigner;
36 import org.bouncycastle.operator.OperatorCreationException;
37 import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
38
39 import java.io.File;
40 import java.io.FileInputStream;
41 import java.io.FileNotFoundException;
42 import java.io.FileOutputStream;
43 import java.math.BigInteger;
44 import java.security.KeyPair;
45 import java.security.KeyPairGenerator;
46 import java.security.KeyStore;
47 import java.security.KeyStore.PrivateKeyEntry;
48 import java.security.NoSuchAlgorithmException;
49 import java.security.PrivateKey;
50 import java.security.cert.Certificate;
51 import java.security.cert.CertificateException;
52 import java.security.cert.X509Certificate;
53 import java.util.Date;
54
55 import javax.security.auth.x500.X500Principal;
56
57 /**
58 * A Helper to create and read keystore/keys.
59 */
60 public final class KeystoreHelper {
61
62 /**
63 * Certificate CN value. This is a hard-coded value for the debug key.
64 * Android Market checks against this value in order to refuse applications signed with
65 * debug keys.
66 */
67 private static final String CERTIFICATE_DESC = "CN=Android Debug,O=Android,C=US";
68
69 /**
70 * Generated certificate validity.
71 */
72 private static final int DEFAULT_VALIDITY_YEARS = 30;
73
74
75 /**
76 * Returns the location of the default debug keystore.
77 *
78 * @return The location of the default debug keystore
79 * @throws AndroidLocationException if the location cannot be computed
80 */
81 @NonNull
82 public static String defaultDebugKeystoreLocation() throws AndroidLocationException {
83 //this is guaranteed to either return a non null value (terminated with a platform
84 // specific separator), or throw.
85 String folder = AndroidLocation.getFolder();
86 return folder + "debug.keystore";
87 }
88
89 /**
90 * Creates a new debug store with the location, keyalias, and passwords specified in the
91 * config.
92 *
93 * @param storeType an optional type of keystore; if {@code null} the default
94 * @param storeFile the file where the store should be created
95 * @param storePassword a password for the key store
96 * @param keyPassword a password for the key
97 * @param keyAlias the alias under which the key is stored in the store
98 * @param logger (not used, kept for backwards compatibility)
99 * @throws KeytoolException
100 */
101 public static boolean createDebugStore(@Nullable String storeType, @NonNull File storeFile,
102 @NonNull String storePassword, @NonNull String keyPassword, @NonNull String keyAlias,
103 @NonNull ILogger logger) throws KeytoolException {
104
105 return createNewStore(storeType, storeFile, storePassword, keyPassword, keyAlias,
106 CERTIFICATE_DESC, DEFAULT_VALIDITY_YEARS);
107 }
108
109 /**
110 * Creates a new store with a self-signed certificate. The certificate will be valid starting
111 * from the current date up to the number of years provided.
112 *
113 * @param storeType an optional type of keystore; if {@code null} the default
114 * @param storeFile the file where the store should be created
115 * @param storePassword a password for the key store
116 * @param keyPassword a password for the key
117 * @param keyAlias the alias under which the key is stored in the store
118 * @param dn the distinguished name of the owner and issuer of the certificate
119 * @param validityYears number of years the certificate should be valid
120 * @throws KeytoolException failed to generate the self-signed certificate or the store
121 */
122 private static boolean createNewStore(
123 @Nullable String storeType,
124 @NonNull File storeFile,
125 @NonNull String storePassword,
126 @NonNull String keyPassword,
127 @NonNull String keyAlias,
128 @NonNull String dn,
129 int validityYears)
130 throws KeytoolException {
131 Preconditions.checkArgument(validityYears > 0, "validityYears (%s) <= 0", validityYears);
132
133 String useStoreType = storeType;
134 if (useStoreType == null) {
135 useStoreType = KeyStore.getDefaultType();
136 Verify.verifyNotNull(useStoreType);
137 }
138
139 try {
140 KeyStore ks = KeyStore.getInstance(useStoreType);
141 ks.load(null, null);
142
143 Pair<PrivateKey, X509Certificate> generated = generateKeyAndCertificate("RSA",
144 "SHA1withRSA", validityYears, dn);
145 ks.setKeyEntry(keyAlias, generated.getFirst(), keyPassword.toCharArray(),
146 new Certificate[]{generated.getSecond()});
147 FileOutputStream fos = new FileOutputStream(storeFile);
148 boolean threw = true;
149 try {
150 ks.store(fos, storePassword.toCharArray());
151 threw = false;
152 } finally {
153 Closeables.close(fos, threw);
154 }
155 } catch (KeytoolException e) {
156 throw e;
157 } catch (Exception e) {
158 throw new KeytoolException("Failed to create keystore.", e);
159 }
160
161 return true;
162 }
163
164 /**
165 * Returns the CertificateInfo for the given signing configuration.
166 *
167 * @param storeType an optional type of keystore; if {@code null} the default
168 * @param storeFile the file where the store should be created
169 * @param storePassword a password for the key store
170 * @param keyPassword a password for the key
171 * @param keyAlias the alias under which the key is stored in the store
172 * @return the certificate info if it could be loaded
173 * @throws KeytoolException If the password is wrong
174 * @throws FileNotFoundException If the store file cannot be found
175 */
176 @NonNull
177 public static CertificateInfo getCertificateInfo(
178 @Nullable String storeType,
179 @NonNull File storeFile,
180 @NonNull String storePassword,
181 @NonNull String keyPassword,
182 @NonNull String keyAlias)
183 throws KeytoolException, FileNotFoundException {
184
185 try {
186 KeyStore keyStore = KeyStore.getInstance(
187 storeType != null ? storeType : KeyStore.getDefaultType());
188
189 FileInputStream fis = new FileInputStream(storeFile);
190 keyStore.load(fis, storePassword.toCharArray());
191 fis.close();
192
193 char[] keyPasswordArray = keyPassword.toCharArray();
194 PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(
195 keyAlias, new KeyStore.PasswordProtection(keyPasswordArray));
196
197 if (entry == null) {
198 throw new KeytoolException(
199 String.format(
200 "No key with alias '%1$s' found in keystore %2$s",
201 keyAlias,
202 storeFile.getAbsolutePath()));
203 }
204
205 return new CertificateInfo(
206 entry.getPrivateKey(),
207 (X509Certificate) entry.getCertificate());
208 } catch (FileNotFoundException e) {
209 throw e;
210 } catch (Exception e) {
211 throw new KeytoolException(
212 String.format("Failed to read key %1$s from store \"%2$s\": %3$s",
213 keyAlias, storeFile, e.getMessage()),
214 e);
215 }
216 }
217
218 /**
219 * Generates a key and self-signed certificate pair.
220 * @param asymmetric the asymmetric encryption algorithm (<em>e.g.,</em> {@code RSA})
221 * @param sign the signature algorithm (<em>e.g.,</em> {@code SHA1withRSA})
222 * @param validityYears number of years the certificate should be valid, must be greater than
223 * zero
224 * @param dn the distinguished name of the issuer and owner of the certificate
225 * @return a pair with the private key and the corresponding certificate
226 * @throws KeytoolException failed to generate the pair
227 */
228 private static Pair<PrivateKey, X509Certificate> generateKeyAndCertificate(
229 @NonNull String asymmetric, @NonNull String sign, int validityYears,
230 @NonNull String dn) throws KeytoolException {
231 Preconditions.checkArgument(validityYears > 0, "validityYears <= 0");
232
233 KeyPair keyPair;
234 try {
235 keyPair = KeyPairGenerator.getInstance(asymmetric).generateKeyPair();
236 } catch (NoSuchAlgorithmException e) {
237 throw new KeytoolException("Failed to generate key and certificate pair for "
238 + "algorithm '" + asymmetric + "'.", e);
239 }
240
241 Date notBefore = new Date(System.currentTimeMillis());
242 Date notAfter = new Date(System.currentTimeMillis() + validityYears * 365L * 24 * 60 * 60
243 * 1000);
244
245 X500Name issuer = new X500Name(new X500Principal(dn).getName());
246
247 SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(
248 keyPair.getPublic().getEncoded());
249 X509v1CertificateBuilder builder = new X509v1CertificateBuilder(issuer, BigInteger.ONE,
250 notBefore, notAfter, issuer, publicKeyInfo);
251
252 ContentSigner signer;
253 try {
254 signer = new JcaContentSignerBuilder(sign).setProvider(
255 new BouncyCastleProvider()).build(keyPair.getPrivate());
256 } catch (OperatorCreationException e) {
257 throw new KeytoolException("Failed to build content signer with signature algorithm '"
258 + sign + "'.", e);
259 }
260
261 X509CertificateHolder holder = builder.build(signer);
262
263 JcaX509CertificateConverter converter = new JcaX509CertificateConverter()
264 .setProvider(new BouncyCastleProvider());
265
266 X509Certificate certificate;
267 try {
268 certificate = converter.getCertificate(holder);
269 } catch (CertificateException e) {
270 throw new KeytoolException("Failed to obtain the self-signed certificate.", e);
271 }
272
273 return Pair.of(keyPair.getPrivate(), certificate);
274 }
275 }