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 17 package com.android.verity; 18 19 import java.lang.reflect.Constructor; 20 import java.io.File; 21 import java.io.ByteArrayInputStream; 22 import java.io.Console; 23 import java.io.FileInputStream; 24 import java.io.FileOutputStream; 25 import java.io.InputStreamReader; 26 import java.io.IOException; 27 import java.security.GeneralSecurityException; 28 import java.security.Key; 29 import java.security.PrivateKey; 30 import java.security.PublicKey; 31 import java.security.KeyFactory; 32 import java.security.Provider; 33 import java.security.Security; 34 import java.security.Signature; 35 import java.security.cert.Certificate; 36 import java.security.cert.CertificateFactory; 37 import java.security.cert.X509Certificate; 38 import java.security.spec.X509EncodedKeySpec; 39 import java.security.spec.PKCS8EncodedKeySpec; 40 import java.security.spec.InvalidKeySpecException; 41 import java.util.Arrays; 42 import java.util.HashMap; 43 import java.util.Map; 44 45 import javax.crypto.Cipher; 46 import javax.crypto.EncryptedPrivateKeyInfo; 47 import javax.crypto.SecretKeyFactory; 48 import javax.crypto.spec.PBEKeySpec; 49 50 import org.bouncycastle.asn1.ASN1InputStream; 51 import org.bouncycastle.asn1.ASN1ObjectIdentifier; 52 import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; 53 import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; 54 import org.bouncycastle.asn1.x509.AlgorithmIdentifier; 55 import org.bouncycastle.util.encoders.Base64; 56 57 public 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 PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()66 ID_TO_ALG.put(PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), "SHA1withRSA"); PKCSObjectIdentifiers.sha256WithRSAEncryption.getId()67 ID_TO_ALG.put(PKCSObjectIdentifiers.sha256WithRSAEncryption.getId(), "SHA256withRSA"); PKCSObjectIdentifiers.sha512WithRSAEncryption.getId()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 loadProviderIfNecessary(String providerClassName)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 pemToDer(String pem)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 decryptPrivateKey(byte[] encryptedPrivateKey)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 loadDERPrivateKey(byte[] der)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 loadPEMPrivateKey(byte[] pem)170 static PrivateKey loadPEMPrivateKey(byte[] pem) throws Exception { 171 byte[] der = pemToDer(new String(pem)); 172 return loadDERPrivateKey(der); 173 } 174 loadPEMPrivateKeyFromFile(String keyFname)175 static PrivateKey loadPEMPrivateKeyFromFile(String keyFname) throws Exception { 176 return loadPEMPrivateKey(read(keyFname)); 177 } 178 loadDERPrivateKeyFromFile(String keyFname)179 static PrivateKey loadDERPrivateKeyFromFile(String keyFname) throws Exception { 180 return loadDERPrivateKey(read(keyFname)); 181 } 182 loadDERPublicKey(byte[] der)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 loadPEMPublicKey(byte[] pem)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 loadPEMPublicKeyFromFile(String keyFname)196 static PublicKey loadPEMPublicKeyFromFile(String keyFname) throws Exception { 197 return loadPEMPublicKey(read(keyFname)); 198 } 199 loadDERPublicKeyFromFile(String keyFname)200 static PublicKey loadDERPublicKeyFromFile(String keyFname) throws Exception { 201 return loadDERPublicKey(read(keyFname)); 202 } 203 loadPEMCertificate(String fname)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 getSignatureAlgorithm(Key key)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 getSignatureAlgorithmIdentifier(Key key)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 verify(PublicKey key, byte[] input, byte[] signature, AlgorithmIdentifier algId)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 sign(PrivateKey privateKey, byte[] input)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 read(String fname)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 write(byte[] data, String fname)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