Last active
March 6, 2019 03:39
-
-
Save aramezx/f69bbd897cc19f29e68008659f8ed653 to your computer and use it in GitHub Desktop.
Basic Sample in keypair generation using android keystore in api level 18
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* | |
* The API is outlined in the 'Security' section of the 4.3 new API introduction page, | |
* and details can be found in the official SDK reference, so we will only review it briefly. | |
* Instead of introducing yet another Android-specific API, key store access is exposed via standard JCE APIs, | |
* namely KeyGenerator and KeyStore. Both are backed by a new Android JCE provider, | |
* AndroidKeyStoreProvider and are accessed by passing "AndroidKeyStore" as the type | |
* parameter of the respective factory methods (those APIs were actually available in 4.2 as well, | |
* but were not public). For a full sample detailing their usage, | |
* refer to the BasicAndroidKeyStore project in the Android SDK. | |
* To introduce their usage briefly, first you create a KeyPairGeneratorSpec that describes | |
* the keys you want to generate (including a self-signed certificate), initialize a KeyPairGenerator | |
* with it and then generate the keys by calling generateKeyPair(). | |
* The most important parameter is the alias, which you then pass to KeyStore.getEntry() in order to get a handle to the | |
* generated keys later. | |
* There is currently no way to specify key size or type and generated keys default to 2048 bit RSA. | |
* Here's how all this looks like: | |
*/ | |
// generate a key pair | |
Context ctx = getContext(); | |
Calendar notBefore = Calendar.getInstance() | |
Calendar notAfter = Calendar.getInstance(); | |
notAfter.add(1, Calendar.YEAR); | |
KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(ctx) | |
.setAlias("key1") | |
.setSubject( | |
new X500Principal(String.format("CN=%s, OU=%s", alais, | |
ctx.getPackageName()))) | |
.setSerialNumber(BigInteger.ONE).setStartDate(notBefore.getTime()) | |
.setEndDate(notAfter.getTime()).build(); | |
KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore"); | |
kpGenerator.initialize(spec); | |
KeyPair kp = kpGenerator.generateKeyPair(); | |
// in another part of the app, access the keys | |
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); | |
keyStore.load(null); | |
KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry("key1", null); | |
RSAPublicKey pubKey = (RSAPublicKey)keyEntry.getCertificate().getPublicKey(); | |
RSAPrivateKey privKey = (RSAPrivateKey) keyEntry.getPrivateKey(); | |
/* original sample code from https://nelenkov.blogspot.com */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment