CryptoHelper.java

 1package eu.siacs.conversations.utils;
 2
 3import java.security.SecureRandom;
 4
 5public class CryptoHelper {
 6	public static final String FILETRANSFER = "?FILETRANSFERv1:";
 7	final protected static char[] hexArray = "0123456789abcdef".toCharArray();
 8	final protected static char[] vowels = "aeiou".toCharArray();
 9	final protected static char[] consonants = "bcdfghjklmnpqrstvwxyz"
10			.toCharArray();
11
12	public static String bytesToHex(byte[] bytes) {
13		char[] hexChars = new char[bytes.length * 2];
14		for (int j = 0; j < bytes.length; j++) {
15			int v = bytes[j] & 0xFF;
16			hexChars[j * 2] = hexArray[v >>> 4];
17			hexChars[j * 2 + 1] = hexArray[v & 0x0F];
18		}
19		return new String(hexChars);
20	}
21
22	public static byte[] hexToBytes(String hexString) {
23		int len = hexString.length();
24		byte[] array = new byte[len / 2];
25		for (int i = 0; i < len; i += 2) {
26			array[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
27					.digit(hexString.charAt(i + 1), 16));
28		}
29		return array;
30	}
31
32	public static byte[] concatenateByteArrays(byte[] a, byte[] b) {
33		byte[] result = new byte[a.length + b.length];
34		System.arraycopy(a, 0, result, 0, a.length);
35		System.arraycopy(b, 0, result, a.length, b.length);
36		return result;
37	}
38
39	public static String randomMucName(SecureRandom random) {
40		return randomWord(3, random) + "." + randomWord(7, random);
41	}
42
43	protected static String randomWord(int lenght, SecureRandom random) {
44		StringBuilder builder = new StringBuilder(lenght);
45		for (int i = 0; i < lenght; ++i) {
46			if (i % 2 == 0) {
47				builder.append(consonants[random.nextInt(consonants.length)]);
48			} else {
49				builder.append(vowels[random.nextInt(vowels.length)]);
50			}
51		}
52		return builder.toString();
53	}
54}