865b1ef6cd3bf2530e6e4967bb96cf9d87173a20
[platform/framework/web/crosswalk.git] / src / net / android / javatests / src / org / chromium / net / AndroidKeyStoreTestUtil.java
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
5 package org.chromium.net;
6
7 import android.util.Log;
8
9 import org.chromium.base.CalledByNative;
10 import org.chromium.base.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 @JNINamespace("net::android")
20 public class AndroidKeyStoreTestUtil {
21
22     private static final String TAG = "AndroidKeyStoreTestUtil";
23
24     private static final DefaultAndroidKeyStore sKeyStore = new DefaultAndroidKeyStore();
25     /**
26      * Called from native code to create a PrivateKey object from its
27      * encoded PKCS#8 representation.
28      * @param type The key type, accoding to PrivateKeyType.
29      * @return new PrivateKey handle, or null in case of error.
30      */
31     @CalledByNative
32     public static AndroidPrivateKey createPrivateKeyFromPKCS8(int type, byte[] encodedKey) {
33         String algorithm = null;
34         switch (type) {
35             case PrivateKeyType.RSA:
36                 algorithm = "RSA";
37                 break;
38             case PrivateKeyType.DSA:
39                 algorithm = "DSA";
40                 break;
41             case PrivateKeyType.ECDSA:
42                 algorithm = "EC";
43                 break;
44             default:
45                 return null;
46         }
47
48         try {
49             KeyFactory factory = KeyFactory.getInstance(algorithm);
50             KeySpec ks = new PKCS8EncodedKeySpec(encodedKey);
51             PrivateKey key = factory.generatePrivate(ks);
52             return sKeyStore.createKey(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 }