# Sentinel Docs

Welcome to Sentinel - integrate it into your Kotlin Multiplatform project to detect runtime security threats across Android and iOS from a single shared codebase.

<figure><img src="https://2012990535-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvDrQNZyFZaeOKF18hXwk%2Fuploads%2F0eYkqnlz0bVI5RvYbkjA%2Fheader.png?alt=media&amp;token=dde40dbf-b832-4ba4-b832-843ec1dee3f6" alt=""><figcaption></figcaption></figure>

Sentinel is a lightweight, modular security toolkit designed specifically for Kotlin Multiplatform (KMP). It empowers mobile developers to analyze runtime environments and detect potential security threats in real-time across both Android and iOS applications from a single codebase.

{% hint style="danger" %}
Development Stage Notice Sentinel is currently in an active development and testing phase. API structures may change as new features are added. Caution is advised when deploying to production environments.
{% endhint %}

{% hint style="danger" %}
Sentinel is a client-side detection library and is not a standalone security solution. It can be bypassed on rooted or jailbroken devices by a sufficiently capable attacker.&#x20;

For robust, real-world security, Sentinel must be utilized within a defense-in-depth framework, supported by server-side verification mechanisms such as the Sentinel Attest architecture, Play Integrity API (Android), and App Attest (iOS)
{% endhint %}

{% columns %}
{% column %}

<p align="center">Android</p>

<figure><img src="https://2012990535-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvDrQNZyFZaeOKF18hXwk%2Fuploads%2FBsiD3tpu7tvKlSpAPgZv%2FSentinel-Android.gif?alt=media&amp;token=fe172244-0456-49e8-8363-9e5b793ab213" alt=""><figcaption></figcaption></figure>
{% endcolumn %}

{% column %}

<p align="center">iOS</p>

<figure><img src="https://2012990535-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvDrQNZyFZaeOKF18hXwk%2Fuploads%2Fx3Bd16ak7Le80BSwSpva%2FiOS.gif?alt=media&amp;token=17209747-cc15-4597-ab0f-98f288927d84" alt=""><figcaption></figcaption></figure>
{% endcolumn %}
{% endcolumns %}

{% file src="/files/ddtzdTtsMpYE2Bv8j0RY" %}

***

### 🛡️ Why Sentinel?

Most mobile applications rely heavily on server-side security, leaving a massive blind spot on the client side. Attacks, reverse engineering, and environment manipulations happen directly on the user's device.

Sentinel solves this by providing real-time, on-device threat detection with minimal performance overhead, ensuring your app's runtime environment remains secure.

#### Key Capabilities:

* Detect Compromised Devices: Instantly flag rooted Android devices or jailbroken iOS devices.
* Halt Runtime Manipulation: Detect dynamic hooking tools like Frida or Xposed.
* Prevent Reverse Engineering: Identify application tampering and signature mismatches.
* Isolate Unsafe Environments: Detect if the app is running on emulators, simulators, or under a debugger.

***

### ⚡ Core Features

* Kotlin Multiplatform: Natively supports Android and iOS with a clean, unified API.
* Modular Detector Architecture: Turn specific security checks on or off, or easily extend them with custom rules.
* Smart Risk Aggregation: Employs a weighted scoring system by category to prevent artificial risk inflation.
* DSL-Based Configuration: Setting up thresholds and active modules is clean, expressive, and developer-friendly.
* RASP (Runtime Application Self-Protection): Moves beyond startup checks to continuously monitor your app for injection or hooking attempts in the background.


# Quick Start

Sentinel is a lightweight, modular security toolkit designed specifically for Kotlin Multiplatform (KMP). It empowers mobile developers to analyze runtime environments and detect potential security threats in real-time across both Android and iOS applications from a single codebase.

### Dependency

```kotlin
implementation("co.rexiox:sentinel:{version}")
```

### Configuration

You can use the following method to print the appId and appIntegrity values required for your security or configuration processes and assign them to the relevant fields within the config as a ByteList:

* `appId`: Package name for Android, Bundle Identifier for iOS
* `appIntegrity`: Package signature for Android, unique digital fingerprint of the Provisioning Profile file for iOS

