Android和Python不同的SHA1校验和相同的文件

时间:2013-10-29 08:15:25

标签: android python sha1 checksum sha

情景是下一个:

我想将图片上传到服务器。但在上传文件之前,我必须发送该文件的SHA1校验和,以便服务器检查文件是否已经上传,所以我不再上传。

问题是对于同一个文件,我的应用程序和服务器端没有得到相同的SHA1校验和。

以下是我的Android应用中的代码:

public static String getSHA1FromFileContent(String filename)
        throws NoSuchAlgorithmException, IOException {

    final MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");

    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    final byte[] buffer = new byte[1024];

    for (int read = 0; (read = is.read(buffer)) != -1;) {
        messageDigest.update(buffer, 0, read);
    }

    is.close();

    // Convert the byte to hex format
    Formatter formatter = new Formatter();

    for (final byte b : messageDigest.digest()) {
        formatter.format("%02x", b);
    }

    String res = formatter.toString();

    formatter.close();

    return res;
}

这是服务器端的代码:

def hashFile(f):

sha1 = hashlib.sha1()

if hasattr(f, 'multiple_chunks') and f.multiple_chunks():
    for c in f.chunks():
    sha1.update(c)
else:
    try:
    sha1.update(f.read())
    finally:
    f.close()

return sha1.hexdigest()

问题是什么?为什么我会得到不同的SHA1校验和?

1 个答案:

答案 0 :(得分:0)

原来在生成sha1总和之前有一些服务器端图像编辑,这在这种情况下并不意味着要完成。他们在服务器端进行了更改,现在效果非常好。