区块链--java入门案例

参考:https://yq.aliyun.com/articles/65264?utm_content=m_41935

定义:区块链分布式数据存储、点对点传输、共识机制、加密算法等计算机技术的新型应用模式。所谓共识机制是区块链系统中实现不同节点之间建立信任、获取权益的数学算法

1  环境:jdk 1.8   所需jar :gson-2.8.2.jar


2.代码

import java.util.ArrayList;
import java.util.Date;

import com.google.gson.GsonBuilder;

import java.security.MessageDigest;

/**
 * 定义区块链中的块
 * 
 * @author Administrator
 *
 */
public class Blockchain {
	public static void main(String[] args) {

		// test1();
		test2();
	}

	private static void test1() {
		Block genesisBlock = new Block("Hi im the first block", "0");
		System.out.println("Hash for block 1 : " + genesisBlock.hash);

		Block secondBlock = new Block("Yo im the second block", genesisBlock.hash);
		System.out.println("Hash for block 2 : " + secondBlock.hash);

		Block thirdBlock = new Block("Hey im the third block", secondBlock.hash);
		System.out.println("Hash for block 3 : " + thirdBlock.hash);
	}

	private static void test2() {
		ArrayList<Block> blockchain = new ArrayList<Block>();
		blockchain.add(new Block("Hi im the first block", "0"));
		blockchain.add(new Block("Yo im the second block", blockchain.get(blockchain.size() - 1).hash));
		blockchain.add(new Block("Hey im the third block", blockchain.get(blockchain.size() - 1).hash));

		String blockchainJson = new GsonBuilder().setPrettyPrinting().create().toJson(blockchain);
		System.out.println(blockchainJson);
		System.out.println(Block.isChainValid(blockchain));// 判断数据是否正确
	}
}
/***块****/
class Block {

	/**
	 * 自己的hash值
	 */
	public String hash;
	/**
	 * 上一个块中的hash值
	 */
	public String previousHash;

	/**
	 * 块数据信息
	 */
	private String data;

	/**
	 * 时间戳
	 */
	private long timeStamp;

	public Block() {

	}

	/**
	 * 
	 * @param data
	 *            块数据
	 * @param previousHash
	 *            前一个块hash值
	 */
	public Block(String data, String previousHash) {
		this.data = data;
		this.previousHash = previousHash;
		this.timeStamp = new Date().getTime();
		this.hash = calculateHash();
	}

	/**
	 * 计算hash值
	 * 
	 * @return
	 */
	public String calculateHash() {
		String calculatedhash = StringUtil.applySha256(previousHash + Long.toString(timeStamp) + data);
		return calculatedhash;
	}

	/**
	 * 
	 * @return
	 */
	public static Boolean isChainValid(ArrayList<Block> blockchain) {
		Block currentBlock;// 当前块
		Block previousBlock;// 上一个块

		for (int i = 1; i < blockchain.size(); i++) {
			currentBlock = blockchain.get(i);
			previousBlock = blockchain.get(i - 1);
			// 比较hash值:如果当前hash值和计算出来的不一致,返回false
			if (!currentBlock.hash.equals(currentBlock.calculateHash())) {
				return false;
			}
			// 如果当前块的上一个hash值,与上一个块中hash不匹配,返回false
			if (!previousBlock.hash.equals(currentBlock.previousHash)) {
				return false;
			}
		}
		return true;
	}
}

/**
 * 工具类
 * 
 * @author Administrator
 *
 */
class StringUtil {
	/**
	 * 目的:生成一个独一无二的hash值(数字签名)
	 * 
	 * 选用了SHA256这种加密方式,SHA(Secure Hash Algorithm)安全散列算法;
	 * 这种算法的特点是数据的少量更改会在Hash值中产生不可预知的大量更改;
	 * hash值用作表示大量数据的固定大小的唯一值,而SHA256算法的hash值大小为256位
	 * 
	 * @param input
	 * @return
	 */
	public static String applySha256(String input) {
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-256");

			byte[] hash = digest.digest(input.getBytes("UTF-8"));// 加密输入的数据
			StringBuffer hexString = new StringBuffer();
			for (int i = 0; i < hash.length; i++) {
				String hex = Integer.toHexString(0xff & hash[i]);// 十六进制
				if (hex.length() == 1)
					hexString.append('0');
				hexString.append(hex);
			}
			return hexString.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}


                
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值