1/*
2 * Copyright (C) 2014 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
17package com.android.verity;
18
19import java.lang.reflect.Constructor;
20import java.io.File;
21import java.io.ByteArrayInputStream;
22import java.io.Console;
23import java.io.FileInputStream;
24import java.io.FileOutputStream;
25import java.io.InputStreamReader;
26import java.io.IOException;
27import java.security.GeneralSecurityException;
28import java.security.Key;
29import java.security.PrivateKey;
30import java.security.PublicKey;
31import java.security.KeyFactory;
32import java.security.Provider;
33import java.security.Security;
34import java.security.Signature;
35import java.security.cert.Certificate;
36import java.security.cert.CertificateFactory;
37import java.security.cert.X509Certificate;
38import java.security.spec.X509EncodedKeySpec;
39import java.security.spec.PKCS8EncodedKeySpec;
40import java.security.spec.InvalidKeySpecException;
41import java.util.Arrays;
42import java.util.HashMap;
43import java.util.Map;
44
45import javax.crypto.Cipher;
46import javax.crypto.EncryptedPrivateKeyInfo;
47import javax.crypto.SecretKeyFactory;
48import javax.crypto.spec.PBEKeySpec;
49
50import org.bouncycastle.asn1.ASN1InputStream;
51import org.bouncycastle.asn1.ASN1ObjectIdentifier;
52import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
53import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
54import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
55import org.bouncycastle.util.encoders.Base64;
56
57public class Utils {
58
59    private static final Map<String, String> ID_TO_ALG;
60    private static final Map<String, String> ALG_TO_ID;
61
62    static {
63        ID_TO_ALG = new HashMap<String, String>();
64        ALG_TO_ID = new HashMap<String, String>();
65
66        ID_TO_ALG.put(PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), "SHA1withRSA");
67        ID_TO_ALG.put(PKCSObjectIdentifiers.sha256WithRSAEncryption.getId(), "SHA256withRSA");
68        ID_TO_ALG.put(PKCSObjectIdentifiers.sha512WithRSAEncryption.getId(), "SHA512withRSA");
69
70        ALG_TO_ID.put("SHA1withRSA", PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
71        ALG_TO_ID.put("SHA256withRSA", PKCSObjectIdentifiers.sha256WithRSAEncryption.getId());
72        ALG_TO_ID.put("SHA512withRSA", PKCSObjectIdentifiers.sha512WithRSAEncryption.getId());
73    }
74
75    private static void loadProviderIfNecessary(String providerClassName) {
76        if (providerClassName == null) {
77            return;
78        }
79
80        final Class<?> klass;
81        try {
82            final ClassLoader sysLoader = ClassLoader.getSystemClassLoader();
83            if (sysLoader != null) {
84                klass = sysLoader.loadClass(providerClassName);
85            } else {
86                klass = Class.forName(providerClassName);
87            }
88        } catch (ClassNotFoundException e) {
89            e.printStackTrace();
90            System.exit(1);
91            return;
92        }
93
94        Constructor<?> constructor = null;
95        for (Constructor<?> c : klass.getConstructors()) {
96            if (c.getParameterTypes().length == 0) {
97                constructor = c;
98                break;
99            }
100        }
101        if (constructor == null) {
102            System.err.println("No zero-arg constructor found for " + providerClassName);
103            System.exit(1);
104            return;
105        }
106
107        final Object o;
108        try {
109            o = constructor.newInstance();
110        } catch (Exception e) {
111            e.printStackTrace();
112            System.exit(1);
113            return;
114        }
115        if (!(o instanceof Provider)) {
116            System.err.println("Not a Provider class: " + providerClassName);
117            System.exit(1);
118        }
119
120        Security.insertProviderAt((Provider) o, 1);
121    }
122
123    static byte[] pemToDer(String pem) throws Exception {
124        pem = pem.replaceAll("^-.*", "");
125        String base64_der = pem.replaceAll("-.*$", "");
126        return Base64.decode(base64_der);
127    }
128
129    private static PKCS8EncodedKeySpec decryptPrivateKey(byte[] encryptedPrivateKey)
130        throws GeneralSecurityException {
131        EncryptedPrivateKeyInfo epkInfo;
132        try {
133            epkInfo = new EncryptedPrivateKeyInfo(encryptedPrivateKey);
134        } catch (IOException ex) {
135            // Probably not an encrypted key.
136            return null;
137        }
138
139        char[] password = System.console().readPassword("Password for the private key file: ");
140
141        SecretKeyFactory skFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName());
142        Key key = skFactory.generateSecret(new PBEKeySpec(password));
143        Arrays.fill(password, '\0');
144
145        Cipher cipher = Cipher.getInstance(epkInfo.getAlgName());
146        cipher.init(Cipher.DECRYPT_MODE, key, epkInfo.getAlgParameters());
147
148        try {
149            return epkInfo.getKeySpec(cipher);
150        } catch (InvalidKeySpecException ex) {
151            System.err.println("Password may be bad.");
152            throw ex;
153        }
154    }
155
156    static PrivateKey loadDERPrivateKey(byte[] der) throws Exception {
157        PKCS8EncodedKeySpec spec = decryptPrivateKey(der);
158
159        if (spec == null) {
160            spec = new PKCS8EncodedKeySpec(der);
161        }
162
163        ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(spec.getEncoded()));
164        PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
165        String algOid = pki.getPrivateKeyAlgorithm().getAlgorithm().getId();
166
167        return KeyFactory.getInstance(algOid).generatePrivate(spec);
168    }
169
170    static PrivateKey loadPEMPrivateKey(byte[] pem) throws Exception {
171        byte[] der = pemToDer(new String(pem));
172        return loadDERPrivateKey(der);
173    }
174
175    static PrivateKey loadPEMPrivateKeyFromFile(String keyFname) throws Exception {
176        return loadPEMPrivateKey(read(keyFname));
177    }
178
179    static PrivateKey loadDERPrivateKeyFromFile(String keyFname) throws Exception {
180        return loadDERPrivateKey(read(keyFname));
181    }
182
183    static PublicKey loadDERPublicKey(byte[] der) throws Exception {
184        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(der);
185        KeyFactory factory = KeyFactory.getInstance("RSA");
186        return factory.generatePublic(publicKeySpec);
187    }
188
189    static PublicKey loadPEMPublicKey(byte[] pem) throws Exception {
190        byte[] der = pemToDer(new String(pem));
191        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(der);
192        KeyFactory factory = KeyFactory.getInstance("RSA");
193        return factory.generatePublic(publicKeySpec);
194    }
195
196    static PublicKey loadPEMPublicKeyFromFile(String keyFname) throws Exception {
197        return loadPEMPublicKey(read(keyFname));
198    }
199
200    static PublicKey loadDERPublicKeyFromFile(String keyFname) throws Exception {
201        return loadDERPublicKey(read(keyFname));
202    }
203
204    static X509Certificate loadPEMCertificate(String fname) throws Exception {
205        try (FileInputStream fis = new FileInputStream(fname)) {
206            CertificateFactory cf = CertificateFactory.getInstance("X.509");
207            return (X509Certificate) cf.generateCertificate(fis);
208        }
209    }
210
211    private static String getSignatureAlgorithm(Key key) {
212        if ("RSA".equals(key.getAlgorithm())) {
213            return "SHA256withRSA";
214        } else {
215            throw new IllegalArgumentException("Unsupported key type " + key.getAlgorithm());
216        }
217    }
218
219    static AlgorithmIdentifier getSignatureAlgorithmIdentifier(Key key) {
220        String id = ALG_TO_ID.get(getSignatureAlgorithm(key));
221
222        if (id == null) {
223            throw new IllegalArgumentException("Unsupported key type " + key.getAlgorithm());
224        }
225
226        return new AlgorithmIdentifier(new ASN1ObjectIdentifier(id));
227    }
228
229    static boolean verify(PublicKey key, byte[] input, byte[] signature,
230            AlgorithmIdentifier algId) throws Exception {
231        String algName = ID_TO_ALG.get(algId.getObjectId().getId());
232
233        if (algName == null) {
234            throw new IllegalArgumentException("Unsupported algorithm " + algId.getObjectId());
235        }
236
237        Signature verifier = Signature.getInstance(algName);
238        verifier.initVerify(key);
239        verifier.update(input);
240
241        return verifier.verify(signature);
242    }
243
244    static byte[] sign(PrivateKey privateKey, byte[] input) throws Exception {
245        Signature signer = Signature.getInstance(getSignatureAlgorithm(privateKey));
246        signer.initSign(privateKey);
247        signer.update(input);
248        return signer.sign();
249    }
250
251    static byte[] read(String fname) throws Exception {
252        long offset = 0;
253        File f = new File(fname);
254        long length = f.length();
255        byte[] image = new byte[(int)length];
256        FileInputStream fis = new FileInputStream(f);
257        while (offset < length) {
258            offset += fis.read(image, (int)offset, (int)(length - offset));
259        }
260        fis.close();
261        return image;
262    }
263
264    static void write(byte[] data, String fname) throws Exception{
265        FileOutputStream out = new FileOutputStream(fname);
266        out.write(data);
267        out.close();
268    }
269}
270