author | František Kučera <franta-hg@frantovo.cz> |
Wed Jan 26 18:58:02 2011 +0100 (2011-01-26) | |
changeset 182 | bb8af29610c4 |
parent 123 | 9135d52e8b0a |
permissions | -rw-r--r-- |
franta-hg@52 | 1 |
package cz.frantovo.nekurak.util; |
franta-hg@52 | 2 |
|
franta-hg@52 | 3 |
import java.io.UnsupportedEncodingException; |
franta-hg@52 | 4 |
import java.security.MessageDigest; |
franta-hg@52 | 5 |
import java.security.NoSuchAlgorithmException; |
franta-hg@52 | 6 |
|
franta-hg@52 | 7 |
/** |
franta-hg@52 | 8 |
* Pomocná třída pro počítání hashů. |
franta-hg@52 | 9 |
* @author fiki |
franta-hg@52 | 10 |
*/ |
franta-hg@52 | 11 |
public class Hash { |
franta-hg@52 | 12 |
|
franta-hg@145 | 13 |
private static String algoritmus = "SHA-512"; |
franta-hg@145 | 14 |
private static String kodovani = "UTF-8"; |
franta-hg@52 | 15 |
|
franta-hg@145 | 16 |
private static String prevedNaHex(byte[] data) { |
franta-hg@145 | 17 |
StringBuilder vysledek = new StringBuilder(); |
franta-hg@145 | 18 |
for (int i = 0; i < data.length; i++) { |
franta-hg@145 | 19 |
int pulBajt = (data[i] >>> 4) & 0x0F; |
franta-hg@145 | 20 |
int dvePulky = 0; |
franta-hg@145 | 21 |
do { |
franta-hg@145 | 22 |
if ((0 <= pulBajt) && (pulBajt <= 9)) { |
franta-hg@145 | 23 |
vysledek.append((char) ('0' + pulBajt)); |
franta-hg@145 | 24 |
} else { |
franta-hg@145 | 25 |
vysledek.append((char) ('a' + (pulBajt - 10))); |
franta-hg@145 | 26 |
} |
franta-hg@145 | 27 |
pulBajt = data[i] & 0x0F; |
franta-hg@145 | 28 |
} while (dvePulky++ < 1); |
franta-hg@52 | 29 |
} |
franta-hg@145 | 30 |
return vysledek.toString(); |
franta-hg@52 | 31 |
} |
franta-hg@52 | 32 |
|
franta-hg@145 | 33 |
/** |
franta-hg@145 | 34 |
* @param text vstupní text |
franta-hg@145 | 35 |
* @return hashovaný text v HEX tvaru |
franta-hg@145 | 36 |
* @throws NoSuchAlgorithmException neexistující hashovací algoritmus |
franta-hg@145 | 37 |
* @throws UnsupportedEncodingException nepodporované kódování znaků |
franta-hg@145 | 38 |
* @throws NullPointerException pokud je vstup null |
franta-hg@145 | 39 |
*/ |
franta-hg@145 | 40 |
public static String hashuj(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { |
franta-hg@145 | 41 |
MessageDigest md; |
franta-hg@145 | 42 |
md = MessageDigest.getInstance(algoritmus); |
franta-hg@145 | 43 |
byte[] hash = new byte[40]; |
franta-hg@145 | 44 |
md.update(text.getBytes(kodovani), 0, text.length()); |
franta-hg@145 | 45 |
hash = md.digest(); |
franta-hg@145 | 46 |
return prevedNaHex(hash); |
franta-hg@145 | 47 |
} |
franta-hg@52 | 48 |
} |