Skip to main content

Posts

MD5 Hashing in Java

This is useful for storing passwords in a database though still vulnerable to md5 dictionary attacks, anyway, here’s a static method. public static String hash(String text) { String hashedString = ""; try { MessageDigest md5Hash = MessageDigest.getInstance("MD5"); md5Hash.update(text.getBytes(), 0, text.length()); hashedString = new BigInteger(1, md5Hash.digest()).toString(16); } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } return hashedString; } This will return the MD5 hash. Have a great day!

Static Methods and Variables in Java

Static methods and variables are shared by all instances of the class. Static variables are initialized when a class is loaded whereas instance variables are initialized when an instance of the class is created. Static methods belong to a class, therefore, it can only access static members of the class and it can be called before instantiating the class. class StaticCase { static int staticCounter = 0; int nonStaticCounter = 0; StaticCase() { staticCounter++; //class level nonStaticCounter++; //instance level } } class StaticCaseImpl { //static method, entry point public static void main(String... args) { //StaticCase.nonStaticCounter, error, not a static variable StaticCase sc1 = new StaticCase(); StaticCase sc2 = new StaticCase(); System.out.println("staticCounter sc1: " + sc1.staticCounter); //output is staticCounter sc1: 2 //or in static context, StaticCase.staticCounter System.out.println("nonSta...