Skip to content

Commit 7da490d

Browse files
authored
Use java.util.Logger as it's common (#58)
1 parent 7ca1626 commit 7da490d

File tree

8 files changed

+52
-38
lines changed

8 files changed

+52
-38
lines changed

lib/src/main/java/at/bitfire/cert4android/CertUtils.kt

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,15 @@ import java.security.MessageDigest
1010
import java.security.cert.X509Certificate
1111
import java.util.Locale
1212
import java.util.logging.Level
13+
import java.util.logging.Logger
1314
import javax.net.ssl.TrustManagerFactory
1415
import javax.net.ssl.X509TrustManager
1516

1617
object CertUtils {
1718

19+
private val logger
20+
get() = Logger.getLogger(javaClass.name)
21+
1822
fun getTrustManager(keyStore: KeyStore?): X509TrustManager? {
1923
try {
2024
val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
@@ -23,7 +27,7 @@ object CertUtils {
2327
.filterIsInstance<X509TrustManager>()
2428
.forEach { return it }
2529
} catch(e: GeneralSecurityException) {
26-
Cert4Android.log.log(Level.SEVERE, "Couldn't initialize trust manager", e)
30+
logger.log(Level.SEVERE, "Couldn't initialize trust manager", e)
2731
}
2832
return null
2933
}

lib/src/main/java/at/bitfire/cert4android/ConscryptIntegration.kt

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,14 @@ package at.bitfire.cert4android
22

33
import org.conscrypt.Conscrypt
44
import java.security.Security
5+
import java.util.logging.Logger
56
import javax.net.ssl.SSLContext
67

78
object ConscryptIntegration {
89

10+
private val logger
11+
get() = Logger.getLogger(javaClass.name)
12+
913
private var initialized = false
1014

1115
@Synchronized
@@ -17,11 +21,11 @@ object ConscryptIntegration {
1721
Security.insertProviderAt(Conscrypt.newProvider(), 1)
1822

1923
val version = Conscrypt.version()
20-
Cert4Android.log.info("Using Conscrypt/${version.major()}.${version.minor()}.${version.patch()} for TLS")
24+
logger.info("Using Conscrypt/${version.major()}.${version.minor()}.${version.patch()} for TLS")
2125

2226
val engine = SSLContext.getDefault().createSSLEngine()
23-
Cert4Android.log.info("Enabled protocols: ${engine.enabledProtocols.joinToString(", ")}")
24-
Cert4Android.log.info("Enabled ciphers: ${engine.enabledCipherSuites.joinToString(", ")}")
27+
logger.info("Enabled protocols: ${engine.enabledProtocols.joinToString(", ")}")
28+
logger.info("Enabled ciphers: ${engine.enabledCipherSuites.joinToString(", ")}")
2529

2630
initialized = true
2731
}

lib/src/main/java/at/bitfire/cert4android/CustomCertManager.kt

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import android.content.Context
99
import kotlinx.coroutines.flow.StateFlow
1010
import java.security.cert.CertificateException
1111
import java.security.cert.X509Certificate
12+
import java.util.logging.Logger
1213
import javax.net.ssl.SSLSession
1314
import javax.net.ssl.X509TrustManager
1415

@@ -29,6 +30,9 @@ class CustomCertManager @JvmOverloads constructor(
2930
var appInForeground: StateFlow<Boolean>?
3031
): X509TrustManager {
3132

33+
private val logger
34+
get() = Logger.getLogger(javaClass.name)
35+
3236
val certStore = CustomCertStore.getInstance(context)
3337

3438

@@ -67,7 +71,7 @@ class CustomCertManager @JvmOverloads constructor(
6771
// default HostnameVerifier says trusted → OK
6872
return true
6973

70-
Cert4Android.log.warning("Host name \"$hostname\" not verified, checking whether certificate is explicitly trusted")
74+
logger.warning("Host name \"$hostname\" not verified, checking whether certificate is explicitly trusted")
7175
// Allow users to explicitly accept certificates that have a bad hostname here
7276
(session.peerCertificates.firstOrNull() as? X509Certificate)?.let { cert ->
7377
// Check without trusting system certificates so that the user will be asked even for system-trusted certificates

lib/src/main/java/at/bitfire/cert4android/CustomCertStore.kt

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import java.security.KeyStore
1919
import java.security.cert.CertificateException
2020
import java.security.cert.X509Certificate
2121
import java.util.logging.Level
22+
import java.util.logging.Logger
2223

2324
class CustomCertStore internal constructor(
2425
private val context: Context,
@@ -46,6 +47,9 @@ class CustomCertStore internal constructor(
4647

4748
}
4849

50+
private val logger
51+
get() = Logger.getLogger(javaClass.name)
52+
4953
/** system default TrustStore */
5054
private val systemKeyStore by lazy { Conscrypt.getDefaultX509TrustManager() }
5155

@@ -64,7 +68,7 @@ class CustomCertStore internal constructor(
6468

6569
@Synchronized
6670
fun clearUserDecisions() {
67-
Cert4Android.log.info("Clearing user-(dis)trusted certificates")
71+
logger.info("Clearing user-(dis)trusted certificates")
6872

6973
for (alias in userKeyStore.aliases())
7074
userKeyStore.deleteEntry(alias)
@@ -104,7 +108,7 @@ class CustomCertStore internal constructor(
104108
}
105109

106110
if (appInForeground == null) {
107-
Cert4Android.log.log(Level.INFO, "Certificate not known and running in non-interactive mode, rejecting")
111+
logger.log(Level.INFO, "Certificate not known and running in non-interactive mode, rejecting")
108112
return false
109113
}
110114

@@ -116,7 +120,7 @@ class CustomCertStore internal constructor(
116120
ui.check(cert, appInForeground.value)
117121
}
118122
} catch (_: TimeoutCancellationException) {
119-
Cert4Android.log.log(Level.WARNING, "User timeout while waiting for certificate decision, rejecting")
123+
logger.log(Level.WARNING, "User timeout while waiting for certificate decision, rejecting")
120124
false
121125
}
122126
}
@@ -133,7 +137,7 @@ class CustomCertStore internal constructor(
133137
@Synchronized
134138
fun setTrustedByUser(cert: X509Certificate) {
135139
val alias = CertUtils.getTag(cert)
136-
Cert4Android.log.info("Trusted by user: ${cert.subjectDN.name} ($alias)")
140+
logger.info("Trusted by user: ${cert.subjectDN.name} ($alias)")
137141

138142
userKeyStore.setCertificateEntry(alias, cert)
139143
saveUserKeyStore()
@@ -143,7 +147,7 @@ class CustomCertStore internal constructor(
143147

144148
@Synchronized
145149
fun setUntrustedByUser(cert: X509Certificate) {
146-
Cert4Android.log.info("Distrusted by user: ${cert.subjectDN.name}")
150+
logger.info("Distrusted by user: ${cert.subjectDN.name}")
147151

148152
// find certificate
149153
val alias = userKeyStore.getCertificateAlias(cert)
@@ -162,14 +166,14 @@ class CustomCertStore internal constructor(
162166
try {
163167
FileInputStream(userKeyStoreFile).use {
164168
userKeyStore.load(it, null)
165-
Cert4Android.log.fine("Loaded ${userKeyStore.size()} trusted certificate(s)")
169+
logger.fine("Loaded ${userKeyStore.size()} trusted certificate(s)")
166170
}
167171
} catch(_: Exception) {
168-
Cert4Android.log.fine("No key store for trusted certificates (yet); creating in-memory key store.")
172+
logger.fine("No key store for trusted certificates (yet); creating in-memory key store.")
169173
try {
170174
userKeyStore.load(null, null)
171175
} catch(e: Exception) {
172-
Cert4Android.log.log(Level.SEVERE, "Couldn't initialize in-memory key store", e)
176+
logger.log(Level.SEVERE, "Couldn't initialize in-memory key store", e)
173177
}
174178
}
175179
}
@@ -179,7 +183,7 @@ class CustomCertStore internal constructor(
179183
try {
180184
FileOutputStream(userKeyStoreFile).use { userKeyStore.store(it, null) }
181185
} catch(e: Exception) {
182-
Cert4Android.log.log(Level.SEVERE, "Couldn't save custom certificate key store", e)
186+
logger.log(Level.SEVERE, "Couldn't save custom certificate key store", e)
183187
}
184188
}
185189

lib/src/main/java/at/bitfire/cert4android/Cert4Android.kt renamed to lib/src/main/java/at/bitfire/cert4android/ThemeManager.kt

Lines changed: 1 addition & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,29 +4,13 @@
44

55
package at.bitfire.cert4android
66

7-
import android.util.Log
87
import androidx.compose.foundation.layout.Box
98
import androidx.compose.foundation.layout.safeDrawingPadding
109
import androidx.compose.material3.MaterialTheme
1110
import androidx.compose.runtime.Composable
1211
import androidx.compose.ui.Modifier
13-
import java.util.logging.Level
14-
import java.util.logging.Logger
15-
16-
object Cert4Android {
17-
18-
// logging
19-
20-
const val TAG = "cert4android"
21-
22-
var log: Logger = Logger.getLogger(TAG)
23-
init {
24-
log.level = if (Log.isLoggable(TAG, Log.VERBOSE))
25-
Level.ALL
26-
else
27-
Level.INFO
28-
}
2912

13+
object ThemeManager {
3014

3115
// theme
3216

lib/src/main/java/at/bitfire/cert4android/TrustCertificateActivity.kt

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ import java.security.spec.MGF1ParameterSpec.SHA1
5353
import java.security.spec.MGF1ParameterSpec.SHA256
5454
import java.text.DateFormat
5555
import java.util.logging.Level
56+
import java.util.logging.Logger
5657

5758
class TrustCertificateActivity : ComponentActivity() {
5859

@@ -78,7 +79,7 @@ class TrustCertificateActivity : ComponentActivity() {
7879
enableEdgeToEdge()
7980

8081
setContent {
81-
Cert4Android.theme {
82+
ThemeManager.theme {
8283
MainLayout(
8384
onRegisterDecision = { trusted -> model.registerDecision(trusted) },
8485
onFinish = { finish() }
@@ -304,6 +305,9 @@ class TrustCertificateActivity : ComponentActivity() {
304305

305306
class Model(application: Application) : AndroidViewModel(application) {
306307

308+
private val logger
309+
get() = Logger.getLogger(javaClass.name)
310+
307311
private var cert: X509Certificate? = null
308312

309313
var uiState by mutableStateOf(UiState())
@@ -337,7 +341,7 @@ class TrustCertificateActivity : ComponentActivity() {
337341
)
338342
}
339343
} catch (e: CertificateParsingException) {
340-
Cert4Android.log.log(Level.WARNING, "Couldn't parse certificate", e)
344+
logger.log(Level.WARNING, "Couldn't parse certificate", e)
341345
}
342346
}
343347
}

lib/src/main/java/at/bitfire/cert4android/UserDecisionRegistry.kt

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import androidx.core.app.NotificationCompat
88
import androidx.core.app.TaskStackBuilder
99
import kotlinx.coroutines.suspendCancellableCoroutine
1010
import java.security.cert.X509Certificate
11+
import java.util.logging.Logger
1112
import kotlin.coroutines.Continuation
1213
import kotlin.coroutines.resume
1314

@@ -33,6 +34,9 @@ class UserDecisionRegistry private constructor(
3334

3435
}
3536

37+
private val logger
38+
get() = Logger.getLogger(javaClass.name)
39+
3640
internal val pendingDecisions = mutableMapOf<X509Certificate, MutableList<Continuation<Boolean>>>()
3741

3842
/**
@@ -86,7 +90,7 @@ class UserDecisionRegistry private constructor(
8690

8791
} else {
8892
// We're not able to retrieve user feedback, directly reject request
89-
Cert4Android.log.warning("App not in foreground and missing notification permission, rejecting certificate")
93+
logger.warning("App not in foreground and missing notification permission, rejecting certificate")
9094
cont.resume(false)
9195
}
9296
}

sample-app/src/main/java/at/bitfire/cert4android/demo/MainActivity.kt

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@ import androidx.core.app.ActivityCompat
3131
import androidx.lifecycle.AndroidViewModel
3232
import androidx.lifecycle.MutableLiveData
3333
import androidx.lifecycle.viewModelScope
34-
import at.bitfire.cert4android.Cert4Android
3534
import at.bitfire.cert4android.CustomCertManager
3635
import at.bitfire.cert4android.CustomCertStore
36+
import at.bitfire.cert4android.ThemeManager
3737
import kotlinx.coroutines.Dispatchers
3838
import kotlinx.coroutines.flow.MutableStateFlow
3939
import kotlinx.coroutines.launch
@@ -54,7 +54,7 @@ class MainActivity : ComponentActivity() {
5454
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), 0)
5555

5656
setContent {
57-
Cert4Android.theme {
57+
ThemeManager.theme {
5858
Column(Modifier
5959
.padding(8.dp)
6060
.verticalScroll(rememberScrollState())) {
@@ -125,6 +125,12 @@ class MainActivity : ComponentActivity() {
125125

126126
class Model(application: Application): AndroidViewModel(application) {
127127

128+
companion object {
129+
130+
const val TAG = "cert4android.sample-app"
131+
132+
}
133+
128134
val appInForeground = MutableStateFlow(true)
129135
val resultMessage = MutableLiveData<String>()
130136

@@ -160,12 +166,12 @@ class MainActivity : ComponentActivity() {
160166
}
161167

162168
// access sample URL
163-
Log.i(Cert4Android.TAG, "testAccess(): HTTP ${urlConn.responseCode}")
169+
Log.i(TAG, "testAccess(): HTTP ${urlConn.responseCode}")
164170
resultMessage.postValue("${urlConn.responseCode} ${urlConn.responseMessage}")
165171
urlConn.inputStream.close()
166172
} catch (e: Exception) {
167173
resultMessage.postValue("testAccess() ERROR: ${e.message}")
168-
Log.w(Cert4Android.TAG, "testAccess(): ERROR: ${e.message}")
174+
Log.w(TAG, "testAccess(): ERROR: ${e.message}")
169175
}
170176
}
171177

0 commit comments

Comments
 (0)