java/nekurak.net-lib/src/cz/frantovo/nekurak/util/Hash.java
author František Kučera <franta-hg@frantovo.cz>
Sun Jun 20 14:46:47 2010 +0200 (2010-06-20)
changeset 145 0efefbf5f8b6
parent 123 9135d52e8b0a
permissions -rw-r--r--
Formátování kódu, důsledné používání tabulátorů, drobné úpravy, StringBuilder
     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 		StringBuilder vysledek = new StringBuilder();
    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 }