Calculation of the hash value of the block BLOCK in the Java blockchain BLOCKCHAIN

Calculation of the hash value of the block in the Java blockchain

There are many calculation methods, such as direct String splicing, stringbuffer, or stringbuilder. The faster stringbuilder is used here, and stringbuffer can be used when programming by yourself.
Where index is the index of the block BLOCK, timestamp is the timestamp of the block BLOCK, data is the data contained in the block BLOCK, and 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

The implementation of java's SHA-256 tool class, using jdk's own tool MessageDigest.getInstance("SHA-256");

package cn.wenwuyi.blockchain.util;

import java.security.MessageDigest;

/**
 * 
 * 类名:CryptoUtil.java
 * 描述:TODO
 * 时间:2018年3月12日 下午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();
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324980386&siteId=291194637