Monday, April 22, 2013

Convert string to sha1 using java

<?php
public static String hash(String toHash) {
    if (toHash == null || toHash.equals(""))
        return null;
    
    StringBuffer hexString = new StringBuffer();
    
    try {
        java.io.StringReader sr =  new java.io.StringReader(toHash);
        java.io.ByteArrayOutputStream baos =  new java.io.ByteArrayOutputStream();
        int ch;

        while ((ch = sr.read()) != -1) {
            baos.write(ch);
        }

         //SHA-1 Hash value of data 
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        sha.reset();
        sha.update(baos.toByteArray());

        byte[] digest = sha.digest();

        /*  NB: This conversion strips the leading 0 from any 
         *  digest byte with a value less than 16.
         *  
         *  This weakens the security of the SHA-1 hash and requires
         *  workarounds on the server to overcome this.
         *  
         *  It's all quite embarrassing. -- PB
         */
        for (int i=0;i<digest.length;i++) {
            hexString.append(Integer.toHexString(0xFF & digest[i]).toUpperCase());
        }
    } catch (java.io.IOException ioE) {
        System.out.println(ioE);
    } catch (NoSuchAlgorithmException algE) {
        System.out.println(algE);
    }
    
    return hexString.toString();
}
?>

No comments:

Post a Comment