author | František Kučera <franta-hg@frantovo.cz> |
Tue, 23 Mar 2010 15:09:19 +0100 | |
changeset 83 | 6767606d6342 |
parent 53 | d76be0124c40 |
child 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@53 | 13 |
private static String algoritmus = "SHA-512"; |
franta-hg@52 | 14 |
private static String kodovani = "UTF-8"; |
franta-hg@52 | 15 |
|
franta-hg@52 | 16 |
private static String prevedNaHex(byte[] data) { |
franta-hg@52 | 17 |
StringBuffer vysledek = new StringBuffer(); |
franta-hg@52 | 18 |
for (int i = 0; i < data.length; i++) { |
franta-hg@52 | 19 |
int pulBajt = (data[i] >>> 4) & 0x0F; |
franta-hg@52 | 20 |
int dvePulky = 0; |
franta-hg@52 | 21 |
do { |
franta-hg@52 | 22 |
if ((0 <= pulBajt) && (pulBajt <= 9)) { |
franta-hg@52 | 23 |
vysledek.append((char) ('0' + pulBajt)); |
franta-hg@52 | 24 |
} else { |
franta-hg@52 | 25 |
vysledek.append((char) ('a' + (pulBajt - 10))); |
franta-hg@52 | 26 |
} |
franta-hg@52 | 27 |
pulBajt = data[i] & 0x0F; |
franta-hg@52 | 28 |
} while (dvePulky++ < 1); |
franta-hg@52 | 29 |
} |
franta-hg@52 | 30 |
return vysledek.toString(); |
franta-hg@52 | 31 |
} |
franta-hg@52 | 32 |
|
franta-hg@52 | 33 |
/** |
franta-hg@52 | 34 |
* @param text vstupní text |
franta-hg@52 | 35 |
* @return hashovaný text v HEX tvaru |
franta-hg@52 | 36 |
* @throws NoSuchAlgorithmException neexistující hashovací algoritmus |
franta-hg@52 | 37 |
* @throws UnsupportedEncodingException nepodporované kódování znaků |
franta-hg@52 | 38 |
*/ |
franta-hg@52 | 39 |
public static String hashuj(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { |
franta-hg@52 | 40 |
MessageDigest md; |
franta-hg@52 | 41 |
md = MessageDigest.getInstance(algoritmus); |
franta-hg@52 | 42 |
byte[] hash = new byte[40]; |
franta-hg@52 | 43 |
md.update(text.getBytes(kodovani), 0, text.length()); |
franta-hg@52 | 44 |
hash = md.digest(); |
franta-hg@52 | 45 |
return prevedNaHex(hash); |
franta-hg@52 | 46 |
} |
franta-hg@52 | 47 |
} |