Skip to content

Instantly share code, notes, and snippets.

@aspnetde
Created January 17, 2017 14:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspnetde/8df8d0e6c02c3d847db1cd2a8823b208 to your computer and use it in GitHub Desktop.
Save aspnetde/8df8d0e6c02c3d847db1cd2a8823b208 to your computer and use it in GitHub Desktop.
An AndroidClientHandler implementation supporting Certificate Pinning
using System.IO;
using Java.Security;
using Java.Security.Cert;
using Javax.Net.Ssl;
using Xamarin.Android.Net;
namespace NeunundsechzigGrad.Foo
{
public class DroidTlsClientHandler : AndroidClientHandler
{
private TrustManagerFactory _trustManagerFactory;
private KeyManagerFactory _keyManagerFactory;
private KeyStore _keyStore;
protected override TrustManagerFactory ConfigureTrustManagerFactory(KeyStore keyStore)
{
if (_trustManagerFactory != null)
{
return _trustManagerFactory;
}
_trustManagerFactory = TrustManagerFactory
.GetInstance(TrustManagerFactory.DefaultAlgorithm);
_trustManagerFactory.Init(keyStore);
return _trustManagerFactory;
}
protected override KeyManagerFactory ConfigureKeyManagerFactory(KeyStore keyStore)
{
if (_keyManagerFactory != null)
{
return _keyManagerFactory;
}
_keyManagerFactory = KeyManagerFactory
.GetInstance(KeyManagerFactory.DefaultAlgorithm);
_keyManagerFactory.Init(keyStore, null);
return _keyManagerFactory;
}
protected override KeyStore ConfigureKeyStore(KeyStore keyStore)
{
if (_keyStore != null)
{
return _keyStore;
}
_keyStore = KeyStore.GetInstance(KeyStore.DefaultType);
_keyStore.Load(null, null);
CertificateFactory cff = CertificateFactory.GetInstance("X.509");
Certificate cert;
// Add your Certificate to the Assets folder and address it here by its name
using (Stream certStream = Android.App.Application.Context.Assets.Open("your_certificate.cert"))
{
cert = cff.GenerateCertificate(certStream);
}
_keyStore.SetCertificateEntry("TrustedCert", cert);
return _keyStore;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment