Skip to content

Instantly share code, notes, and snippets.

@willblaschko
Created May 5, 2016 15:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willblaschko/95136b6b9e8b509213d616e5e09deeba to your computer and use it in GitHub Desktop.
Save willblaschko/95136b6b9e8b509213d616e5e09deeba to your computer and use it in GitHub Desktop.
...
if(BuildConfig.DEBUG) {
Log.i("Key", SigningKey.getCertificateMD5Fingerprint(this));
}
...
public class SigningKey {
/**
* Get the MD5 fingerprint required for application authentication on the server to set up security profiles
* @param context any Context from the running application
* @return the string equivalent of the MD5 fingerprint
*/
public static String getCertificateMD5Fingerprint(Context context) {
PackageManager pm = context.getPackageManager();
String packageName = context.getPackageName();
int flags = PackageManager.GET_SIGNATURES;
PackageInfo packageInfo = null;
try {
packageInfo = pm.getPackageInfo(packageName, flags);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
Signature[] signatures = packageInfo.signatures;
byte[] cert = signatures[0].toByteArray();
InputStream input = new ByteArrayInputStream(cert);
CertificateFactory cf = null;
try {
cf = CertificateFactory.getInstance("X509");
} catch (CertificateException e) {
e.printStackTrace();
}
X509Certificate c = null;
try {
c = (X509Certificate) cf.generateCertificate(input);
} catch (CertificateException e) {
e.printStackTrace();
}
String hexString = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] publicKey = md.digest(c.getEncoded());
hexString = byte2HexFormatted(publicKey);
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (CertificateEncodingException e) {
e.printStackTrace();
}
return hexString;
}
/**
* Convert the resulting byte array into a string for submission
* @param arr the byte array supplied by getCertificateMD5Fingerprint
* @return the string equivalent
*/
public static String byte2HexFormatted(byte[] arr) {
StringBuilder str = new StringBuilder(arr.length * 2);
for (int i = 0; i < arr.length; i++) {
String h = Integer.toHexString(arr[i]);
int l = h.length();
if (l == 1) h = "0" + h;
if (l > 2) h = h.substring(l - 2, l);
str.append(h.toUpperCase());
if (i < (arr.length - 1)) str.append(':');
}
return str.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment