Skip to content

Instantly share code, notes, and snippets.

@dflima
Created December 5, 2018 15:43
Show Gist options
  • Save dflima/d867002c50b7758199c203339421ff34 to your computer and use it in GitHub Desktop.
Save dflima/d867002c50b7758199c203339421ff34 to your computer and use it in GitHub Desktop.
Blockchain implementation in Java
import java.util.Date;
public class Block {
public String hash;
public String previousHash;
private 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 calculatedHash = StringUtil.applySha256(
previousHash +
Long.toString(timestamp) +
data
);
return calculatedHash;
}
}
public class NoobChain {
public static void main(String[] args) {
Block genesisBlock = new Block("Hi I'm the first block", "0");
System.out.println("Hash for block 1: " + genesisBlock.hash);
Block secondBlock = new Block("Yo I'm the second block", genesisBlock.hash);
System.out.println("Hash for block 2: " + secondBlock.hash);
Block thirdBlock = new Block("Hey I'm the third block", secondBlock.hash);
System.out.println("Hash for block 3: " + thirdBlock.hash);
}
}
import java.security.MessageDigest;
public class StringUtil {
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);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment