android_keyring/
lib.rs

1use jni::{JNIEnv, objects::JObject};
2use shared_preferences::Context;
3
4#[cfg(feature = "android-log")]
5pub mod android_log;
6pub mod cipher;
7pub mod credential;
8pub mod keystore;
9pub mod methods;
10pub mod shared_preferences;
11#[cfg(feature = "compile_tests")]
12pub mod tests;
13
14// package io.crates.keyring
15// import android.content.Context
16// class Keyring {
17//     companion object {
18//         init {
19//             System.loadLibrary("android_keyring")
20//         }
21//         external fun setAndroidKeyringCredentialBuilder(context: Context);
22//     }
23// }
24#[unsafe(no_mangle)]
25pub extern "system" fn Java_io_crates_keyring_Keyring_00024Companion_setAndroidKeyringCredentialBuilder(
26    env: JNIEnv,
27    _class: JObject,
28    context: JObject,
29) {
30    let context = match Context::new(&env, context) {
31        Ok(context) => context,
32        Err(e) => {
33            tracing::error!(%e, "error converting context jobject into Context");
34            tracing::debug!(?e);
35            return;
36        }
37    };
38
39    let builder = match credential::AndroidBuilder::new(&env, context) {
40        Ok(builder) => builder,
41        Err(e) => {
42            tracing::error!(%e, "error initialized AndroidBuilder credential builder");
43            tracing::debug!(?e);
44            return;
45        }
46    };
47
48    keyring::set_default_credential_builder(Box::new(builder));
49}
50
51/// Initializes the android-keyring from pure Rust (no Java call needed).
52/// Requires the `ndk-context` feature.
53#[cfg(feature = "ndk-context")]
54pub fn set_android_keyring_credential_builder() -> Result<(), credential::AndroidKeyringError> {
55    keyring::set_default_credential_builder(Box::new(
56        credential::AndroidBuilder::from_ndk_context()?,
57    ));
58
59    Ok(())
60}