为了防止别人很同意就破解自己的应用,在代码添加classes.dex的校检,不通过则不能继续运行,这样增加点破解的难度。
有三种方式,一种是通过获取整个app的sha1哈希值,第二种是获取classes.dex的crc32的值,第三种是获取classes.dex的sha1的值
思路来源:http://my.oschina.net/u/2323218/blog/406860
下面是参考了以上写了个工具类
public class DexVerifyUtil {
private static final String TAG = DexVerifyUtil.class.getSimpleName();
public static String getApkSHA1(Context context) {
String dexPath = context.getPackageCodePath();
String sha = null;
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
byte[] bytes = new byte[1024];
int count;
FileInputStream fis = new FileInputStream(new File(dexPath));
while ((count = fis.read(bytes)) > 0) {
messageDigest.update(bytes, 0, count);
}
BigInteger bigInteger = new BigInteger(1, messageDigest.digest());
sha = bigInteger.toString(16);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.i(TAG, "apk sha1:" + sha);
return sha;
}
public static String getDexFileCrc(Context context) {
String dexPath = context.getPackageCodePath();
String crc = null;
try {
ZipFile zipFile = new ZipFile(dexPath);
ZipEntry zipEntry = zipFile.getEntry("classes.dex");
if (zipEntry != null) {
long crc1 = zipEntry.getCrc();
crc = Long.toHexString(crc1);
}
} catch (Exception e) {
e.printStackTrace();
}
Log.i(TAG, "dex crc;" + crc);
return crc;
}
public static String getDexSHA1(Context context) {
String sha1 = null;
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
String dexPath = context.getPackageCodePath();
ZipFile zf = new ZipFile(dexPath);
ZipEntry zipEntry = zf.getEntry("classes.dex");
if (zipEntry != null) {
InputStream is = zf.getInputStream(zipEntry);
byte[] bytes = new byte[1024];
int byteCount;
while ((byteCount = is.read(bytes)) > 0) {
digest.update(bytes, 0, byteCount);
}
BigInteger bigInteger = new BigInteger(1, digest.digest());
sha1 = bigInteger.toString(16);
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
Log.i(TAG, "dex sha1:" + sha1);
return sha1;
}