Calculation of the hash value of chunks in Java block chain
There are many methods of calculation, such as, can be directly splicing string, can also be used StringBuffer, or StringBuilder. It uses a faster StringBuilder, and can use stringbuffer when programming.
Where index is the index of block block, timestamp is the time stamp of block block, data is the block contained in the chunk, the nonce is the difficulty coefficient of the block. The overall calculation code is as follows:
/** * 计算hash服务 * @param index 索引 * @param previousHash 前一个区块的hash值 * @param timestamp 时间戳 * @param data 数据 * @param nonce 难度系数 * @return 当前hash */ private String calculateHash(int index, String previousHash, long timestamp, String data,long nonce) { StringBuilder builder = new StringBuilder(index); builder.append(previousHash).append(timestamp).append(data).append(nonce); return CryptoUtil.getSHA256(builder.toString()); }
Simple implementation of SHA-256 algorithm in Java blockchain
Java SHA-256 Tool class implementation, with the JDK with the tool messagedigest.getinstance ("SHA-256");
Package Cn.wenwuyi.blockchain.util;import java.security.messagedigest;/** * Class Name: Cryptoutil.java * Description: TODO * Time: March 12, 2018 PM 7:06:04 * @author Cn.wenwuyi * @version 1.0 */public class Cryptoutil {private Cryptoutil () {} public static string getSHA256 (String str) {MessageDigest messagedigest; String encodestr = ""; try {messagedigest = messagedigest.getinstance ("SHA-256"); Messagedigest.update (Str.getbytes ("UTF-8")); Encodestr = Byte2hex (Messagedigest.digest ()); } catch (Exception e) {System.out.println ("getSHA256 is Error" + e.getmessage ()); } return ENCODESTR; } private static String Byte2hex (byte[] bytes) {StringBuilder builder = new StringBuilder (); String temp; for (int i = 0; i < bytes.length; i++) {temp = integer.tohexstring (Bytes[i] & 0xFF); if (temp.length () = = 1) {builder.append ("0"); } Builder.append (temp); } return builder.tostring (); }}
Calculation of the hash value of block block in the Java blockchain blockchain