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