思路:比较打包证书的hashcode 或者 md5 值,如果二次打包了,那么这个值应该就不一致了。
public class SecondPackage{
private final static String TAG = "SecondPackage"
public SecondPackage(Context context){
// TODO Auto-generated constructor stub
this.context = context;
}
private Context context;
/************protect second package*******************/
private void byte2hex(byte b, StringBuffer buf) {
char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F' };
int high = ((b & 0xf0) >> 4);
int low = (b & 0x0f);
buf.append(hexChars[high]);
buf.append(hexChars[low]);
}
/*
* Converts a byte array to hex string
*/
private String toHexString(byte[] block) {
StringBuffer buf = new StringBuffer();
int len = block.length;
for (int i = 0; i < len; i++) {
byte2hex(block[i], buf);
if (i < len-1) {
buf.append(":");
}
}
return buf.toString();
}
public boolean getSignInfo() {
boolean checkright = false;
try {
PackageInfo packageInfo = context.getApplicationContext().getPackageManager().getPackageInfo(
"com.xxx.xxx", PackageManager.GET_SIGNATURES);
Signature[] signs = packageInfo.signatures;
Signature sign = signs[0];
int code = sign.hashCode();
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(sign.toByteArray());
byte[] digest = md.digest();
String res = toHexString(digest);
Log.e(TAG, "apk md5:"+res);
//if (code == xxxxxxxxx) {
Log.i(TAG, "hashCode:" + code);
//对比MD5值和hashcode是否和自己原来的MD5相同
if(res.equals("xxxxxxxxxx")
&& code == yyyyyyyyyy){
checkright = true;
}
//parseSignature(sign.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}
return checkright;
}
void parseSignature(byte[] signature) {
try {
CertificateFactory certFactory = CertificateFactory
.getInstance("X.509");
X509Certificate cert = (X509Certificate) certFactory
.generateCertificate(new ByteArrayInputStream(signature));
byte[] buffer = cert.getEncoded();
System.out.println( "md5: "+ new String(buffer));
} catch (CertificateException e) {
e.printStackTrace();
}
}
/***********************************/
}
调用的时候
SecondPackage sePa= new SecondPackage(this);
if(!sePa.getSignInfo()){
finish();
}