Home > Blockchain >  Step by step become block 3 chain developer
Step by step become block 3 chain developer

Time:09-24

The link chain is the block, each block has its own digital signature, it contains before a block of digital signature, in addition also contains some data (the data may be some trade), digital signature=hash value (Hush), before each block contains not only a piece of the hash value, and its own hash value (this hash value is a piece of the hash value of calculation), if the previous block contains data change, so before a piece of the hash value will be changed (because the piece of hash value is part of the data calculated by the block contains), it will affect after all block, therefore, to calculate and compare the hash value can help us understand a block chain is effective, because of the change of any data can destroy the block chain,

We begin to create a block:

Public class Block {

Public String hash.

Public String previousHash;

Private String data.

Private long timeStamp;

//Block Constructor.

Public Block (String data, String previousHash) {

This data=https://bbs.csdn.net/topics/data;

Enclosing previousHash=previousHash;

This. TimeStamp=new Date (). GetTime (); ?
}

The above code from the beginning of the string hash, we will from the hash generated electronic signature, and previousHash will be stored on a piece of hush, string data will be stored data of the whole block, with this basis, we can generate electronic signature, this means that we can choose the encryption algorithm, in this case, we will use SHA256 encryption algorithms, we input SHA256 as follows:

Import the Java. Security. MessageDigest;

Public class StringUtil {

Public static StringapplySha256 (String input) {

Try {

The MessageDigest digest=MessageDigest. GetInstance (" SHA - 256 ");

Byte [] hash=digest. Digest (input. GetBytes (" utf-8 "));

StringBuffer hexString=newStringBuffer ();//This will contain the hash as hexidecimal

for (int i=0; I & lt; Hash. Length; I++) {

String hex=Integer. ToHexString (0 XFF & amp; Hash [I]);

If (hex. Length ()==1) hexString. Append (' 0 ');

HexString. Append (hex);

}

Return hexString. ToString ();

}

The catch (Exception e) {

throw new RuntimeException(e);

}

}

}

Here to create a StringUtil application class, after use, it will receive a string and invoke the SHA256 algorithm, and returns an electronic signature, so we can in our block types calculated hash: with all the parts in the block,?

Public String calculateHash () {

String calculatedHash=StringUtil. ApplySha256 (

PreviousHash +

Long. ToString (timeStamp) +

The data

);

Return calculatedHash;

}

Public Block (String data, String previousHash) {

This data=https://bbs.csdn.net/topics/data;

Enclosing previousHash=previousHash;

This timeStamp=newDate (.) getTime ();

This hash=calculateHash ();

}


  • Related