Building a simple blockchain in Java is a great way to learn how it works. A blockchain is a sequence of blocks linked with cryptographic hashes. In Java, you can create a Block class with data, hash, previousHash, and timestamp. Use SHA-256 to generate each block’s hash based on its content and the previous hash. For example: new Block("Second Block", previousHash). Validate each block to ensure the chain’s integrity.This project shows how secure, tamper-proof chains are built using basic Java.
Go Back🕒 12:28 PM
📅 May 24, 2025
✍️ By ChessTica542319
Data: The content or transaction information.
Let’s create a simple blockchain in Java. We'll start by defining a Block class and then build a chain using a list.
import java.util.Date;
import java.security.MessageDigest;
public class Block {
public String hash;
public String previousHash;
public String data;
private long timeStamp;
public Block(String data, String previousHash) {
this.data = data;
this.previousHash = previousHash;
this.timeStamp = new Date().getTime();
this.hash = calculateHash();
}
public String calculateHash() {
String input = previousHash + Long.toString(timeStamp) + data;
return applySha256(input);
}
public static String applySha256(String input){
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = digest.digest(input.getBytes("UTF-8"));
StringBuilder hexString = new StringBuilder();
for (byte b : hashBytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
import java.util.ArrayList;
public class Blockchain {
public static ArrayList<Block> blockchain = new ArrayList<>();
public static void main(String[] args) {
blockchain.add(new Block("Genesis Block", "0"));
blockchain.add(new Block("Second Block", blockchain.get(0).hash));
blockchain.add(new Block("Third Block", blockchain.get(1).hash));
for (Block block : blockchain) {
System.out.println("Data: " + block.data);
System.out.println("Hash: " + block.hash);
System.out.println("Previous Hash: " + block.previousHash);
System.out.println("-----------------------");
}
System.out.println("Blockchain is valid: " + isChainValid());
}
public static boolean isChainValid() {
for (int i = 1; i < blockchain.size(); i++) {
Block current = blockchain.get(i);
Block previous = blockchain.get(i - 1);
if (!current.hash.equals(current.calculateHash())) return false;
if (!current.previousHash.equals(previous.hash)) return false;
}
return true;
}
}