java/nekurak.net-lib/src/cz/frantovo/nekurak/util/Hash.java
author František Kučera <franta-hg@frantovo.cz>
Thu Mar 04 22:42:23 2010 +0100 (2010-03-04)
changeset 53 d76be0124c40
parent 52 4c0408690ebf
child 123 9135d52e8b0a
permissions -rw-r--r--
Kontrola hesla, překlady, grafika, drobnosti.
     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      */
    39     public static String hashuj(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    40 	MessageDigest md;
    41 	md = MessageDigest.getInstance(algoritmus);
    42 	byte[] hash = new byte[40];
    43 	md.update(text.getBytes(kodovani), 0, text.length());
    44 	hash = md.digest();
    45 	return prevedNaHex(hash);
    46     }
    47 }