區塊鏈是區塊的鏈接,每個區塊都有自己的數字簽名,它包含前一個區塊的數字簽名,除此之外還包含一些資料(這些資料可能是某些交易)。數字簽名=哈希值(Hush)。每個塊不僅包含前一個塊的哈希值,并且它自己的哈希值(這個哈希值是從前一個塊的哈希值計算來的)。如果前一個塊所包含的資料改變,那么前一個塊的哈希值將被改變(因為塊的哈希值是部分由塊所包含的資料計算得來),這會影響之后所有的塊。因此,計算和比較哈希值能幫助我們了解一個區塊鏈是否有效,因為任何資料的改變會破壞這個區塊鏈。
我們開始創建一個區塊:
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 = data;
this.previousHash = previousHash;
this.timeStamp = new Date().getTime();?
}
上面的代碼從字串hash開始,我們將會從hash生成電子簽名。而previousHash會儲存上一個塊的hush,字串data會儲存整個塊的資料。有了這些基礎,我們可以生成電子簽名,這表示我們可以選擇加密演算法。在這個例子里,我們會用SHA256加密演算法。我們輸入SHA256如下:
import java.security.MessageDigest;
public class StringUtil {
public static StringapplySha256(String input){
try {
MessageDigest digest= MessageDigest.getInstance(“SHA-256”);
byte[] hash = digest.digest(input.getBytes(“UTF-8”));
StringBuffer hexString = newStringBuffer(); // This will contain hash as hexidecimal
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);
}
}
}
這里創建了一個StringUtil應用類,之后會用到。它會接收字串及呼叫SHA256演算法,而回傳一個電子簽名。因此我們能在我們的塊型別里計算hash:用塊內所有的部分。?
public String calculateHash() {
String calculatedHash =StringUtil.applySha256(
previousHash +
Long.toString(timeStamp) +
data
);
return calculatedHash;
}
public Block(String data,String previousHash ){
this.data=https://bbs.csdn.net/topics/ data;
this.previousHash = previousHash;
this.timeStamp = newDate().getTime();
this.hash= calculateHash();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/35124.html
標籤:區塊鏈技術
上一篇:通證經濟研究院
下一篇:百多來種幣,還能買嗎?
