首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >计算SHA-256散列时的前导零

计算SHA-256散列时的前导零
EN

Stack Overflow用户
提问于 2019-02-27 14:51:28
回答 1查看 6.2K关注 0票数 4

我正在尝试将同一个文件的SHA-256哈希值与Python和Java进行比较。但是,在某些情况下,Python哈希值有前导零,而Java版本则没有。例如,在两个程序中对somefile.txt进行散列处理会产生以下结果:

Python:000c3720cf1066fcde30876f498f060b0b3ad4e21abd473588f1f31f10fdd890

Java:c3720cf1066fcde30876f498f060b0b3ad4e21abd473588f1f31f10fdd890

简单地删除前导0并进行比较是安全的,还是存在不产生前导零的实现?

Python代码

代码语言:javascript
复制
def sha256sum(filename):
    h  = hashlib.sha256()
    b  = bytearray(128*1024)
    mv = memoryview(b)
    with open(filename, 'rb', buffering=0) as f:
        for n in iter(lambda : f.readinto(mv), 0):
            h.update(mv[:n])
    return h.hexdigest()

print(sha256sum('/somepath/somefile.txt'))

# 000c3720cf1066fcde30876f498f060b0b3ad4e21abd473588f1f31f10fdd890

Java代码

代码语言:javascript
复制
public static String calculateSHA256(File updateFile) {
    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "Exception while getting digest", e);
        return null;
    }

    InputStream is;
    try {
        is = new FileInputStream(updateFile);
    } catch (FileNotFoundException e) {
        Log.e(TAG, "Exception while getting FileInputStream", e);
        return null;
    }

    byte[] buffer = new byte[8192];
    int read;
    try {
        while ((read = is.read(buffer)) > 0) {
            digest.update(buffer, 0, read);
        }
        byte[] shaSum = digest.digest();
        BigInteger bigInt = new BigInteger(1, shaSum);
        String output = bigInt.toString(16);
        return output;
    } catch (IOException e) {
        throw new RuntimeException("Unable to process file for SHA256", e);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            Log.e(TAG, "Exception on closing SHA256 input stream", e);
        }
    }
}

Log.i("Output", calculateSHA256(somefile))

// I/Output: c3720cf1066fcde30876f498f060b0b3ad4e21abd473588f1f31f10fdd890
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-27 14:56:37

BigInteger转换忽略SHA-256散列中的前导零。相反,您应该直接编码byte[]。如建议的在这个答案中,您可以使用String.format()

代码语言:javascript
复制
StringBuilder sb = new StringBuilder();
for (byte b : shaSum) {
    sb.append(String.format("%02X", b));
}
return sb.toString();

当编码为十六进制字符串时,SHA-256值按照wiki示例有64个字符。

SHA256("") 0x e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54908161

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档