【发布时间】:2018-09-22 21:47:45
【问题描述】:
我遇到了一个涉及基本加密货币的项目。要求之一是根据文件中提供的哈希检查前一行的哈希。因此,本质上,您将计算上一行的 SHA-256 散列,与提供的散列进行比较,如果未提供有效散列,则抛出异常。
但是,我遇到了一个错误,我已将其范围缩小到实际的哈希码。据我所知,我已经验证了文件正在被正确读取,但是一旦将byte[]计算的哈希转换为提供的哈希的方法出现,它就会发现它们不等效并抛出异常。我一直在尝试调试,但真的不确定问题出在哪里。
我的代码如下。谢谢!
if (block_line == null && block_hash == "0")
{
return true; //genesis block, special hash
}
//remove new lines and tabs
block_line = block_line.replaceAll("\\r\\n", "");
byte[] hash = null;
byte[] file_hash = block_hash.getBytes();
try
{
//create SHA-256 hash of raw line to ensure following hash is correct
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(block_line.getBytes());
hash = md.digest();
}
catch (NoSuchAlgorithmException nsaex)
{
System.err.println("No SHA-256 algorithm found.");
System.err.println("This generally should not happen...");
System.exit(1);
}
//check if the hash in the file was valid for the line in question
try
{
if (Arrays.equals(hash, file_hash))
{
return true; //file hash is valid
}
else
{
throw new InvalidDataException(block_hash, 0);
}
}
catch (InvalidDataException ide)
{
System.err.println("InvalidDataException: " + ide);
ide.printStackTrace();
System.err.println("Quitting...");
return false;
}
【问题讨论】:
-
1.) 不要抛出异常并在同一个函数中捕获它。 2.) 这可能与 UTF-16 与 UTF-8 有关。 3.) 不要在每个周期都更严厉地重新创建消息摘要。 4.) 不要发布控制台输出的图像。
-
另外,你不能用 == 比较字符串,而且你没有删除制表符或单个新行,只有 CR LF
标签: java cryptography sha cryptocurrency