Skip to content

Commit 70e3194

Browse files
committed
修复从 keystore 获取数据可能失败
1 parent 7d10989 commit 70e3194

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

chat/src/main/java/cn/wildfire/chat/app/misc/KeyStoreUtil.java

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import android.content.Context;
44
import android.content.SharedPreferences;
5+
import android.os.Build;
56
import android.security.keystore.KeyGenParameterSpec;
67
import android.security.keystore.KeyProperties;
78

@@ -62,11 +63,16 @@ private static PublicKey getPublicKey() throws Exception {
6263
if (!keyStore.containsAlias(PP_KEYSTORE_ALIAS)) {
6364
return generateKey().getPublic();
6465
}
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;
6875
}
69-
return ((KeyStore.PrivateKeyEntry) entry).getCertificate().getPublicKey();
7076
}
7177

7278
/**
@@ -81,11 +87,16 @@ private static PrivateKey getPrivateKey() throws Exception {
8187
if (!keyStore.containsAlias(PP_KEYSTORE_ALIAS)) {
8288
return generateKey().getPrivate();
8389
}
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;
8799
}
88-
return ((KeyStore.PrivateKeyEntry) entry).getPrivateKey();
89100
}
90101

91102
/**

0 commit comments

Comments
 (0)