Using Android KeyChain

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* This method will launch an intent to install the key chain
*/
public static final String PKCS12_FILENAME = "keychain.p12";
private static final String DEFAULT_ALIAS = "My Key Chain";
private static final int INSTALL_KEYCHAIN_CODE = 1;
private void installPkcs12() {
try {
// prepare a PKCS12 format file with filename *.p12 or *.pfx
BufferedInputStream bis = new BufferedInputStream(getAssets().open(
PKCS12_FILENAME));
byte[] keychain = new byte[bis.available()];
bis.read(keychain);

Intent installIntent = KeyChain.createInstallIntent();
installIntent.putExtra(KeyChain.EXTRA_PKCS12, keychain);
installIntent.putExtra(KeyChain.EXTRA_NAME, DEFAULT_ALIAS);
startActivityForResult(installIntent, INSTALL_KEYCHAIN_CODE);
} catch (IOException e) {
e.printStackTrace();
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == INSTALL_KEYCHAIN_CODE) {
switch (resultCode) {
case Activity.RESULT_OK:
chooseCert();
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
}

private void chooseCert() {
KeyChain.choosePrivateKeyAlias(this, this, // Callback
new String[] {}, // Any key types.
null, // Any issuers.
"localhost", // Any host
-1, // Any port
DEFAULT_ALIAS);
}

/**
* This implements the KeyChainAliasCallback
*/
@Override
public void alias(String alias) {
// callback to get the alias set by the user
}

References

Android SDK KeyChainDemo
Android KeyChain