Skip to content

Instantly share code, notes, and snippets.

@faruktoptas
Last active April 27, 2021 07:14
Show Gist options
  • Save faruktoptas/4b95cbfeafea93176bd3 to your computer and use it in GitHub Desktop.
Save faruktoptas/4b95cbfeafea93176bd3 to your computer and use it in GitHub Desktop.
Public Key Pinning
public final class PubKeyManager implements X509TrustManager {
private String publicKey;
public PubKeyManager(String publicKey) {
this.publicKey = publicKey;
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
if (chain == null) {
throw new IllegalArgumentException(
“checkServerTrusted: X509Certificate array is null”);
}
if (!(chain.length > 0)) {
throw new IllegalArgumentException(
“checkServerTrusted: X509Certificate is empty”);
}
// Perform customary SSL/TLS checks
TrustManagerFactory tmf;
try {
tmf = TrustManagerFactory.getInstance(“X509”);
tmf.init((KeyStore) null);
for (TrustManager trustManager : tmf.getTrustManagers()) {
((X509TrustManager) trustManager).checkServerTrusted(
chain, authType);
}
} catch (Exception e) {
throw new CertificateException(e.toString());
}
// Hack ahead: BigInteger and toString(). We know a DER encoded Public
// Key starts with 0x30 (ASN.1 SEQUENCE and CONSTRUCTED), so there is
// no leading 0x00 to drop.
RSAPublicKey pubkey = (RSAPublicKey) chain[0].getPublicKey();
String encoded = new BigInteger(1 /* positive */, pubkey.getEncoded())
.toString(16);
// Pin it!
final boolean expected = publicKey.equalsIgnoreCase(encoded);
// fail if expected public key is different from our public key
if (!expected) {
throw new CertificateException(
“Not trusted”);
}
}
}
@trungnn-1883
Copy link

@faruktoptas thanks you for your answer. I understood it : )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment