Monday, 29 April 2019

MessageDigest.getInstance("SHA") is the same as MessageDigest.getInstance("SHA-1")

"SHA-1" is not recommended to be used to hash passwords, by the way. More advanced SHA algorithms such as 'SHA-256' should be used instead

import java.security.MessageDigest;

public final class PasswordHasher {
    
    private PasswordHasher() {
        throw new IllegalStateException("Utility class");
    }
    
    public static String hash(String plainPassword, String passwordSalt) {
        return hash("SHA", plainPassword, passwordSalt);
    }
    
    public static String hash(String algorithm, String plainPassword, String passwordSalt) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm) ;
            md.update(passwordSalt.getBytes()) ; 
            md.update(plainPassword.getBytes()) ;
            byte[] digest = md.digest() ;
            StringBuilder sb = new StringBuilder(500) ;
            for (int i=0;i<digest.length;i++) {
                sb.append(Integer.toHexString((digest[i]&0xFF) | 0x100).substring(1,3)) ;
            }
            return sb.toString() ;
        }catch(Exception e) {
            throw new IllegalArgumentException("Error occurred when hashing password ", e);
        }
    }
}

import static org.junit.Assert.*;

import org.junit.Test;

public class PasswordHasherTest {

    @Test
    public void hash() {
        String plainPassword = "password";
        String salt = "salty19143";
        assertEquals("0dd9e6d58f5316e828c352af8876143a61b291fc", PasswordHasher.hash(plainPassword, salt));
        plainPassword = "random123";
        assertEquals(PasswordHasher.hash("SHA-1", plainPassword, salt), PasswordHasher.hash(plainPassword, salt));
    }

}

Tuesday, 20 June 2017

Javascript: What does 'return false;' do in event handler?

Bootstrap dropdown menu HTML

 <ul class="dropdown-menu">  
   <li><a href="#" id="edit">Edit</a></li>  
   <li><a href="#" id="delete">Delete</a></li>  
 </ul>  

jQuery code

 $("#delete").click(function (event) {  
   console.log("clicked");  
   return false;  
 });  

With 'return false;', double clicking the link prints out 'clicked' twice

 $("#delete").click(function (event) {  
   console.log("clicked");  
 });  

Without' return false;',  double clicking the link prints out 'clicked' once

Turns out what 'return false' does is event.preventDefault() and event.stopPropagation(). When the propagation is stopped, the bootstrap javascript code, which hides the dropdown menu, doesn't have a chance to be executed.

To see the difference, we can compare the effect when single clicking the link. Without 'return false;' the dropdown menu disappears. With return false; the dropdown menu still lingers.

The lesson is always use event.preventDefault() as opposed to return false; for event handing. The above code is best written as

 $("#delete").click(function (event) {  
   event.preventDefault();  
   console.log("clicked");  
 });  

Monday, 5 December 2016

Javascript: prototype and construct

Equation 1: Object.prototype.[[prototype]] == null
Equation 2: Function.prototype.[[prototype]] === Object.prototype
Equation 3: Func.[[prototype]] == Function.prototype
Equation 4: Object.create(Obj).[[prototype]] = Obj
Equation 5: obj.[[prototype]] === obj.constructor.prototype
Equation 6: Object.prototype.prototype == undefined
Equation 7: Func.constructor === Function
Equation 8: Func.prototype.constructor === Func
Rule 1: When a property cannot be found on an obj, consult obj.[[prototype]], if still not found, consult obj.[[prototype]].[[prototype]] until reaching the end of chain (null)


I sorted these equations in the hope to explain the 'myths' around the prototype, constructor, and [[prototype]] (aka __proto__)

Let's see.

 

Exercise 1

Prove:
var obj = {};
Console.log(obj.prototype === undefined)

Solution:

obj doesn't have the property prototype on its own, it needs to consult obj.[[prototype]]. //Rule 1

obj.[[prototype]] === obj.constructor.prototype  //Equation 5
obj.constructor === Object //WHY?
obj.[[prototypte]] === Object.prototype

Object.prototype is the end of the chain because Object.prototype.[[prototype]] === null; //Equation 1

obj.prototype === obj.[[prototypte]].prototype === Object.prototype.prototype === undefined //Equation 6

 

Exercise 2

Prove:
var obj = new Object(2);
Console.log(obj.prototype === undefined);

Solution:

obj.[[prototype]] === obj.constructor.prototype  //Equation 5
obj.constructor === Number //WHY?
obj.[[prototype]] === Number.prototype

Number.prototype also doesn't have property prototype on its own, it needs to consult Number.prototype.[[prototype]] //Rule 1

Number.prototype.[[prototype]] === Object.prototype //Equation 2

obj.prototype === Number.prototype.[[prototype]].prototype === Object.prototype.prototype === undefined //Equation 6

Exercise 3

Prove:
var obj = Object.create(Object);
Console.log(obj.prototype === Object.prototype);

Solution:
obj.[[prototype]] === Object; //Equation 4
obj.prototype === obj.[[prototype]].prototype = Object.prototype //Rule 1

 

Exercise 4

Prove:
Console.log (Object.getPrototypeOf(Object) === Function.prototype); //true

Solution:
Object.[[prototype]] ===  Function.prototype; //Equation 3

Exercise 5

Prove:

var obj = new Function();
Console.log(Object.getPrototype(obj) === Function.prototype);

Solution:
typeof 'new Function()' is also a function!

obj.[[prototype]] === Function.prototype; //Equation 3


Note: Those lines with //WHY are the ones that I am unable to account for. Strictly speaking, new Object(2) doesn't even have a constructor property on its own. There are some circular arguments around equation 5. For now, I just tell the object's constructor by looking at its definition --- new Object(2) is a Number, "123" is also a Number, "ABC" is a String, etc. The ones that I cannot tell are Objects.This assumption could be deeply flawed. Will find out..

Friday, 25 November 2016

Javascript: every, some, arrow function

Array.every() returns true when all the items meet certain condition

var nums = [5,7,10,17,20];
var nums2 = [11,17,20,23];

var allBig = nums.every(function(element){
    return element > 10;
});

console.log(allBig); //false

//ES6 arrow function
allBig = nums.every(element => element > 10);

console.log(allBig); //false

allBig = nums2.every(function(element){
    return element > 10;
});

console.log(allBig); //true

//ES6 arrow function
allBig = nums2.every(element => element > 10);

console.log(allBig); //true

Array.some() returns true when any item meets certain condition.
var nums = [5,7,10,17,20];
var nums2 = [11,17,20,23];

var allBig = nums.some(function(element){
    return element > 10;
});

console.log(allBig); //true

//ES6 arrow function
allBig = nums.some(element => element > 10);

console.log(allBig); //true

allBig = nums2.some(function(element){
    return element > 30;
});

console.log(allBig); //false

//ES6 arrow function
allBig = nums2.some(element => element > 30);

console.log(allBig); //false

Thursday, 24 November 2016

Effective Java Item 35. Write own annotation and reflection

 //Almost always RUNTIME  
 @Retention(RetentionPolicy.RUNTIME)  
 @Target({ElementType.TYPE, ElementType.METHOD})  
 @interface MyTest {}  
 class Sample{  
   @MyTest  
   public static void m1(){}  
 }  
 public class MyAnnotation{  
   public static void main(String[] args){  
     Class testClass = Sample.class;  
     //Get all methods including private, protected  
     //as opposed to testClass.getMethods() only returning public methods  
     for (Method m : testClass.getDeclaredMethods()){  
       if (m.isAnnotationPresent(MyTest.class)){  
         try{  
           m.invoke(null); //Call static method  
         } catch (InvocationTargetException e) {  
           e.printStackTrace();  
         } catch (Exception e) {  
           e.printStackTrace();  
         }  
       }  
     }  
   }  
 }  

Javascript: check undefined/null

If you are sure the variable has been declared (i.e var a;), simply use
if (a != null){
    ...
}
If a can be undeclared, then use


if (typeof a != 'undefined' && a != null){
    ...
}

Javascript: softbind

Excerpted from You Don't Know JS: this & Object Prototypes

I couldn't fully understand the code below.
  
if (!Function.prototype.softBind) {
    Function.prototype.softBind = function(obj) {
        var fn = this,
            curried = [].slice.call( arguments, 1 ),
            bound = function bound() {
                return fn.apply(
                    (!this ||
                        (typeof window !== "undefined" &&
                            this === window) ||
                        (typeof global !== "undefined" &&
                            this === global)
                    ) ? obj : this,
                    curried.concat.apply( curried, arguments )
                );
            };
        bound.prototype = Object.create( fn.prototype );
        return bound;
    };
}

function foo() {
   console.log("name: " + this.name);
}

var obj = { name: "obj" },
    obj2 = { name: "obj2" },
    obj3 = { name: "obj3" };

var fooOBJ = foo.softBind( obj );

fooOBJ(); // name: obj

obj2.foo = foo.softBind(obj);
obj2.foo(); // name: obj2   <---- look!!!

fooOBJ.call( obj3 ); // name: obj3   <---- look!

setTimeout( obj2.foo, 10 ); // name: obj   <---- falls back to soft-binding
  1. What does [].slice.call(...) do? 
  2. Are the two 'this' referring to the same thing? 
  3. What does bound.prototype = Object.create(fn.prototype) do?
Let's go through the code step by step by inserting some console output code. And for the sake of demonstrating the purpose of curried, I also rewrote the foo() function.
if (!Function.prototype.softBind) {
    Function.prototype.softBind = function(obj) {
        var fn = this;
        console.log("Outer this = "+ fn);
        var curried = [].slice.call( arguments, 1 );
        console.log("Outer curry = "+curried);
        var bound = function bound() {
            console.log("Inner this = " + this);
            console.log("Inner curry = "+curried.concat.apply( curried, arguments ));
            return fn.apply(
                (!this ||
                    (typeof window !== "undefined" &&
                        this === window) ||
                    (typeof global !== "undefined" &&
                         this === global)
                ) ? obj : this,
                curried.concat.apply( curried, arguments )
            );
        };
        bound.prototype = Object.create( fn.prototype );
        console.log("return bound");
        return bound;
    };
}

function foo(a1, a2) {
   console.log(a1 + ' ' +a2 + " name: " + this.name);
}

var obj = { name: "obj" },
    obj2 = { name: "obj2" },
    obj3 = { name: "obj3" };

var fooOBJ = foo.softBind( obj, 'A1');
fooOBJ('A2'); // name: obj

//obj2.foo = foo.softBind(obj, 'A1');
//obj2.foo('A2'); // name: obj2   <---- look!!!

//fooOBJ.call( obj3 ); // name: obj3   <---- look!
Here is the output.
Outer this = function foo(a1, a2) {
   console.log(a1 + ' ' +a2 + " name: " + this.name);
}
Outer curry = A
return bound
Inner this = [object Object]
Inner curry = A,A2
A A2 name: obj2

[].slice.call(arguments, 1)
is semantically equal to
arguments.slice(1)
except the latter is syntactically incorrect because the variable arguments is not a real array. It's an 'array-like' object.

The outer this refers to the foo function while the inner this refers to the window (global) variable. It's worth noting that by the time foo.softBind(obj) completes execution, the bound() function hasn't been invoked. It's only invoked when the line fooOBJ('A2') is executed.

bound.prototype = Object.create( fn.prototype );
copies all the properties of foo to bound, essentially ensuring that after softbind the function foo doesn't lose any properties.