java/nekurak.net-lib/src/cz/frantovo/nekurak/util/Hash.java
author František Kučera <franta-hg@frantovo.cz>
Tue May 25 13:54:21 2010 +0200 (2010-05-25)
changeset 123 9135d52e8b0a
parent 53 d76be0124c40
child 145 0efefbf5f8b6
permissions -rw-r--r--
Test hashovací funkce + test češtiny v identifikátorech
Java Language Specification – 3.8 Identifiers:
http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#40625
     1 package cz.frantovo.nekurak.util;
     2 
     3 import java.io.UnsupportedEncodingException;
     4 import java.security.MessageDigest;
     5 import java.security.NoSuchAlgorithmException;
     6 
     7 /**
     8  * Pomocná třída pro počítání hashů.
     9  * @author fiki
    10  */
    11 public class Hash {
    12 
    13     private static String algoritmus = "SHA-512";
    14     private static String kodovani = "UTF-8";
    15 
    16     private static String prevedNaHex(byte[] data) {
    17 	StringBuffer vysledek = new StringBuffer();
    18 	for (int i = 0; i < data.length; i++) {
    19 	    int pulBajt = (data[i] >>> 4) & 0x0F;
    20 	    int dvePulky = 0;
    21 	    do {
    22 		if ((0 <= pulBajt) && (pulBajt <= 9)) {
    23 		    vysledek.append((char) ('0' + pulBajt));
    24 		} else {
    25 		    vysledek.append((char) ('a' + (pulBajt - 10)));
    26 		}
    27 		pulBajt = data[i] & 0x0F;
    28 	    } while (dvePulky++ < 1);
    29 	}
    30 	return vysledek.toString();
    31     }
    32 
    33     /**
    34      * @param text vstupní text
    35      * @return hashovaný text v HEX tvaru
    36      * @throws NoSuchAlgorithmException neexistující hashovací algoritmus
    37      * @throws UnsupportedEncodingException nepodporované kódování znaků
    38      * @throws NullPointerException pokud je vstup null
    39      */
    40     public static String hashuj(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    41 	MessageDigest md;
    42 	md = MessageDigest.getInstance(algoritmus);
    43 	byte[] hash = new byte[40];
    44 	md.update(text.getBytes(kodovani), 0, text.length());
    45 	hash = md.digest();
    46 	return prevedNaHex(hash);
    47     }
    48 }