```kotlin
SentinelLogger.print(tag = "APP_ID", msg = Sentinel.Identity.appId.toByteList())
SentinelLogger.print(tag = "APP_INTEGRITY", msg = Sentinel.Identity.appIntegrity.toByteList())
```

#### Android Setup

```kotlin
val sentinel = Sentinel.configure(context = context) {
    config {
        appId = listOf<Byte>()
        appIntegrity = listOf<Byte>()
        threshold = 90
        isLoggingEnabled = true
    }

    all()
    // root()
    // tamper()
    // hook()
    // emulator()
    // debug()
    // location()
}
```

#### iOS Setup

```kotlin
val sentinel = Sentinel.configure {
    config {
        appId = listOf<Byte>()
        appIntegrity = listOf<Byte>()
        threshold = 90
        isLoggingEnabled = true
    }

    all()
    // jailbreak()
    // tamper()
    // hook()
    // simulator()
    // debug()
}
```

Instead of basic checks, Sentinel performs a thorough inspection of the environment and provides a detailed report based on threat severity.

> `inspect()` is a suspend function and must be executed within a coroutine scope.

```kt
val report = sentinel.inspect()
```

### Report

After the inspection completes, Sentinel returns a `SecurityReport`. This report aggregates all detected threats and provides a unified severity score and risk level for the current runtime environment.

```kotlin
println("Risk Level: ${report.riskLevel}")
println("Total Risk Score: ${report.severity} / ${report.threshold}")
println("Threat Count: ${report.threats.size}")
println("Timestamp: ${report.timestamp}")

if (report.isCompromised) println("Device integrity failed (Root/Jailbreak detected).")
if (report.isRooted) println("Root detected")
if (report.isJailbroken) println("Jailbreak detected")
if (report.isTampered) println("App tampering detected")
if (report.isHooked) println("Hooking detected")
if (report.isEmulator) println("Emulator detected")
if (report.isSimulator) println("Simulator detected")
if (report.isDebugged) println("Debugger detected")
if (report.isMockLocation) println("Mock location detected")

if (report.isSafe()) {
    println("Device is secure")
} else {
    println("Security risks detected!")
}

if (report.isCritical()) {
    println("Block app usage.")
}
```


# RASP Protection

Sentinel extends protection beyond initial startup checks by continuously monitoring the application during runtime. Through background scanning mechanisms, it detects unauthorized access attempts, runtime tampering, and external manipulation activities in real time.

```kotlin
sentinel.runtime {
    onCompromised {
        print(msg = "Device integrity failed (Root/Jailbreak detected).")
    }

    onTampered {
        print(msg = "App tampering detected.")
    }

    onHooked {
        print(msg = "Runtime hook detection.")
    }

    onSimulated {
        print(msg = "Running on Emulator/Simulator environment.")
    }

    onDebugged {
        print(msg = "Active debugging session detected.")
    }

    onCritical { score ->
        print(msg = "High risk score reached: $score")
    }

    onSafe {
        print(msg = "All systems nominal.")
    }
}
```


# Security Measures

* Hidden Keywords (Anti-Strings): Hackers cannot find or search for sensitive words like `/system/bin/su` or `magisk` in the code because they are fully encrypted into hex bytes.
* Dynamic Keys: A randomized encryption key is generated for the obfuscation process, making static bypass methods useless.
* Native C++ Barrier: The security logic is locked inside the C++ layer (Android NDK / iOS CInterop) instead of Java/Kotlin, making it extremely difficult to reverse-engineer or decompile.


# Supported Threats

The Sentinel delivers broad-spectrum security coverage for Android and iOS, protecting against multiple threat types.

<table><thead><tr><th width="160.0625">Threat</th><th width="70.87890625" align="center"></th><th>Android Features</th><th width="70.3984375" align="center"></th><th>iOS Features</th></tr></thead><tbody><tr><td><strong>Root/Jailbreak</strong></td><td align="center">✔</td><td>- Su Binary<br>- Suspicious Mount<br>- App Installed<br>- Su Command</td><td align="center">✔</td><td>- Sandbox<br>- Suspicious Symlinks<br>- App Installed<br>- URL Schemes</td></tr><tr><td><strong>Tamper</strong></td><td align="center">✔</td><td>- Package Name Changed<br>- Signature Mismatch</td><td align="center">✔</td><td>- Bundle Id Changed<br>- Provisioning Hash Mismatch</td></tr><tr><td><strong>Hooking</strong></td><td align="center">✔</td><td>- Framework Detected</td><td align="center">✔</td><td>- Framework Detected<br>- Inline Hook Detected</td></tr><tr><td><strong>Environment</strong></td><td align="center">✔</td><td>- Emulator Detected</td><td align="center">✔</td><td>- Simulator Detected</td></tr><tr><td><strong>Debugger</strong></td><td align="center">✔</td><td>- Debugger Attached<br>- Debuggable<br>- Test Keys</td><td align="center">✔</td><td>- Debugger Attached</td></tr><tr><td><strong>Location</strong></td><td align="center">✔</td><td>- Mock Setting Enabled<br>- Mock App Installed<br>- isMocked()</td><td align="center">-</td><td></td></tr></tbody></table>

<br>


# Risk Scoring

Sentinel employs a weighted risk assessment instead of a basic summation approach

* Groups threats by category
* Takes the highest severity per category
* Produces a realistic risk score

This approach prevents artificial risk inflation and provides a more accurate security assessment.


# Risk Level

RiskLevel is an enumeration class used to evaluate the risk status of system components or events. It dynamically determines and returns a risk level by analyzing a given severity value (severity) against a specific boundary limit (threshold).

### Enum Constants

The class represents 4 distinct risk levels, ordered from lowest to highest:

* **SAFE**: No risk detected; the system or component is operating normally.
* **LOW**: Low-priority risk; requires basic monitoring.
* **MEDIUM**: Moderate risk; may require mitigation planning.
* **HIGH**: Critical risk; requires immediate attention or automated intervention.

### Static Methods

#### getLevel(severity: Int, threshold: Int): RiskLevel

A factory/utility method defined inside the companion object. It can be called directly using the class name (RiskLevel.getLevel(...)) without instantiating the class.

**Parameters**

| Parameter | Type | Description                                                                |
| --------- | ---- | -------------------------------------------------------------------------- |
| severity  | Int  | The numerical representation of the current error, threat, or system load. |
| threshold | Int  | The critical boundary limit that triggers the HIGH risk level.             |

### Risk Level

```kotlin
enum class RiskLevel {
    SAFE,
    LOW,
    MEDIUM,
    HIGH;

    companion object {

        fun getLevel(severity: Int, threshold: Int): RiskLevel = when {
            severity == 0 -> SAFE
            severity >= threshold -> HIGH
            severity >= (threshold / 2) -> MEDIUM
            severity > 0 -> LOW
            else -> SAFE
        }
    }
}
```


# Overview

{% hint style="danger" %}
Development Stage Notice Sentinel is currently in an active development and testing phase. API structures may change as new features are added. Caution is advised when deploying to production environments.
{% endhint %}

Sentinel Attest is a KMP module that cryptographically signs the device integrity report generated by Sentinel and transmits it to the server. It adds a server-side verification layer to Sentinel, which operates solely on the client side.

It enables the configuration of Play Integrity for Android and App Attest for iOS. The encrypted payload transmitted to your server includes the token data from your defined configurations. Furthermore, client-side security reports generated by Sentinel are also embedded into the payload.


# How it works?

Four things are defined in the `configure` block: who will attest, which key will be used for encryption, where the nonce comes from, and where the result will be sent. This is done once and the same instance is used throughout the app.

The process starts when `execute` is called. `sentinel.inspect()` scans the current device state and produces a report. This report is combined with the platform token from `attestProvider` - Play Integrity on Android, App Attest on iOS. A one-time nonce is taken from the `nonce` block and added to the package. The resulting payload is encrypted with AES, and the AES key is encrypted with the RSA public key. Everything is packaged into an `EncryptedAttestation` object.

Then `callbacks` takes over. `verify` receives the encrypted package - posting it to your own API is your responsibility.

<figure><img src="https://2012990535-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvDrQNZyFZaeOKF18hXwk%2Fuploads%2FpfbhC0Bz7KF8iir9uwqj%2FSentinel%20Attest.png?alt=media&amp;token=77754e32-764e-49f0-9182-d118d8408eab" alt=""><figcaption></figcaption></figure>

The Sentinel report and platform token are not sent separately - they go inside a single encrypted envelope. The server opens the envelope and evaluates both together.


# Client-Side Integration

Setup for platform integration, encryption, and server communication to verify app and device authenticity.

### Dependency

```kotlin
implementation("co.rexiox:sentinel-attest:{version}")
implementation("co.rexiox:sentinel-crypto:{version}")
```

### Configuration

```kotlin
SentinelAttest.configure {
    provider = attestProvider

    publicKey = "RSA_PUBLIC_KEY"

    nonce {
        // Retrieves a backend-generated nonce to uniquely bind and validate the attestation request.
        apiService.getSecureNonce()
    
        // Client-side nonce generation (not recommended, less secure than server-provided nonce)
        // generateSecureNonce()
    }
    
    callbacks {
        verify { encryptedAttestation ->
            // Receives the encrypted attestation payload and forwards it to the backend for verification.
            // apiService.verifyAttestation(body = encryptedAttestation)
        }

        onError { error ->
            // Called when an error occurs during attestation generation, encryption, or processing.
            print("Attestation faulted. Error Code: ${error.code}")
        }

        onComplete {
            // Invoked when the attestation pipeline completes, regardless of success or failure.
        }
    }
}
```

* [**`provider`**](/attestation/attest-providers) The platform-specific component responsible for attesting the device. On Android this is Play Integrity, on iOS this is App Attest.
* **`publicKey`** The server's RSA public key. After the payload is encrypted with a randomly generated AES key, the AES key itself is encrypted with this public key before being sent to the server. This ensures the encryption key is transmitted securely - only your server, which holds the private key, can decrypt it.
* **`nonce`** A unpredictable, single-use value that eliminates the risk of replay attacks. Each `execute` call consumes one nonce. If an attacker intercepts and resends the same encrypted package, the server rejects it because the nonce has already been used.
* **`verify`** Called with the encrypted payload. Post this to your server using your preferred HTTP client (Ktor, OkHttp, Retrofit, etc.).
* **`onComplete`** Triggered when the attestation process finishes, regardless of whether it succeeded or failed.
* **`onError`** Triggered when an error occurs during the process (e.g. signing failure, encryption error).

### Execute

```kotlin
sentinelAttest.execute(report = sentinel.inspect())
```


# Server-Side Integration

This section explains how the encrypted security report sent from the Sentinel Attest client library is received, decrypted, and validated on the server side, step by step.

### 1. Nonce Generation Endpoint

Before initiating the attestation process on the client side, the client must request a short-lived cryptographically secure token (Nonce) from the server to prevent replay attacks.

`GET` `/api/v1/attestation/nonce`

* Purpose: Generates a single-use, unpredictable value and stores it temporarily on the backend.

### 2. Data Models

The raw data structure sent by the client to your server and the decrypted object models are defined below.

#### 2.1. Encrypted Request Model (Incoming Server Payload)

The client encrypts the prepared package using hybrid encryption - both asymmetric ([RSA](/attestation/cryptography)) and symmetric ([AES](/attestation/cryptography#aes-properties)) - and sends it to your server's `/api/v1/attestation/verify` endpoint via a `POST` request.

```kotlin
@Serializable
data class EncryptedAttestation(
    val encryptedKey: String,  // Base64-encoded one-time AES key, encrypted with the server's RSA Public Key
    val encryptedData: String, // Base64-encoded core payload data, encrypted with the AES key
    val iv: String             // Base64-encoded Initialization Vector (IV) used in the AES encryption
)
```

#### 2.2. Decrypted Data Model (Payload)

Once the `EncryptedAttestation` is successfully decrypted, this is the main object model you will obtain to execute your core validation logic:

```kotlin
@Serializable
data class AttestationPayload(
    val nonce: String,                      // A unique, single-use token generated by the server
    val attestationToken: String,           // The attestation token from Play Integrity (Android) or App Attest (iOS)
    val securityReport: SecurityReportDto   // Sentinel device security analysis report
    val platform: String,                   // operating system indicator: "android" or "iOS"
    val timestamp: Long                     // The epoch timestamp (ms) when the request was created on the client side
)
```

#### 2.3. Sentinel Security Report Details (SecurityReport)

This report contains the real-time security status of the device, root/jailbreak detection flags, and specific threats detected:

```kotlin
@Serializable
data class SecurityReport(
    val severity: Int,              // Total risk weight score (e.g., 90, 120, 330)
    val riskLevel: String,          // Categorized risk level (e.g., "SAFE", "LOW", "MEDIUM", "HIGH")
    val isCompromised: Boolean,     // Indicates if the device is rooted/jailbroken or if system integrity is breached
    val isTampered: Boolean,        // Indicates if the application package or its signature has been modified
    val isHooked: Boolean,          // Indicates active runtime manipulation (e.g., Frida, Xposed)
    val isVirtualDevice: Boolean,   // Indicates if the app is running on an emulator or simulator
    val isDebugged: Boolean,        // Indicates if a debugger is attached to the application
    val isMockLocation: Boolean,    // Indicates if mock or spoofed location providers are active
    val threats: List<String>,      // A list of class names representing the specific violations detected
    val timestamp: Long             // The generation timestamp of the report
)
```

### 3. Server-Side Processing Pipeline

When the server receives an attestation request (e.g., `POST /api/v1/attestation/verify`), it must execute the following operations in sequence:

#### Step 1: Hybrid Decryption

1. Decrypt the AES Key (RSA): Decrypt the incoming `EncryptedAttestation.encryptedKey` using your server's securely stored RSA Private Key to retrieve the raw symmetric AES key.
2. Decrypt the Payload (AES): Decrypt the `EncryptedAttestation.encryptedData` using the extracted AES key along with the provided `EncryptedAttestation.iv`.
3. Deserialization: Convert the resulting decrypted plaintext string (which is in JSON format) into the `AttestationPayload` object.

{% hint style="info" icon="toolbox" %}
**Tip for Testing & Debugging:** While implementing and testing your server-side validation, you can use the following trusted online tools to manually decode, decrypt, and inspect your payloads:

* [RSA Key Generator](https://emn178.github.io/online-tools/rsa/key-generator/)
* [RSA Encryption](https://emn178.github.io/online-tools/rsa/encrypt/)
* [RSA Decryption](https://emn178.github.io/online-tools/rsa/decrypt/)
* [AES Encryption](https://emn178.github.io/online-tools/aes/encrypt/)
* [AES Decryption](https://emn178.github.io/online-tools/aes/decrypt/)
* [CBOR Playground](https://hildjj.github.io/cbor2/playground/)
  {% endhint %}

#### Step 2: Nonce and Expiration Validation (Replay Attack Protection)

1. Nonce Verification: Look up the `payload.nonce` in your database or cache layer (e.g., Redis).
   * If the nonce does not exist or has already been marked as used, reject the request immediately.
   * If the nonce is valid, delete it from your system immediately to prevent any subsequent reuse.
2. Timestamp Expiration Check: Compare the server's current time with `payload.timestamp`. Reject any requests that exceed your configured threshold (e.g., older than 5 minutes) to protect against time-lagged replay attacks.

#### Step 3: Attest Provider Platform Verification

Execute secondary platform-specific validation based on the `payload.platform` flag:

* **`android`**: Forward the `payload.attestationToken` to the [official Google Play Integrity API](https://developer.android.com/google/play/integrity/standard?hl=tr#decrypt-and) servers for remote validation. Verify that the `packageName` returned by Google matches your application's unique identifier.
* **`iOS`**: Validate the `payload.attestationToken` on your backend according to Apple's native [App Attest Validation guidelines](https://developer.apple.com/documentation/devicecheck/validating-apps-that-connect-to-your-server).

#### Step 4: Sentinel Security Policy Evaluation

Enforce your specific business rules based on the telemetry inside `payload.securityReport`. You can implement flexible mitigation policies:

* Strict Policy (Full Block): If `isCompromised`, `isTampered`, or `isHooked` is `true`, or if the `riskLevel` is evaluated as `"HIGH"`, return an error response to the client and block the user from proceeding with critical transactions (e.g., money transfers, login attempts).
* Monitoring / Restricted Mode: If lighter flags like `isVirtualDevice` or `isDebugged` are triggered, you may choose to log the event or flag the user profile for review rather than terminating the session entirely.

Once all layers of validation (Decryption, Nonce lifecycle, Apple/Google ecosystem verification, and the Sentinel report) pass successfully, return a successful response (`HTTP 200 OK`) to the client.

{% hint style="info" %}
Backend Developer Note: The `threats` list contains specific technical categories of the violations caught on the client side (e.g., `Root`, `Tamper`, `Hook`). We highly recommend passing this array directly into your logging or SIEM infrastructure to analyze real-time attack trends from your backend dashboard.
{% endhint %}


# Attest Providers

Attestation providers handle platform-specific device integrity verification. On Android, the [**Play Integrity**](https://developer.android.com/google/play/integrity) is used, while on Huawei devices, the [**SysIntegrity**](https://developer.huawei.com/consumer/en/doc/Security-Guides/dysintegritydevelopment-0000001050156331) provides device integrity verification. On iOS, [**App Attest**](https://developer.apple.com/documentation/devicecheck/establishing-your-app-s-integrity) provides secure hardware-backed attestation.

{% hint style="danger" %}
Please configure and implement the providers listed below in strict accordance with their official platform documentation.
{% endhint %}

#### Play Integrity (Android)

On Android, the Play Integrity API is used to verify app and device integrity. It generates an attestation token tied to a secure nonce provided by the backend.

```kotlin
class PlayIntegrityProvider(context: Context) : AttestProvider {

    private val integrityManager = IntegrityManagerFactory.create(context)

    override suspend fun getToken(nonce: String): String {
        val integrityTokenResponse: Task<IntegrityTokenResponse> =
            integrityManager.requestIntegrityToken(
                IntegrityTokenRequest.builder()
                    .setNonce(nonce)
                    .build()
            )

        return suspendCancellableCoroutine { cont ->
            integrityTokenResponse
                .addOnSuccessListener {
                    cont.resume(it.token())
                }
                .addOnFailureListener { e ->
                    cont.resumeWithException(
                        AttestationException(
                            message = "Attestation failure: ${e.localizedMessage}",
                            code = AttestationErrorCode.ATTESTATION_FAILED
                        )
                    )
                }
        }
    }
}
```

#### App Attest (iOS)

On iOS, Apple’s App Attest service is used to generate and validate a device-bound cryptographic attestation. It ensures the app instance is legitimate and unmodified.

```kotlin
class AppAttestProvider : AttestProvider {

    @OptIn(ExperimentalForeignApi::class)
    override suspend fun getToken(nonce: String): String = suspendCancellableCoroutine { cont ->
        val service = DCAppAttestService.sharedService

        if (!service.supported) {
            cont.resumeWithException(
                AttestationException(
                    message = "App Attest is not supported.",
                    code = AttestationErrorCode.ATTESTATION_FAILED
                )
            )
            return@suspendCancellableCoroutine
        }
        
        // Cache keyId for subsequent operations.
        service.generateKeyWithCompletionHandler { keyId, error ->
            if (error != null || keyId == null) {
                cont.resumeWithException(
                    AttestationException(
                        message = "Key could not be generated: ${error?.localizedDescription}",
                        code = AttestationErrorCode.ATTESTATION_FAILED
                    )
                )
                return@generateKeyWithCompletionHandler
            }

            val hash = nonce.encodeToByteArray().sha256()

            service.attestKey(keyId = keyId, clientDataHash = hash) { attestation, attestError ->
                when {
                    attestError != null -> cont.resumeWithException(
                        AttestationException(
                            message = "Attestation failure: ${attestError.localizedDescription}",
                            code = AttestationErrorCode.ATTESTATION_FAILED
                        )
                    )

                    attestation == null -> cont.resumeWithException(
                        AttestationException(
                            message = "Attestation value empty.",
                            code = AttestationErrorCode.ATTESTATION_FAILED
                        )
                    )

                    else -> cont.resume(attestation.base64Encoding())
                }
            }
        }
    }

    @OptIn(ExperimentalForeignApi::class)
    private fun ByteArray.sha256(): NSData = memScoped {
        val input  = allocArray<ByteVar>(size)
        val digest = allocArray<UByteVar>(CC_SHA256_DIGEST_LENGTH)
        forEachIndexed { i, b -> input[i] = b }
        CC_SHA256(input, size.toUInt(), digest)
        NSData.dataWithBytes(digest, CC_SHA256_DIGEST_LENGTH.toULong())
    }

    @OptIn(ExperimentalForeignApi::class)
    fun ByteArray.toNSData(): NSData = memScoped {
        val buf = allocArray<ByteVar>(size)
        forEachIndexed { i, b -> buf[i] = b }
        NSData.dataWithBytes(buf, size.toULong())
    }
}
```

#### SysIntegrity (Huawei)

```kotlin
class SysIntegrityProvider(
    private val context: Context,
    private val appId: String,
) : AttestProvider {

    override suspend fun getToken(nonce: String): String {
        val nonceBytes = nonce.toByteArray(StandardCharsets.UTF_8)

        val sysIntegrityRequest = SysIntegrityRequest().apply {
            this.appId = this@SysIntegrityProvider.appId
            this.nonce = nonceBytes
            this.alg = "PS256"
        }

        return suspendCancellableCoroutine { continuation ->
            SafetyDetect.getClient(context)
                .sysIntegrity(sysIntegrityRequest)
                .addOnSuccessListener { response ->
                    val jwsStr = response.result

                    if (jwsStr.isNotBlank()) {
                        continuation.resume(jwsStr)
                    } else {
                        continuation.resumeWithException(
                            AttestationException(
                                message = "Attestation failure: SysIntegrity response result is null or empty",
                                code = AttestationErrorCode.ATTESTATION_FAILED
                            )
                        )
                    }
                }
                .addOnFailureListener { e ->
                    continuation.resumeWithException(
                        AttestationException(
                            message = "Attestation failure: ${e.localizedMessage}",
                            code = AttestationErrorCode.ATTESTATION_FAILED
                        )
                    )
                }
        }
    }
}
```


# Cryptography

A Hybrid Encryption Architecture is utilized for the secure transmission of attestation data, combining secure asymmetric key exchange with fast symmetric data encryption.

## Properties

RSA and AES Properties

#### RSA Properties

| Property        | Value                   |
| --------------- | ----------------------- |
| Algorithm       | RSA                     |
| Padding         | PKCS#1 v1.5             |
| Key Size        | 2048-bit                |
| Key Format      | X.509/DER (PEM)         |
| Encryption Mode | Encrypt with Public Key |
| Output Format   | Base64                  |

#### AES Properties

| Property        | Value              |
| --------------- | ------------------ |
| Algorithm       | AES                |
| Mode            | CBC                |
| Padding         | PKCS7              |
| IV length       | 16 bytes           |
| Valid key sizes | 16 / 24 / 32 bytes |
| Key chars       | A–Z a–z 0–9        |
| Output Format   | Base64             |


# Monitoring

Sentinel Monitor is a monitoring infrastructure that tracks application-layer vulnerabilities and suspicious activities in real-time and reports these threats.

### Dependency

```kotlin
implementation("co.rexiox:sentinel-monitor:{version}")
```

### Start

```kt
SentinelMonitor.start(
    appId = sentinel.config.appId.orEmpty(),
    appIntegrity = sentinel.config.appIntegrity.orEmpty(),
    threshold = sentinel.config.threshold
)
```

***

<figure><img src="https://2012990535-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvDrQNZyFZaeOKF18hXwk%2Fuploads%2FNHtMGLu2r4l1GraYuMOm%2Fimage.png?alt=media&amp;token=6eea3fe7-cc8d-4cd9-b762-6b8340cd3592" alt=""><figcaption></figcaption></figure>


# Logging

You can optionally log the report to the console / logcat for debugging purposes:

```kotlin
SentinelLogger.report(report = report)
```

<figure><img src="https://2012990535-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvDrQNZyFZaeOKF18hXwk%2Fuploads%2FHn2VsyxGFKZtOIwlen9g%2Fimage.png?alt=media&amp;token=b8833872-2c50-4e2a-ac97-ea9dc15d988a" alt=""><figcaption></figcaption></figure>


# Samples

* [Multiplatform](https://github.com/rexiox/sentinel/blob/main/sample/multiplatform)
* [Android](https://github.com/rexiox/sentinel/blob/main/sample/android)


# Benchmarks

Detailed benchmark reports are available at the following link: [Benchmark Report](https://github.com/rexiox/sentinel/blob/main/sentinel-benchmark/report/performance)


# License

```wiki
MIT License

Copyright (c) 2026 REXIOX

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```


