CryptoHelper.java

 1package eu.siacs.conversations.utils;
 2
 3import java.security.SecureRandom;
 4import java.util.Random;
 5
 6import android.util.Base64;
 7
 8public class CryptoHelper {
 9	final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
10	final protected static char[] vowels = "aeiou".toCharArray();
11	final protected static char[] consonants ="bcdfghjklmnpqrstvwxyz".toCharArray();
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	public static String saslPlain(String username, String password) {
22		byte[] userBytes = username.getBytes();
23		int userLenght = userBytes.length;
24		byte[] passwordBytes = password.getBytes();
25		byte[] saslBytes = new byte[userBytes.length+passwordBytes.length+2];
26		saslBytes[0] = 0x0;
27		for(int i = 1; i < saslBytes.length; ++i) {
28			if (i<=userLenght) {
29				saslBytes[i] = userBytes[i-1];
30			} else if (i==userLenght+1) {
31				saslBytes[i] = 0x0;
32			} else {
33				saslBytes[i] = passwordBytes[i-(userLenght+2)];
34			}
35		}
36		
37		return Base64.encodeToString(saslBytes, Base64.DEFAULT);
38	}
39	
40	public static String randomMucName() {
41		Random random = new SecureRandom();
42		return randomWord(3,random)+"."+randomWord(7,random);
43	}
44	
45	protected static String randomWord(int lenght,Random random) {
46		StringBuilder builder = new StringBuilder(lenght);
47		for(int i = 0; i < lenght; ++i) {
48			if (i % 2 == 0) {
49				builder.append(consonants[random.nextInt(consonants.length)]);
50			} else {
51				builder.append(vowels[random.nextInt(vowels.length)]);
52			}
53		}
54		return builder.toString();
55	}
56}