CriptoUtil.java
2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package br.gov.mc.cadsei.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public final class CriptoUtil {
private static final String hexDigits = "0123456789abcdef";
/**
* Realiza um digest em um array de bytes através do algoritmo especificado
* @param input - O array de bytes a ser criptografado
* @param algoritmo - O algoritmo a ser utilizado
* @return byte[] - O resultado da criptografia
* @throws NoSuchAlgorithmException - Caso o algoritmo fornecido não seja
* válido
*/
private static byte[] digest(byte[] input, String algoritmo)
throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(algoritmo);
md.reset();
return md.digest(input);
}
/**
* Converte o array de bytes em uma representação hexadecimal.
* @param input - O array de bytes a ser convertido.
* @return Uma String com a representação hexa do array
*/
private static String byteArrayToHexString(byte[] b) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < b.length; i++) {
int j = ((int) b[i]) & 0xFF;
buf.append(hexDigits.charAt(j / 16));
buf.append(hexDigits.charAt(j % 16));
}
return buf.toString();
}
/**
* Converte uma String hexa no array de bytes correspondente.
* @param hexa - A String hexa
* @return O vetor de bytes
* @throws IllegalArgumentException - Caso a String não sej auma
* representação haxadecimal válida
*/
@SuppressWarnings("unused")
private static byte[] hexStringToByteArray(String hexa)
throws IllegalArgumentException {
//verifica se a String possui uma quantidade par de elementos
if (hexa.length() % 2 != 0) {
throw new IllegalArgumentException("String hexa inválida");
}
byte[] b = new byte[hexa.length() / 2];
for (int i = 0; i < hexa.length(); i+=2) {
b[i / 2] = (byte) ((hexDigits.indexOf(hexa.charAt(i)) << 4) |
(hexDigits.indexOf(hexa.charAt(i + 1))));
}
return b;
}
public static String getCriptografia(String palavra){
String resultado = null;
try{
byte[] input = palavra.getBytes();
byte[] b = digest(input, "md5");
return CriptoUtil.byteArrayToHexString(b);
}catch(Exception e){
System.out.println(e.toString());
}
return resultado;
}
public static void main(String[] args) throws NoSuchAlgorithmException {
System.out.println( CriptoUtil.byteArrayToHexString(CriptoUtil.digest(
"c508a02b4b3ff383f8d8dea0e1e5596d".getBytes(), "md5")));
}
}