• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 package org.chromium.net;
6 
7 import android.util.Log;
8 
9 import org.jni_zero.CalledByNative;
10 import org.jni_zero.JNINamespace;
11 
12 import java.security.KeyFactory;
13 import java.security.NoSuchAlgorithmException;
14 import java.security.PrivateKey;
15 import java.security.spec.InvalidKeySpecException;
16 import java.security.spec.KeySpec;
17 import java.security.spec.PKCS8EncodedKeySpec;
18 
19 /** Utility functions to create Android platform keys in tests. */
20 @JNINamespace("net::android")
21 public class AndroidKeyStoreTestUtil {
22 
23     private static final String TAG = "AndroidKeyStoreTestUtil";
24 
25     /**
26      * Called from native code to create a PrivateKey object from its
27      * encoded PKCS#8 representation.
28      * @param type The key type, according to PrivateKeyType.
29      * @return new PrivateKey handle, or null in case of error.
30      */
31     @CalledByNative
createPrivateKeyFromPKCS8(int type, byte[] encodedKey)32     public static PrivateKey createPrivateKeyFromPKCS8(int type, byte[] encodedKey) {
33         String algorithm = null;
34         switch (type) {
35             case PrivateKeyType.RSA:
36                 algorithm = "RSA";
37                 break;
38             case PrivateKeyType.ECDSA:
39                 algorithm = "EC";
40                 break;
41             default:
42                 return null;
43         }
44 
45         try {
46             @SuppressWarnings("InsecureCryptoUsage") // This util class is for test only.
47             KeyFactory factory = KeyFactory.getInstance(algorithm);
48             KeySpec ks = new PKCS8EncodedKeySpec(encodedKey);
49             PrivateKey key = factory.generatePrivate(ks);
50             return key;
51 
52         } catch (NoSuchAlgorithmException e) {
53             Log.e(TAG, "Could not create " + algorithm + " factory instance!");
54             return null;
55         } catch (InvalidKeySpecException e) {
56             Log.e(TAG, "Could not load " + algorithm + " private key from bytes!");
57             return null;
58         }
59     }
60 }
61