- add sources.
[platform/framework/web/crosswalk.git] / src / net / android / javatests / src / org / chromium / net / AndroidKeyStoreTestUtil.java
1 // Copyright (c) 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.os.Build;
8 import android.util.Log;
9
10 import java.security.PrivateKey;
11 import java.security.PrivateKey;
12 import java.security.Signature;
13 import java.security.KeyFactory;
14 import java.security.spec.KeySpec;
15 import java.security.spec.PKCS8EncodedKeySpec;
16 import java.security.KeyStoreException;
17 import java.security.spec.InvalidKeySpecException;
18 import java.security.NoSuchAlgorithmException;
19
20 import org.chromium.base.CalledByNative;
21 import org.chromium.base.JNINamespace;
22 import org.chromium.net.PrivateKeyType;
23
24 @JNINamespace("net::android")
25 public class AndroidKeyStoreTestUtil {
26
27     private static final String TAG = "AndroidKeyStoreTestUtil";
28
29     /**
30      * Called from native code to create a PrivateKey object from its
31      * encoded PKCS#8 representation.
32      * @param type The key type, accoding to PrivateKeyType.
33      * @return new PrivateKey handle, or null in case of error.
34      */
35     @CalledByNative
36     public static PrivateKey createPrivateKeyFromPKCS8(int type,
37                                                        byte[] encoded_key) {
38         String algorithm = null;
39         switch (type) {
40             case PrivateKeyType.RSA:
41                 algorithm = "RSA";
42                 break;
43             case PrivateKeyType.DSA:
44                 algorithm = "DSA";
45                 break;
46             case PrivateKeyType.ECDSA:
47                 algorithm = "EC";
48                 break;
49             default:
50                 return null;
51         }
52
53         try {
54             KeyFactory factory = KeyFactory.getInstance(algorithm);
55             KeySpec ks = new PKCS8EncodedKeySpec(encoded_key);
56             PrivateKey key = factory.generatePrivate(ks);
57             return key;
58
59         } catch (NoSuchAlgorithmException e) {
60             Log.e(TAG, "Could not create " + algorithm + " factory instance!");
61             return null;
62         } catch (InvalidKeySpecException e) {
63             Log.e(TAG, "Could not load " + algorithm + " private key from bytes!");
64             return null;
65         }
66     }
67 }