Search code examples
fluttercryptographyflutter-secure-storage

Flutter - Authenticate with a pin


I want to lock my app with a 6 digit pin. When the user creates a new pin the hash of this pin is saved in flutter secure storage. A pin is proofed by getting the hashed pin from the secure storage and comparing them. Would this be secure?

import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:steel_crypt/steel_crypt.dart';

//Saves the hash of the pin in FlutterSecureStorage
Future<void> createPin(String pin) async {

  const secureStorage = FlutterSecureStorage();

  //Hash the pin and save the hash
  var hasher = HashCrypt(algo: HashAlgo.Sha_256);
  String hashedPin = hasher.hash(inp: pin);

  await secureStorage.write(key: "hashedPin", value: hashedPin)
  return;
}


//Check if the given pin is correct
Future<bool> checkPin(String pin) async {

  const secureStorage = FlutterSecureStorage();
  var hashedPin = await secureStorage.read(key: "hashedPin")

  var hasher = HashCrypt(algo: HashAlgo.Sha_256);

  return hasher.check(plain: pin, hashed: hashedPin);
}

Solution

  • Disclaimer: I am not a certified security expert, but based on what I do know about it, I'd say it's quite secure.

    I did the exact same thing on another app of mine, and here is the reasoning/logic when determining that it was secure enough for my use case:

    1. Flutter secure storage uses methods channels to Android's KeyStore and iOS's Keychain - those are operating system APIs provided by Apple & Google to us developers, and are made specifically for storing sensitive data.

    When those APIs encrypt and decrypt values, only the operating system (not even our own apps) have access to the decryption keys and/or salts. Meaning no apps, not even our own could decrypt without the help of the operating system, who governs who should have access to decrypt something for a given app.

    1. Like your approach, I was also storing the pin as a one way hash only (and not the actual pin, the truly sensitive data) and using flutter secure storage (hence OS provided encryption) also means that the data is encrypted at rest.

    2. Future checks on pin input were also one way hashed, and compared to the securely stored value.

    That said, it's all software running on an environment you don't control, so could it be hacked? Yes. But I'd trust the Apple and Googles data security engineer's abilities to harden against attacks far more than mine.