1package eu.siacs.conversations.utils;
2
3import java.security.SecureRandom;
4import java.text.Normalizer;
5
6public class CryptoHelper {
7 public static final String FILETRANSFER = "?FILETRANSFERv1:";
8 final protected static char[] hexArray = "0123456789abcdef".toCharArray();
9 final protected static char[] vowels = "aeiou".toCharArray();
10 final protected static char[] consonants = "bcdfghjklmnpqrstvwxyz".toCharArray();
11 final public static byte[] ONE = new byte[] { 0, 0, 0, 1 };
12
13 public static String bytesToHex(byte[] bytes) {
14 char[] hexChars = new char[bytes.length * 2];
15 for (int j = 0; j < bytes.length; j++) {
16 int v = bytes[j] & 0xFF;
17 hexChars[j * 2] = hexArray[v >>> 4];
18 hexChars[j * 2 + 1] = hexArray[v & 0x0F];
19 }
20 return new String(hexChars);
21 }
22
23 public static byte[] hexToBytes(String hexString) {
24 int len = hexString.length();
25 byte[] array = new byte[len / 2];
26 for (int i = 0; i < len; i += 2) {
27 array[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
28 .digit(hexString.charAt(i + 1), 16));
29 }
30 return array;
31 }
32
33 public static byte[] concatenateByteArrays(byte[] a, byte[] b) {
34 byte[] result = new byte[a.length + b.length];
35 System.arraycopy(a, 0, result, 0, a.length);
36 System.arraycopy(b, 0, result, a.length, b.length);
37 return result;
38 }
39
40 public static String randomMucName(SecureRandom random) {
41 return randomWord(3, random) + "." + randomWord(7, random);
42 }
43
44 protected static String randomWord(int lenght, SecureRandom random) {
45 StringBuilder builder = new StringBuilder(lenght);
46 for (int i = 0; i < lenght; ++i) {
47 if (i % 2 == 0) {
48 builder.append(consonants[random.nextInt(consonants.length)]);
49 } else {
50 builder.append(vowels[random.nextInt(vowels.length)]);
51 }
52 }
53 return builder.toString();
54 }
55
56 /**
57 * Escapes usernames or passwords for SASL.
58 */
59 public static String saslEscape(final String s) {
60 final StringBuilder sb = new StringBuilder((int) (s.length() * 1.1));
61 for (int i = 0; i < s.length(); i++) {
62 char c = s.charAt(i);
63 switch (c) {
64 case ',':
65 sb.append("=2C");
66 break;
67 case '=':
68 sb.append("=3D");
69 break;
70 default:
71 sb.append(c);
72 break;
73 }
74 }
75 return sb.toString();
76 }
77
78 public static String saslPrep(final String s) {
79 return saslEscape(Normalizer.normalize(s, Normalizer.Form.NFKC));
80 }
81}