Grundaufbau der App
[DHBWCampusApp.git] / app / src / main / java / de / dhbwloe / campusapp / Tools.java
1 package de.dhbwloe.campusapp;
2
3 import java.security.MessageDigest;
4 import java.security.NoSuchAlgorithmException;
5
6 import javax.crypto.Cipher;
7 import javax.crypto.spec.SecretKeySpec;
8
9 /**
10  * Created by pk910 on 25.01.2016.
11  */
12 public class Tools {
13
14     public static final String md5(final String s) {
15         final String MD5 = "MD5";
16         try {
17             // Create MD5 Hash
18             MessageDigest digest = java.security.MessageDigest.getInstance(MD5);
19             digest.update(s.getBytes());
20             byte messageDigest[] = digest.digest();
21
22             // Create Hex String
23             StringBuilder hexString = new StringBuilder();
24             for (byte aMessageDigest : messageDigest) {
25                 String h = Integer.toHexString(0xFF & aMessageDigest);
26                 while (h.length() < 2)
27                     h = "0" + h;
28                 hexString.append(h);
29             }
30             return hexString.toString();
31
32         } catch (NoSuchAlgorithmException e) {
33             e.printStackTrace();
34         }
35         return "";
36     }
37
38     public static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
39         SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
40         Cipher cipher = Cipher.getInstance("AES");
41         cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
42         byte[] encrypted = cipher.doFinal(clear);
43         return encrypted;
44     }
45
46     public static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
47         SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
48         Cipher cipher = Cipher.getInstance("AES");
49         cipher.init(Cipher.DECRYPT_MODE, skeySpec);
50         byte[] decrypted = cipher.doFinal(encrypted);
51         return decrypted;
52     }
53
54 }