Skip to content

Instantly share code, notes, and snippets.

@williamdes
Created June 27, 2017 13:24
Show Gist options
  • Save williamdes/ace24f0a6bbaf4465d721eebe874c89f to your computer and use it in GitHub Desktop.
Save williamdes/ace24f0a6bbaf4465d721eebe874c89f to your computer and use it in GitHub Desktop.
Get a fingerprint (String SHA-256) from a android.content.pm.Signature Object
/**
* Get fingerprint from a certificate in android.content.pm.Signature
* @return String fingerprint that contains the SHA-256 digest
*/
private static String getFingerprint(android.content.pm.Signature ce){
String certificate = "";
InputStream input = new ByteArrayInputStream(ce.toByteArray());
CertificateFactory cf = null;
try {
cf = CertificateFactory.getInstance("X509");
} catch (CertificateException e) {
e.printStackTrace();
}
X509Certificate c = null;
try {
if (cf != null) {
c = (X509Certificate) cf.generateCertificate(input);
}
} catch (CertificateException e) {
e.printStackTrace();
}
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] publicKey = new byte[0];
if (c != null) {
publicKey = md.digest(c.getEncoded());
}
StringBuilder hexString = new StringBuilder();
for (byte aPublicKeybyte : publicKey) {
String appendString = Integer.toHexString(0xFF & aPublicKeybyte);
if (appendString.length() == 1) hexString.append("0");
hexString.append(appendString);
}
certificate = hexString.toString();
} catch (NoSuchAlgorithmException | CertificateEncodingException e1) {
e1.printStackTrace();
}
return certificate;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment