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.chromium.base.annotations.CalledByNative; 10 import org.chromium.base.annotations.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 /** 20 * Utility functions to create Android platform keys in tests. 21 */ 22 @JNINamespace("net::android") 23 public class AndroidKeyStoreTestUtil { 24 25 private static final String TAG = "AndroidKeyStoreTestUtil"; 26 27 /** 28 * Called from native code to create a PrivateKey object from its 29 * encoded PKCS#8 representation. 30 * @param type The key type, according to PrivateKeyType. 31 * @return new PrivateKey handle, or null in case of error. 32 */ 33 @CalledByNative createPrivateKeyFromPKCS8(int type, byte[] encodedKey)34 public static PrivateKey createPrivateKeyFromPKCS8(int type, byte[] encodedKey) { 35 String algorithm = null; 36 switch (type) { 37 case PrivateKeyType.RSA: 38 algorithm = "RSA"; 39 break; 40 case PrivateKeyType.ECDSA: 41 algorithm = "EC"; 42 break; 43 default: 44 return null; 45 } 46 47 try { 48 @SuppressWarnings("InsecureCryptoUsage") // This util class is for test only. 49 KeyFactory factory = KeyFactory.getInstance(algorithm); 50 KeySpec ks = new PKCS8EncodedKeySpec(encodedKey); 51 PrivateKey key = factory.generatePrivate(ks); 52 return key; 53 54 } catch (NoSuchAlgorithmException e) { 55 Log.e(TAG, "Could not create " + algorithm + " factory instance!"); 56 return null; 57 } catch (InvalidKeySpecException e) { 58 Log.e(TAG, "Could not load " + algorithm + " private key from bytes!"); 59 return null; 60 } 61 } 62 } 63