ab832c98a9f4567082270bf3d716b58a5a2cea61
[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     /**
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 }