1 package fr.ifremer.quadrige3.core.security;
2
3 /*-
4 * #%L
5 * Quadrige3 Core :: Quadrige3 Client Core
6 * $Id:$
7 * $HeadURL:$
8 * %%
9 * Copyright (C) 2017 Ifremer
10 * %%
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Affero General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU Affero General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 * #L%
24 */
25
26
27 import java.io.ByteArrayOutputStream;
28 import java.security.MessageDigest;
29 import java.security.NoSuchAlgorithmException;
30 import java.util.StringTokenizer;
31
32 /**
33 * <p>Encryption class.</p>
34 *
35 * @author Ludovic Pecquot <ludovic.pecquot@e-is.pro>
36 */
37 public class Encryption {
38
39 private static String getString(byte[] bytes) {
40 StringBuilder sb = new StringBuilder();
41 for (int i = 0; i < bytes.length; i++) {
42 byte b = bytes[i];
43 sb.append(0x00FF & b);
44 if (i + 1 < bytes.length) {
45 sb.append("-"); //$NON-NLS-1$
46 }
47 }
48 return sb.toString();
49 }
50
51 private static byte[] getBytes(String str) {
52 ByteArrayOutputStream bos = new ByteArrayOutputStream();
53 StringTokenizer st = new StringTokenizer(str, "-", false); //$NON-NLS-1$
54 while (st.hasMoreTokens()) {
55 int i = Integer.parseInt(st.nextToken());
56 bos.write((byte) i);
57 }
58 return bos.toByteArray();
59 }
60
61 /**
62 * <p>md5.</p>
63 *
64 * @param source a {@link String} object.
65 * @return a {@link String} object.
66 */
67 public static String md5(String source) {
68 try {
69 MessageDigest md = MessageDigest.getInstance("MD5"); //$NON-NLS-1$
70 byte[] bytes = md.digest(source.getBytes());
71 return getString(bytes);
72 } catch (NoSuchAlgorithmException e) {
73 e.printStackTrace();
74 return null;
75 }
76 }
77
78 /**
79 * <p>sha.</p>
80 *
81 * @param source a {@link String} object.
82 * @return a {@link String} object.
83 */
84 public static String sha(String source) {
85 try {
86 MessageDigest md = MessageDigest.getInstance("SHA"); //$NON-NLS-1$
87 byte[] bytes = md.digest(source.getBytes());
88 return getString(bytes);
89 } catch (NoSuchAlgorithmException e) {
90 e.printStackTrace();
91 return null;
92 }
93 }
94 }