Is there a way to retrieve the signature of the key used to sign an APK? I signed my APK with my key from my keystore. How can I retrieve it programmatically?
You can access the APK's signing signature like this using the PackageManager class
http://developer.android.com/reference/android/content/pm/PackageManager.html
Signature[] sigs = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES).signatures;
for (Signature sig : sigs)
{
Trace.i("MyApp", "Signature hashcode : " + sig.hashCode());
}
I've used this to compare with the hashcode for my debug key, as a way to identify whether the APK is a debug APK or a release APK.
The package manager will give you the signing certificate for any installed package. You can then print out the details of the signing key, e.g.
final PackageManager packageManager = context.getPackageManager();
final List<PackageInfo> packageList = packageManager.getInstalledPackages(PackageManager.GET_SIGNATURES);
for (PackageInfo p : packageList) {
final String strName = p.applicationInfo.loadLabel(packageManager).toString();
final String strVendor = p.packageName;
sb.append("<br>" + strName + " / " + strVendor + "<br>");
final Signature[] arrSignatures = p.signatures;
for (final Signature sig : arrSignatures) {
/*
* Get the X.509 certificate.
*/
final byte[] rawCert = sig.toByteArray();
InputStream certStream = new ByteArrayInputStream(rawCert);
try {
CertificateFactory certFactory = CertificateFactory.getInstance("X509");
X509Certificate x509Cert = (X509Certificate) certFactory.generateCertificate(certStream);
sb.append("Certificate subject: " + x509Cert.getSubjectDN() + "<br>");
sb.append("Certificate issuer: " + x509Cert.getIssuerDN() + "<br>");
sb.append("Certificate serial number: " + x509Cert.getSerialNumber() + "<br>");
sb.append("<br>");
}
catch (CertificateException e) {
// e.printStackTrace();
}
}
}
My situation is that I have a pre-installed apk which use a wrong key-store . So directly install will give a fail because of inconsistent signature.I need to check the signature first to make sure it can be install smoothly.
Here is my solution.
As this code says, you can get the signature from an installed apk.
details:
Signature sig = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES).signatures[0];
Secondly: get the releaseApk hashCode to compare. In my case, I downloaded this apk from my server, and put it in the sd_card.
Signature releaseSig = context.getPackageManager().getPackageArchiveInfo("/mnt/sdcard/myReleaseApk.apk", PackageManager.GET_SIGNATURES).signatures[0];
Finally,compare the hashCode.
return sig.hashCode() == releaseSig.hashCode;
I have tried the code above, it works just fine. If the hashCode is different, you should just uninstall the old apk or if it's a system app and the device is rooted, you can just use runtime to remove it,and then install the new signature apk.
Related
So using the keytool command I was able to generate a hash key for my Android app which uses Facebook login. For purposes of this question, the hash the keytool outputted was "abcdefg=". But when I try to sign on to Facebook from my app, the error says "Key hash abcdefg does not match any stored key hashes" and shows the same exact key I got from keytool just without the equal sign at the end. Why is it not working? Also, when I try to manually type in the key hash on my Facebook developer console (instead of copy/paste), it won't take the key without the equals sign because it only takes keys whose character count is divisible by 4 (my key with equals sign has 28 chars, the key without has only 27 chars). Can someone help?
updateLanguage(getApplicationContext(), "en");
printHashKey(getApplicationContext(),"ur application package name here");
Note1: Create apk file with release keystore.then run on device the keyhash will print logcat. copy the keyhash and place it on facebook app edit setting page.
Note2: correct keyhash generate only on device. dont use simulator for getting keyhash.
public static String printHashKey(Context context, String packagename)
{
String TAG = packagename;
try
{
Log.d(TAG, "keyHash: start");
PackageInfo info = context.getPackageManager().getPackageInfo(TAG,PackageManager.GET_SIGNATURES);
for (Signature signature: info.signatures)
{
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String keyHash = Base64.encodeToString(md.digest(), Base64.DEFAULT);
Log.d(TAG, "keyHash: " + keyHash);
return keyHash;
}
Log.d(TAG, "keyHash: end");
}
catch (NameNotFoundException e)
{
Log.d(TAG, "keyHash: name:"+e);
}
catch (NoSuchAlgorithmException e)
{
Log.d(TAG, "keyHash: name:"+e);
}
return "error";
}
public static void updateLanguage(Context context, String code)
{
Locale locale = new Locale(code);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
}
Is there a way to retrieve the signature of the key used to sign an APK? I signed my APK with my key from my keystore. How can I retrieve it programmatically?
You can access the APK's signing signature like this using the PackageManager class
http://developer.android.com/reference/android/content/pm/PackageManager.html
Signature[] sigs = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES).signatures;
for (Signature sig : sigs)
{
Trace.i("MyApp", "Signature hashcode : " + sig.hashCode());
}
I've used this to compare with the hashcode for my debug key, as a way to identify whether the APK is a debug APK or a release APK.
The package manager will give you the signing certificate for any installed package. You can then print out the details of the signing key, e.g.
final PackageManager packageManager = context.getPackageManager();
final List<PackageInfo> packageList = packageManager.getInstalledPackages(PackageManager.GET_SIGNATURES);
for (PackageInfo p : packageList) {
final String strName = p.applicationInfo.loadLabel(packageManager).toString();
final String strVendor = p.packageName;
sb.append("<br>" + strName + " / " + strVendor + "<br>");
final Signature[] arrSignatures = p.signatures;
for (final Signature sig : arrSignatures) {
/*
* Get the X.509 certificate.
*/
final byte[] rawCert = sig.toByteArray();
InputStream certStream = new ByteArrayInputStream(rawCert);
try {
CertificateFactory certFactory = CertificateFactory.getInstance("X509");
X509Certificate x509Cert = (X509Certificate) certFactory.generateCertificate(certStream);
sb.append("Certificate subject: " + x509Cert.getSubjectDN() + "<br>");
sb.append("Certificate issuer: " + x509Cert.getIssuerDN() + "<br>");
sb.append("Certificate serial number: " + x509Cert.getSerialNumber() + "<br>");
sb.append("<br>");
}
catch (CertificateException e) {
// e.printStackTrace();
}
}
}
My situation is that I have a pre-installed apk which use a wrong key-store . So directly install will give a fail because of inconsistent signature.I need to check the signature first to make sure it can be install smoothly.
Here is my solution.
As this code says, you can get the signature from an installed apk.
details:
Signature sig = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES).signatures[0];
Secondly: get the releaseApk hashCode to compare. In my case, I downloaded this apk from my server, and put it in the sd_card.
Signature releaseSig = context.getPackageManager().getPackageArchiveInfo("/mnt/sdcard/myReleaseApk.apk", PackageManager.GET_SIGNATURES).signatures[0];
Finally,compare the hashCode.
return sig.hashCode() == releaseSig.hashCode;
I have tried the code above, it works just fine. If the hashCode is different, you should just uninstall the old apk or if it's a system app and the device is rooted, you can just use runtime to remove it,and then install the new signature apk.
As all we do I have application which is signed by debug.keystore (by default) when it is in development mode (build). When it goes production we sign it with our private key.
Is there any way to determine at runtime that current package is signed with debug.keystore (is in development mode) or is signed with our private key (is in production mode).
I have tried something like
PackageManager packageManager = getPackageManager();
try {
Signature[] signs = packageManager.getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES).signatures;
for (Signature signature : signs) {
Log.d(TAG, "sign = " + signature.toCharsString());
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
I don't know what to do next? Is this right way of doing this? How to obtain comparable debug.keystore signature?
I know that exists MD5 Fingerprint keytool -list -keystore ~/.android/debug.keystore but in Signature class there is not "md5 fingerprint"-like method.
I want to do this because of MapView Key, Logging, LicenseChecker and stuff like this.
The signature in PackageInfo does not seem to be well named since tha field does not contain the package signature but the signer X509 certificate chain. Note that (most of the time) this chain seems to be limited to one single self-signed certificate.
According to the Android developer page Signing Your Applications the debug signature certificate is generated with this DN: CN=Android Debug,O=Android,C=US
Therefore it is easy to test if the application has been signed in debug mode:
private static final X500Principal DEBUG_DN = new X500Principal("CN=Android Debug,O=Android,C=US");
/* ... */
Signature raw = packageManager.getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES).signatures[0];
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(raw.toByteArray()));
boolean debug = cert.getSubjectX500Principal().equals(DEBUG_DN);
Based on Jcs' answer, we use this to find out at runtime who built the running package:
private enum BuildSigner {
unknown,
Joe,
Carl,
Linda
}
private BuildSigner whoBuiltThis() {
try {
PackageManager packageManager = getPackageManager();
PackageInfo info = packageManager.getPackageInfo(getPackageName(),
PackageManager.GET_SIGNATURES);
Signature[] signs = info.signatures;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate)cf.generateCertificate(
new ByteArrayInputStream(signs[0].toByteArray()));
PublicKey key = cert.getPublicKey();
int modulusHash = ((RSAPublicKey)key).getModulus().hashCode();
switch (modulusHash) {
case 123456789:
return BuildSigner.Joe;
case 424242424:
return BuildSigner.Carl;
case -975318462:
return BuildSigner.Linda;
}
} catch (Exception e) {
}
return BuildSigner.unknown;
}
For any involved certificate, you then just have to find the hash once and add it to the list.
The simplest way to "find the hash once" may be to just add a popup toast before the switch statement that displays modulusHash, compile your app, run it, write down the hash, remove the toast code and add the hash to the list.
Alternatively, when I implemented this, I created a little boilerplate app with a single activity and a single TextView with the ID tv in the main layout, put this into the activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int hash = 0;
try{
PackageManager packageManager = getPackageManager();
PackageInfo info = packageManager.getPackageInfo(
"com.stackexchange.marvin", PackageManager.GET_SIGNATURES);
Signature[] signs = info.signatures;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(
new ByteArrayInputStream(signs[0].toByteArray()));
PublicKey key = cert.getPublicKey();
hash = ((RSAPublicKey) key).getModulus().hashCode();
}catch(Exception e){}
TextView tv = ((TextView)findViewById(R.id.tv));
tv.setText("The Stack Exchange app's signature hash is " + hash + ".");
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 24);
}
(change com.stackexchange.marvin to your app's name), compiled this mini-app, and sent the APK to all involved developers, asking them to run it on their dev device and let me know the displayed hash.
As all we do I have application which is signed by debug.keystore (by default) when it is in development mode (build). When it goes production we sign it with our private key.
Is there any way to determine at runtime that current package is signed with debug.keystore (is in development mode) or is signed with our private key (is in production mode).
I have tried something like
PackageManager packageManager = getPackageManager();
try {
Signature[] signs = packageManager.getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES).signatures;
for (Signature signature : signs) {
Log.d(TAG, "sign = " + signature.toCharsString());
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
I don't know what to do next? Is this right way of doing this? How to obtain comparable debug.keystore signature?
I know that exists MD5 Fingerprint keytool -list -keystore ~/.android/debug.keystore but in Signature class there is not "md5 fingerprint"-like method.
I want to do this because of MapView Key, Logging, LicenseChecker and stuff like this.
The signature in PackageInfo does not seem to be well named since tha field does not contain the package signature but the signer X509 certificate chain. Note that (most of the time) this chain seems to be limited to one single self-signed certificate.
According to the Android developer page Signing Your Applications the debug signature certificate is generated with this DN: CN=Android Debug,O=Android,C=US
Therefore it is easy to test if the application has been signed in debug mode:
private static final X500Principal DEBUG_DN = new X500Principal("CN=Android Debug,O=Android,C=US");
/* ... */
Signature raw = packageManager.getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES).signatures[0];
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(raw.toByteArray()));
boolean debug = cert.getSubjectX500Principal().equals(DEBUG_DN);
Based on Jcs' answer, we use this to find out at runtime who built the running package:
private enum BuildSigner {
unknown,
Joe,
Carl,
Linda
}
private BuildSigner whoBuiltThis() {
try {
PackageManager packageManager = getPackageManager();
PackageInfo info = packageManager.getPackageInfo(getPackageName(),
PackageManager.GET_SIGNATURES);
Signature[] signs = info.signatures;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate)cf.generateCertificate(
new ByteArrayInputStream(signs[0].toByteArray()));
PublicKey key = cert.getPublicKey();
int modulusHash = ((RSAPublicKey)key).getModulus().hashCode();
switch (modulusHash) {
case 123456789:
return BuildSigner.Joe;
case 424242424:
return BuildSigner.Carl;
case -975318462:
return BuildSigner.Linda;
}
} catch (Exception e) {
}
return BuildSigner.unknown;
}
For any involved certificate, you then just have to find the hash once and add it to the list.
The simplest way to "find the hash once" may be to just add a popup toast before the switch statement that displays modulusHash, compile your app, run it, write down the hash, remove the toast code and add the hash to the list.
Alternatively, when I implemented this, I created a little boilerplate app with a single activity and a single TextView with the ID tv in the main layout, put this into the activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int hash = 0;
try{
PackageManager packageManager = getPackageManager();
PackageInfo info = packageManager.getPackageInfo(
"com.stackexchange.marvin", PackageManager.GET_SIGNATURES);
Signature[] signs = info.signatures;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(
new ByteArrayInputStream(signs[0].toByteArray()));
PublicKey key = cert.getPublicKey();
hash = ((RSAPublicKey) key).getModulus().hashCode();
}catch(Exception e){}
TextView tv = ((TextView)findViewById(R.id.tv));
tv.setText("The Stack Exchange app's signature hash is " + hash + ".");
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 24);
}
(change com.stackexchange.marvin to your app's name), compiled this mini-app, and sent the APK to all involved developers, asking them to run it on their dev device and let me know the displayed hash.
Is there a way to retrieve the signature of the key used to sign an APK? I signed my APK with my key from my keystore. How can I retrieve it programmatically?
You can access the APK's signing signature like this using the PackageManager class
http://developer.android.com/reference/android/content/pm/PackageManager.html
Signature[] sigs = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES).signatures;
for (Signature sig : sigs)
{
Trace.i("MyApp", "Signature hashcode : " + sig.hashCode());
}
I've used this to compare with the hashcode for my debug key, as a way to identify whether the APK is a debug APK or a release APK.
The package manager will give you the signing certificate for any installed package. You can then print out the details of the signing key, e.g.
final PackageManager packageManager = context.getPackageManager();
final List<PackageInfo> packageList = packageManager.getInstalledPackages(PackageManager.GET_SIGNATURES);
for (PackageInfo p : packageList) {
final String strName = p.applicationInfo.loadLabel(packageManager).toString();
final String strVendor = p.packageName;
sb.append("<br>" + strName + " / " + strVendor + "<br>");
final Signature[] arrSignatures = p.signatures;
for (final Signature sig : arrSignatures) {
/*
* Get the X.509 certificate.
*/
final byte[] rawCert = sig.toByteArray();
InputStream certStream = new ByteArrayInputStream(rawCert);
try {
CertificateFactory certFactory = CertificateFactory.getInstance("X509");
X509Certificate x509Cert = (X509Certificate) certFactory.generateCertificate(certStream);
sb.append("Certificate subject: " + x509Cert.getSubjectDN() + "<br>");
sb.append("Certificate issuer: " + x509Cert.getIssuerDN() + "<br>");
sb.append("Certificate serial number: " + x509Cert.getSerialNumber() + "<br>");
sb.append("<br>");
}
catch (CertificateException e) {
// e.printStackTrace();
}
}
}
My situation is that I have a pre-installed apk which use a wrong key-store . So directly install will give a fail because of inconsistent signature.I need to check the signature first to make sure it can be install smoothly.
Here is my solution.
As this code says, you can get the signature from an installed apk.
details:
Signature sig = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES).signatures[0];
Secondly: get the releaseApk hashCode to compare. In my case, I downloaded this apk from my server, and put it in the sd_card.
Signature releaseSig = context.getPackageManager().getPackageArchiveInfo("/mnt/sdcard/myReleaseApk.apk", PackageManager.GET_SIGNATURES).signatures[0];
Finally,compare the hashCode.
return sig.hashCode() == releaseSig.hashCode;
I have tried the code above, it works just fine. If the hashCode is different, you should just uninstall the old apk or if it's a system app and the device is rooted, you can just use runtime to remove it,and then install the new signature apk.