• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2013 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.example.android.vault;
18 
19 import android.content.Context;
20 import android.security.KeyPairGeneratorSpec;
21 
22 import java.io.IOException;
23 import java.math.BigInteger;
24 import java.security.GeneralSecurityException;
25 import java.security.KeyPair;
26 import java.security.KeyPairGenerator;
27 import java.security.KeyStore;
28 import java.util.Calendar;
29 import java.util.GregorianCalendar;
30 
31 import javax.crypto.Cipher;
32 import javax.crypto.SecretKey;
33 import javax.security.auth.x500.X500Principal;
34 
35 /**
36  * Wraps {@link SecretKey} instances using a public/private key pair stored in
37  * the platform {@link KeyStore}. This allows us to protect symmetric keys with
38  * hardware-backed crypto, if provided by the device.
39  * <p>
40  * See <a href="http://en.wikipedia.org/wiki/Key_Wrap">key wrapping</a> for more
41  * details.
42  * <p>
43  * Not inherently thread safe.
44  */
45 public class SecretKeyWrapper {
46     private final Cipher mCipher;
47     private final KeyPair mPair;
48 
49     /**
50      * Create a wrapper using the public/private key pair with the given alias.
51      * If no pair with that alias exists, it will be generated.
52      */
SecretKeyWrapper(Context context, String alias)53     public SecretKeyWrapper(Context context, String alias)
54             throws GeneralSecurityException, IOException {
55         mCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
56 
57         final KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
58         keyStore.load(null);
59 
60         if (!keyStore.containsAlias(alias)) {
61             generateKeyPair(context, alias);
62         }
63 
64         // Even if we just generated the key, always read it back to ensure we
65         // can read it successfully.
66         final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(
67                 alias, null);
68         mPair = new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey());
69     }
70 
generateKeyPair(Context context, String alias)71     private static void generateKeyPair(Context context, String alias)
72             throws GeneralSecurityException {
73         final Calendar start = new GregorianCalendar();
74         final Calendar end = new GregorianCalendar();
75         end.add(Calendar.YEAR, 100);
76 
77         final KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
78                 .setAlias(alias)
79                 .setSubject(new X500Principal("CN=" + alias))
80                 .setSerialNumber(BigInteger.ONE)
81                 .setStartDate(start.getTime())
82                 .setEndDate(end.getTime())
83                 .build();
84 
85         final KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
86         gen.initialize(spec);
87         gen.generateKeyPair();
88     }
89 
90     /**
91      * Wrap a {@link SecretKey} using the public key assigned to this wrapper.
92      * Use {@link #unwrap(byte[])} to later recover the original
93      * {@link SecretKey}.
94      *
95      * @return a wrapped version of the given {@link SecretKey} that can be
96      *         safely stored on untrusted storage.
97      */
wrap(SecretKey key)98     public byte[] wrap(SecretKey key) throws GeneralSecurityException {
99         mCipher.init(Cipher.WRAP_MODE, mPair.getPublic());
100         return mCipher.wrap(key);
101     }
102 
103     /**
104      * Unwrap a {@link SecretKey} using the private key assigned to this
105      * wrapper.
106      *
107      * @param blob a wrapped {@link SecretKey} as previously returned by
108      *            {@link #wrap(SecretKey)}.
109      */
unwrap(byte[] blob)110     public SecretKey unwrap(byte[] blob) throws GeneralSecurityException {
111         mCipher.init(Cipher.UNWRAP_MODE, mPair.getPrivate());
112         return (SecretKey) mCipher.unwrap(blob, "AES", Cipher.SECRET_KEY);
113     }
114 }
115