Created
May 21, 2020 11:10
-
-
Save alexnitu88/cb121c6beba87c7528a111deac5eda33 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context; | |
import android.content.pm.PackageInfo; | |
import android.content.pm.PackageManager; | |
import android.content.pm.Signature; | |
import androidx.annotation.NonNull; | |
import java.security.MessageDigest; | |
import java.security.NoSuchAlgorithmException; | |
public class AppUtil { | |
private final static char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); | |
private static final String SIGNATURE_DIGEST_ALGORITHM = "SHA1"; | |
public static String getAppCertSignature(@NonNull Context context, @NonNull String packageName) { | |
try { | |
PackageManager pm = context.getPackageManager(); | |
PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES); | |
if (packageInfo == null | |
|| packageInfo.signatures == null | |
|| packageInfo.signatures.length == 0 | |
|| packageInfo.signatures[0] == null) { | |
return null; | |
} | |
return signatureDigest(packageInfo.signatures[0]); | |
} catch (PackageManager.NameNotFoundException e) { | |
return null; | |
} | |
} | |
private static String signatureDigest(Signature sig) { | |
byte[] signature = sig.toByteArray(); | |
try { | |
MessageDigest md = MessageDigest.getInstance(SIGNATURE_DIGEST_ALGORITHM); | |
byte[] digest = md.digest(signature); | |
return bytesToHex(digest).toLowerCase(); | |
} catch (NoSuchAlgorithmException e) { | |
return null; | |
} | |
} | |
private static String bytesToHex(final byte[] bytes) { | |
if ((bytes == null) || (bytes.length == 0)) { | |
return ""; | |
} | |
final char[] hexChars = new char[bytes.length * 2]; | |
for (int j = 0; j < bytes.length; j++) { | |
int v = bytes[j] & 0xFF; | |
hexChars[j * 2] = HEX_ARRAY[v >>> 4]; | |
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; | |
} | |
return new String(hexChars); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment