http_certificate_pinning 1.0.3

  • Readme
  • Changelog
  • Example
  • Installing
  • 70

Http Certificate Pinning #

Https Certificate pinning for Flutter

This project ins based on ssl_pinning_plugin

Any help is appreciated! Comment, suggestions, issues, PR's!

Getting Started #

In your flutter or dart project add the dependency:

dependencies:
  ...
  http_certificate_pinning: 1.0.2

Get Certificate FingerPrint #

To get SHA256 certificate fingerprint run in console:

openssl x509 -noout -fingerprint -sha256 -inform pem -in [certificate-file.crt]

The Result is like:

'59:58:57:5A:5B:5C:5D:59:58:57:5A:5B:5C:5D:59:58:57:5A:5B:5C:5D:59:58:57:5A:5B:5C:5D:59:58:57:5A:5B:5C:5D'

Usage example #

Using Dio #

import 'package:http_certificate_pinning/certificate_pinning_interceptor.dart';
  
  // Add CertificatePinningInterceptor in dio Client
  Dio getClient(String baseUrl, List<String> allowedSHAFingerprints){
      var dio =  Dio(BaseOptions(baseUrl: baseUrl))
        ..interceptors.add(CertificatePinningInterceptor(allowedSHAFingerprints));
      return dio;
  }

  myRepositoryMethod(){ 
    dio.get("myurl.com");
  }    

Using Http #

import 'package:http_certificate_pinning/secure_http_client.dart';
  
  // Uses SecureHttpClient to make requests
  SecureHttpClient getClient(List<String> allowedSHAFingerprints){
      final secureClient = SecureHttpClient.build(certificateSHA256Fingerprints);
      return secureClient;
  }

  myRepositoryMethod(){ 
    secureClient.get("myurl.com");
  }    

Other Client #

import 'package:http_certificate_pinning/http_certificate_pinning.dart';
  
Future myCustomImplementation(String url, Map<String,String> headers, List<String> allowedSHAFingerprints) async {
  try{
    final secure = await HttpCertificatePinning.check(
      serverURL: url,
      headerHttp: headers,
      sha: SHA.SHA256,
      allowedSHAFingerprints:allowedSHAFingerprints,
      timeout : 50
    );

    if(secure.contains("CONNECTION_SECURE")){
      return true;
    }else{
      return false;
    }
  }catch(e){
    return false;
  }
}

1.0.0 #

1.0.1 #

Accepts ':' in certificates

1.0.2 #

1.0.3 #

Downgrade Alamofire version

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http_certificate_pinning/http_certificate_pinning.dart';

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _PiningSslData {
  String serverURL = '';
  Map<String, String> headerHttp = new Map();
  String allowedSHAFingerprint = '';
  int timeout = 0;
  SHA sha;
}

class _MyAppState extends State<MyApp> {
  final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  _PiningSslData _data = new _PiningSslData();
  BuildContext scaffoldContext;

  @override
  initState() {
    super.initState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  check(String url, String fingerprint, SHA sha, Map<String, String> headerHttp, int timeout) async {

    List<String> allowedShA1FingerprintList = new List();
    allowedShA1FingerprintList.add(fingerprint);

    try {
      // Platform messages may fail, so we use a try/catch PlatformException.
      String checkMsg = await HttpCertificatePinning.check(serverURL: url,
          headerHttp: headerHttp,
          sha: sha,
          allowedSHAFingerprints: allowedShA1FingerprintList,
          timeout: timeout);

      // If the widget was removed from the tree while the asynchronous platform
      // message was in flight, we want to discard the reply rather than calling
      // setState to update our non-existent appearance.
      if (!mounted)
        return;

      Scaffold.of(scaffoldContext).showSnackBar(
        new SnackBar(
          content: new Text(checkMsg),
          duration: Duration(seconds: 1),
          backgroundColor: Colors.green,
        ),

      );
    }catch (e){
      Scaffold.of(scaffoldContext).showSnackBar(
        new SnackBar(
          content: new Text(e.toString()),
          duration: Duration(seconds: 1),
          backgroundColor: Colors.red,
        ),

      );
    }

  }

  void submit() {
    // First validate form.
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save(); // Save our form now.

      this.check(_data.serverURL, _data.allowedSHAFingerprint, _data.sha, _data.headerHttp, _data.timeout);
    }
  }

  @override
  Widget build(BuildContext context) {
    this.scaffoldContext = context;
    return new MaterialApp(
      home: new Scaffold(
          appBar: new AppBar(
            title: new Text('Ssl Pinning Plugin'),
          ),
          body:
          new Builder(builder: (BuildContext context) {
            this.scaffoldContext = context;
            return Container(
                padding: EdgeInsets.all(20.0),
                child: Form(
                  key: this._formKey,
                  child: new ListView(
                    children: <Widget>[
                      TextFormField(
                          keyboardType: TextInputType.url,
                          decoration: InputDecoration(
                              hintText: 'https://yourdomain.com',
                              labelText: 'URL'
                          ),
                          validator: (value) {
                            if (value.isEmpty) {
                              return 'Please enter some url';
                            }
                          },
                          onSaved: (String value) {
                            this._data.serverURL = value;
                          }
                      ),
                      DropdownButton(
                        items: [DropdownMenuItem(child: Text(SHA.SHA1.toString()), value: SHA.SHA1,), DropdownMenuItem(child: Text(SHA.SHA256.toString()), value: SHA.SHA256,)],
                        value: _data.sha,
                        isExpanded: true,
                        onChanged: (SHA val){
                          setState(() {
                            this._data.sha = val;
                          });
                        },
                      ),
                      TextFormField(
                          keyboardType: TextInputType.text,
                          decoration: InputDecoration(
                              hintText: 'OO OO OO OO OO OO OO OO OO OO',
                              labelText: 'Fingerprint'
                          ),
                          validator: (value) {
                            if (value.isEmpty) {
                              return 'Please enter some fingerprint';
                            }
                          },
                          onSaved: (String value) {
                            this._data.allowedSHAFingerprint = value;
                          }
                      ),
                      TextFormField(
                          keyboardType: TextInputType.number,
                          initialValue: '60',
                          decoration: InputDecoration(
                              hintText: '60',
                              labelText: 'Timeout'
                          ),
                          validator: (value) {
                            if (value.isEmpty) {
                              return 'Please enter some timeout';
                            }
                          },
                          onSaved: (String value) {
                            this._data.timeout = int.parse(value);
                          }
                      ),
                      Container(
                        child: RaisedButton(
                          child: Text(
                            'Check',
                            style: TextStyle(
                                color: Colors.white
                            ),
                          ),
                          onPressed: () => submit(),
                          color: Colors.blue,
                        ),
                        margin: EdgeInsets.only(
                            top: 20.0
                        ),
                      )
                    ],
                  ),
                )
            );
          })
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  http_certificate_pinning: ^1.0.3

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:http_certificate_pinning/http_certificate_pinning.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
48
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
80
Overall:
Weighted score of the above. [more]
70
Learn more about scoring.

We analyzed this package on Mar 31, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6
  • Flutter: 1.12.13+hotfix.8

Health suggestions

Format lib/certificate_pinning_interceptor.dart.

Run flutter format to format lib/certificate_pinning_interceptor.dart.

Format lib/http_certificate_pinning.dart.

Run flutter format to format lib/http_certificate_pinning.dart.

Format lib/secure_http_client.dart.

Run flutter format to format lib/secure_http_client.dart.

Maintenance suggestions

The package description is too short. (-20 points)

Add more detail to the description field of pubspec.yaml. Use 60 to 180 characters to describe the package, what it does, and its target use case.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
dio ^3.0.9 3.0.9
flutter 0.0.0
http ^0.12.0+4 0.12.0+4
Transitive dependencies
async 2.4.1
charcode 1.1.3
collection 1.14.11 1.14.12
http_parser 3.1.4
meta 1.1.8
path 1.6.4
pedantic 1.9.0
sky_engine 0.0.99
source_span 1.7.0
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test