I am trying to do client certificate authenticiation in dart. But when I compile the app with flutter I keep getting cert.p12 not found. Here is my way of doing certificate authentication.
HttpClient createHttpClient(SecurityContext context) {
final cert = "assets/cert.p12";
final password = "mittal";
final sc = SecurityContext.defaultContext
..useCertificateChain(cert, password: password)
..usePrivateKey(cert, password: password);
return super.createHttpClient(sc)
My assets folder is at the root of the project and cert.p12 is in it. Please help.
Here is a screenshot of android studio :
I have read the https://flutter.dev/docs/development/ui/assets-and-images and and added, but still the same problem. Please Help
flutter:
assets:
- assets/
- assets/cert.p12
You actually say this:
String cert = "assets/cert.p12"
<-- you don't load the cert, you create a String.
This is an example how it works for me:
final clientCert = await rootBundle.load('assets/cert.p12');
context.useCertificateChainBytes(clientCert.buffer.asUint8List(), password: password);
This is a full example:
class MyHttpOverrides extends HttpOverrides {
ByteData clientCert;
ByteData keystore;
MyHttpOverrides({
required this.clientCert,
required this.keystore,
});
@override
HttpClient createHttpClient(SecurityContext? context) {
context = SecurityContext.defaultContext;
bool _certificateCheck(truststore, String host, int port) {
return host == "test.backend.com";
}
String password = "password";
context.useCertificateChainBytes(clientCert.buffer.asUint8List(), password: password);
context.usePrivateKeyBytes(keystore.buffer.asUint8List(), password: password);
HttpClient client = super.createHttpClient(context)..badCertificateCallback = (_certificateCheck);
client..badCertificateCallback = (_certificateCheck);
return client;
}
}
And use it like this:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final clientCert = await rootBundle.load('assets/cert.pem');
final keystore = await rootBundle.load('assets/key.pem');
HttpOverrides.global = MyHttpOverrides(
clientCert: clientCert,
keystore: keystore,
);
runApp(MyApp());
}
These are the imports:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';