2
2
3
3
import android .content .Context ;
4
4
import android .content .SharedPreferences ;
5
+ import android .os .Build ;
5
6
import android .security .keystore .KeyGenParameterSpec ;
6
7
import android .security .keystore .KeyProperties ;
7
8
@@ -62,11 +63,16 @@ private static PublicKey getPublicKey() throws Exception {
62
63
if (!keyStore .containsAlias (PP_KEYSTORE_ALIAS )) {
63
64
return generateKey ().getPublic ();
64
65
}
65
- KeyStore .Entry entry = keyStore .getEntry (PP_KEYSTORE_ALIAS , null );
66
- if (!(entry instanceof KeyStore .PrivateKeyEntry )) {
67
- return null ;
66
+
67
+ // FYI https://stackoverflow.com/questions/52024752/android-9-keystore-exception-android-os-servicespecificexception
68
+ if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .P ) {
69
+ return keyStore .getCertificate (PP_KEYSTORE_ALIAS ).getPublicKey ();
70
+ } else {
71
+ KeyStore .Entry kentry = keyStore .getEntry (PP_KEYSTORE_ALIAS , null );
72
+ return kentry instanceof KeyStore .PrivateKeyEntry
73
+ ? ((KeyStore .PrivateKeyEntry ) kentry ).getCertificate ().getPublicKey ()
74
+ : null ;
68
75
}
69
- return ((KeyStore .PrivateKeyEntry ) entry ).getCertificate ().getPublicKey ();
70
76
}
71
77
72
78
/**
@@ -81,11 +87,16 @@ private static PrivateKey getPrivateKey() throws Exception {
81
87
if (!keyStore .containsAlias (PP_KEYSTORE_ALIAS )) {
82
88
return generateKey ().getPrivate ();
83
89
}
84
- KeyStore .Entry entry = keyStore .getEntry (PP_KEYSTORE_ALIAS , null );
85
- if (!(entry instanceof KeyStore .PrivateKeyEntry )) {
86
- return null ;
90
+
91
+ // FYI https://stackoverflow.com/questions/52024752/android-9-keystore-exception-android-os-servicespecificexception
92
+ if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .P ) {
93
+ return (PrivateKey ) keyStore .getKey (PP_KEYSTORE_ALIAS , null );
94
+ } else {
95
+ KeyStore .Entry entry = keyStore .getEntry (PP_KEYSTORE_ALIAS , null );
96
+ return entry instanceof KeyStore .PrivateKeyEntry
97
+ ? ((KeyStore .PrivateKeyEntry ) entry ).getPrivateKey ()
98
+ : null ;
87
99
}
88
- return ((KeyStore .PrivateKeyEntry ) entry ).getPrivateKey ();
89
100
}
90
101
91
102
/**
0 commit comments