Skip to content

Instantly share code, notes, and snippets.

@aimore
Last active September 28, 2018 04:47
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 aimore/6685fc3a2485e000a3914bf641bc85f2 to your computer and use it in GitHub Desktop.
Save aimore/6685fc3a2485e000a3914bf641bc85f2 to your computer and use it in GitHub Desktop.
Android signature security validation for Xamarin.Android
public bool ValidateAppSignature(Android.Content.Context context)
{
PackageInfo packageInfo = context.PackageManager.GetPackageInfo(context.PackageName, PackageInfoFlags.Signatures);
//note sample just checks the first signature
foreach (Signature signature in packageInfo.Signatures) {
// SHA1 the signature
String sha1 = GetSHA1(signature.ToByteArray());
// check is matches hardcoded value
return APP_SIGNATURE.Equals(sha1);
}
//computed the sha1 hash of the signature
public static String GetSHA1(byte[] sig)
{
Java.Security.MessageDigest digest = Java.Security.MessageDigest.GetInstance("SHA1", "BC");
digest.Update(sig);
byte[] hashtext = digest.Digest();
return BytesToHex(hashtext);
}
//util method to convert byte array to hex string
public static String BytesToHex(byte[] bytes)
{
char[] hexArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F' };
char[] hexChars = new char[bytes.Length * 2];
int v;
for (int j = 0; j < bytes.Length; j++)
{
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[(int)((uint)v >> 4)];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment