← quay lại
8 thg 6, 2026 0 lượt xem
FlutterYubikey

Using Yubikey to sign Flutter apps on Android

How to use Yubikey to sign Flutter apps on Android

1. Why Use a YubiKey to Sign Applications?

When developing Android applications (Flutter, React Native, or Native Android), the common approach is to generate a keystore file (.jks or .keystore) using keytool and store it directly on a computer. While simple, this method introduces several security risks:

  • The keystore file may be exposed if it is accidentally committed to GitHub.
  • The private key can be stolen by malware running on the development machine.
  • Access control becomes difficult when working in a team environment.

To completely eliminate these risks, I decided to use a YubiKey 5 NFC for application signing. By using a hardware security key:

  • The private key never leaves the device: The key is generated or imported directly into the secure chip inside the YubiKey. It cannot be copied or exported.
  • Hardware-enforced signing: Every signing operation is performed directly within the YubiKey hardware. You must physically insert the key and provide the PIN before any signing operation can occur.
  • NFC support: NFC functionality allows convenient interaction with mobile devices when needed.

2. Preparing and Configuring PKCS#11 for Android

To allow Java tools (keytool and jarsigner) to communicate with a YubiKey, we need to use the PKCS#11 standard. In this setup, I use OpenSC as the middleware layer.

Step 1: Install OpenSC

If you are using macOS, install OpenSC through Homebrew:

brew install opensc

After installation, the OpenSC PKCS#11 library (opensc-pkcs11.so) will be located at:

  • Apple Silicon (M1/M2/M3...): /opt/homebrew/lib/opensc-pkcs11.so
  • Intel Macs: /usr/local/lib/opensc-pkcs11.so

Step 2: Create the android/yubikey.cfg Configuration File

We need to create a SunPKCS11 configuration file so Java knows where to find the OpenSC library. Create a file named yubikey.cfg inside the project's android/ directory with the following content:

name = OpenSC-PKCS11
description = SunPKCS11 via OpenSC
library = /opt/homebrew/lib/opensc-pkcs11.so
slot = 0

Note: Update the library path if you are using an Intel-based Mac.

Step 3: Disable Automatic Signing in Gradle

Since the application will be signed manually after Flutter generates an unsigned .aab file, Gradle should not require a traditional keystore configuration during release builds.

Update android/app/build.gradle.kts as follows:

buildTypes {
    release {
        signingConfig = null
    }
}

Setting signingConfig = null tells Gradle that this release build does not require automatic signing during compilation.

3. Automating the Build & Sign Process

To make the build and signing workflow smoother and reduce manual mistakes, I created a Bash script that automates the entire process. The script first validates the YubiKey PIN, then builds the Flutter application, and finally signs the generated AAB using jarsigner.

Below is the complete content of build_app.sh:

#!/bin/bash

# Usage:
# ./build.sh android -> Build Android
# ./build.sh ios -> Build iOS
# ./build.sh -> Show selection menu

# --- CONFIGURATION ---
AAB_PATH="build/app/outputs/bundle/release/app-release.aab"
CFG_PATH="android/yubikey.cfg"
JARSIGNER="/Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/jarsigner"
ALIAS="Certificate for PIV Authentication"

# Read input argument
PLATFORM=$(echo "$1" | tr '[:upper:]' '[:lower:]')

if [ -z "$PLATFORM" ]; then
    echo "Operating system not specified. Please choose:"
    select opt in "Android" "iOS" "Exit"; do
        case $opt in
            "Android") PLATFORM="android"; break;;
            "iOS") PLATFORM="ios"; break;;
            "Exit") echo "Process cancelled."; exit 0;;
            *) echo "Invalid selection!";;
        esac
    done
fi

if [ "$PLATFORM" == "android" ]; then
    if [ -z "$PIN" ]; then
        read -sp "Enter YubiKey PIN: " PIN
        echo ""
    fi

    # --- VERIFY YUBIKEY PIN BEFORE BUILDING ---
    echo "Verifying YubiKey PIN..."

    KEYTOOL="${JARSIGNER/jarsigner/keytool}"

    "$KEYTOOL" -list \
        -keystore NONE \
        -storetype PKCS11 \
        -providerClass sun.security.pkcs11.SunPKCS11 \
        -providerArg "$CFG_PATH" \
        -storepass "$PIN" < /dev/null > /dev/null 2>&1

    if [ $? -ne 0 ]; then
        echo "Error: Incorrect YubiKey PIN or device not connected!"
        exit 1
    fi

    echo "YubiKey authentication successful. Starting build..."

    echo "Starting Android Build & Sign process..."
    echo "Step 1: Building AAB..."

    flutter build appbundle --obfuscate --release --split-debug-info=debug

    if [ $? -ne 0 ]; then
        echo "Error: Flutter build failed!"
        exit 1
    fi

    echo "Step 2: Signing with YubiKey (Slot 9a)..."

    "$JARSIGNER" -keystore NONE \
        -storetype PKCS11 \
        -providerClass sun.security.pkcs11.SunPKCS11 \
        -providerArg "$CFG_PATH" \
        -storepass "$PIN" \
        -sigalg SHA256withRSA \
        -digestalg SHA-256 \
        -J"--add-exports=jdk.crypto.cryptoki/sun.security.pkcs11=ALL-UNNAMED" \
        "$AAB_PATH" "$ALIAS" < /dev/null

    if [ $? -eq 0 ]; then
        echo "SUCCESS: Application signed using YubiKey!"
    else
        echo "Error: Unable to sign the AAB file. Check the .cfg file and YubiKey."
        exit 1
    fi

    echo "Step 3: Verifying certificate information..."

    "$JARSIGNER" -verify -verbose -certs "$AAB_PATH" | grep "X.509" | head -n 1

    echo "---------------------------------------------------"
    echo "DONE! The AAB file is ready for Google Play upload:"
    echo "$AAB_PATH"
    echo "---------------------------------------------------"

    open build/app/outputs/bundle/release
fi

4. Understanding the Key Technical Details

If you configure this setup manually, you will likely encounter several frustrating issues. The script above optimizes three important areas:

1. Verifying the YubiKey PIN Before Building

A common problem occurs when flutter build appbundle takes 2–5 minutes to complete, only for the signing process to fail afterward because of an incorrect PIN. This wastes valuable development time.

By using keytool -list to validate the PIN first, the script immediately stops if the PIN is incorrect or if the YubiKey is not connected.

The redirection:

< /dev/null > /dev/null 2>&1

ensures the command runs silently and does not block user input if an error occurs.

2. Using the Alias "Certificate for PIV Authentication"

When using the YubiKey PIV application, Slot 9a is typically used for authentication and contains your certificate.

Within Java's PKCS#11 provider, the alias used to reference this certificate is:

Certificate for PIV Authentication

5. Conclusion

Using a YubiKey for application signing elevates your project's security to an enterprise-grade level.

Although the initial Java PKCS#11 setup can be somewhat complex and requires precise configuration of library paths and JDK module export parameters, integrating everything into an automated script results in a fast, secure, and reliable build/sign workflow.

I hope this guide helps you better protect your application signing keys and improve the security of your software delivery process.