我正在PHP和Android中生成SHA1密钥来验证文件。但是我得到了PHP和Android的不同密钥。
人造人:
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
byte[] buffer = new byte[65536];
InputStream fis = new FileInputStream(downloadFile.getPath());
int n = 0;
while (n != -1) {
n = fis.read(buffer);
if (n > 0) {
digest.update(buffer, 0, n);
}
}
fis.close();
byte[] digestResult = digest.digest();
log("CheckSum : " + byteArray2Hex(digestResult));
} catch (Exception e) {
log("Exception : " + e.getLocalizedMessage());
}
.PHP:
echo ' 'nSHA1 File hash of '. $filePath . ': ' . sha1_file($filePath);
校验和输出:
PHP SHA1 校验和 : e7a91cd4127149a230f3dcb5ae81605615d3e1be安卓 SHA1 校验和 : 19bcbd9d18a3880d2375bddb9181d75da3f32da0
谁能帮忙如何处理这个问题。
从这个 SO 答案: https://stackoverflow.com/a/9855338/3393666 考虑使用这个 byteArray2Hex 函数:
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String byteArray2Hex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
我已经在java 1.7与PHP 7和Android 5.0上进行了测试,使用SDK 23编译。希望这有帮助。