Skip to content

Instantly share code, notes, and snippets.

@qichuan
Last active October 23, 2018 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qichuan/a4880e5b9e6cf62b894cdbe239c89883 to your computer and use it in GitHub Desktop.
Save qichuan/a4880e5b9e6cf62b894cdbe239c89883 to your computer and use it in GitHub Desktop.
// Read the pinned certificate from local (i.e., assets folder)
val inputStream = context.assets.open("google.crt")
val pinnedCertificate = CertificateFactory.getInstance("X.509")
.generateCertificate(inputStream)
// Create a request to www.google.com
val url = URL("https://www.google.com")
val httpsUrlConnection = url.openConnection() as HttpsURLConnection
// Establish the connection
httpsUrlConnection.connect()
// Check the certificates and see if one of the server certificates
// matches the pinned certificate
if (httpsUrlConnection.serverCertificates.contains(pinnedCertificate)) {
// Open stream
httpsUrlConnection.inputStream
Log.d("Pinning", "Server certificates validation successful")
} else {
Log.d("Pinning", "Server certificates validation failed")
throw SSLException("Server certificates validation failed for google.com")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment