CryptoHelper.java

  1package eu.siacs.conversations.utils;
  2
  3import android.os.Bundle;
  4import android.util.Base64;
  5import android.util.Pair;
  6
  7import org.bouncycastle.asn1.x500.X500Name;
  8import org.bouncycastle.asn1.x500.style.BCStyle;
  9import org.bouncycastle.asn1.x500.style.IETFUtils;
 10import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
 11
 12import java.net.MalformedURLException;
 13import java.net.URL;
 14import java.security.MessageDigest;
 15import java.security.NoSuchAlgorithmException;
 16import java.security.SecureRandom;
 17import java.security.cert.CertificateEncodingException;
 18import java.security.cert.CertificateParsingException;
 19import java.security.cert.X509Certificate;
 20import java.text.Normalizer;
 21import java.util.ArrayList;
 22import java.util.Arrays;
 23import java.util.Collection;
 24import java.util.Iterator;
 25import java.util.LinkedHashSet;
 26import java.util.List;
 27import java.util.Locale;
 28import java.util.regex.Pattern;
 29
 30import eu.siacs.conversations.Config;
 31import eu.siacs.conversations.R;
 32import eu.siacs.conversations.entities.Account;
 33import eu.siacs.conversations.entities.Message;
 34import eu.siacs.conversations.http.AesGcmURLStreamHandler;
 35import rocks.xmpp.addr.Jid;
 36
 37public final class CryptoHelper {
 38
 39	private static final char[] VOWELS = "aeiou".toCharArray();
 40	private static final char[] CONSONANTS = "bcfghjklmnpqrstvwxyz".toCharArray();
 41
 42	private final static char[] hexArray = "0123456789abcdef".toCharArray();
 43
 44	public static final Pattern UUID_PATTERN = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}");
 45	final public static byte[] ONE = new byte[] { 0, 0, 0, 1 };
 46
 47	public static String bytesToHex(byte[] bytes) {
 48		char[] hexChars = new char[bytes.length * 2];
 49		for (int j = 0; j < bytes.length; j++) {
 50			int v = bytes[j] & 0xFF;
 51			hexChars[j * 2] = hexArray[v >>> 4];
 52			hexChars[j * 2 + 1] = hexArray[v & 0x0F];
 53		}
 54		return new String(hexChars);
 55	}
 56
 57	public static String pronounceable(SecureRandom random) {
 58		char[] output = new char[random.nextInt(4) * 2 + 5];
 59		boolean vowel = random.nextBoolean();
 60		for(int i = 0; i < output.length; ++i) {
 61			output[i] = vowel ? VOWELS[random.nextInt(VOWELS.length)] : CONSONANTS[random.nextInt(CONSONANTS.length)];
 62			vowel = !vowel;
 63		}
 64		return String.valueOf(output);
 65	}
 66
 67	public static byte[] hexToBytes(String hexString) {
 68		int len = hexString.length();
 69		byte[] array = new byte[len / 2];
 70		for (int i = 0; i < len; i += 2) {
 71			array[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
 72					.digit(hexString.charAt(i + 1), 16));
 73		}
 74		return array;
 75	}
 76
 77	public static String hexToString(final String hexString) {
 78		return new String(hexToBytes(hexString));
 79	}
 80
 81	public static byte[] concatenateByteArrays(byte[] a, byte[] b) {
 82		byte[] result = new byte[a.length + b.length];
 83		System.arraycopy(a, 0, result, 0, a.length);
 84		System.arraycopy(b, 0, result, a.length, b.length);
 85		return result;
 86	}
 87
 88	/**
 89	 * Escapes usernames or passwords for SASL.
 90	 */
 91	public static String saslEscape(final String s) {
 92		final StringBuilder sb = new StringBuilder((int) (s.length() * 1.1));
 93		for (int i = 0; i < s.length(); i++) {
 94			char c = s.charAt(i);
 95			switch (c) {
 96				case ',':
 97					sb.append("=2C");
 98					break;
 99				case '=':
100					sb.append("=3D");
101					break;
102				default:
103					sb.append(c);
104					break;
105			}
106		}
107		return sb.toString();
108	}
109
110	public static String saslPrep(final String s) {
111		return Normalizer.normalize(s, Normalizer.Form.NFKC);
112	}
113
114	public static String random(int length, SecureRandom random) {
115		final byte[] bytes = new byte[length];
116		random.nextBytes(bytes);
117		return Base64.encodeToString(bytes,Base64.NO_PADDING|Base64.NO_WRAP|Base64.URL_SAFE);
118	}
119
120	public static String prettifyFingerprint(String fingerprint) {
121		if (fingerprint==null) {
122			return "";
123		} else if (fingerprint.length() < 40) {
124			return fingerprint;
125		}
126		StringBuilder builder = new StringBuilder(fingerprint);
127		for(int i=8;i<builder.length();i+=9) {
128			builder.insert(i, ' ');
129		}
130		return builder.toString();
131	}
132
133	public static String prettifyFingerprintCert(String fingerprint) {
134		StringBuilder builder = new StringBuilder(fingerprint);
135		for(int i=2;i < builder.length(); i+=3) {
136			builder.insert(i,':');
137		}
138		return builder.toString();
139	}
140
141	public static String[] getOrderedCipherSuites(final String[] platformSupportedCipherSuites) {
142		final Collection<String> cipherSuites = new LinkedHashSet<>(Arrays.asList(Config.ENABLED_CIPHERS));
143		final List<String> platformCiphers = Arrays.asList(platformSupportedCipherSuites);
144		cipherSuites.retainAll(platformCiphers);
145		cipherSuites.addAll(platformCiphers);
146		filterWeakCipherSuites(cipherSuites);
147		cipherSuites.remove("TLS_FALLBACK_SCSV");
148		return cipherSuites.toArray(new String[cipherSuites.size()]);
149	}
150
151	private static void filterWeakCipherSuites(final Collection<String> cipherSuites) {
152		final Iterator<String> it = cipherSuites.iterator();
153		while (it.hasNext()) {
154			String cipherName = it.next();
155			// remove all ciphers with no or very weak encryption or no authentication
156			for (String weakCipherPattern : Config.WEAK_CIPHER_PATTERNS) {
157				if (cipherName.contains(weakCipherPattern)) {
158					it.remove();
159					break;
160				}
161			}
162		}
163	}
164
165	public static Pair<Jid,String> extractJidAndName(X509Certificate certificate) throws CertificateEncodingException, IllegalArgumentException, CertificateParsingException {
166		Collection<List<?>> alternativeNames = certificate.getSubjectAlternativeNames();
167		List<String> emails = new ArrayList<>();
168		if (alternativeNames != null) {
169			for(List<?> san : alternativeNames) {
170				Integer type = (Integer) san.get(0);
171				if (type == 1) {
172					emails.add((String) san.get(1));
173				}
174			}
175		}
176		X500Name x500name = new JcaX509CertificateHolder(certificate).getSubject();
177		if (emails.size() == 0 && x500name.getRDNs(BCStyle.EmailAddress).length > 0) {
178			emails.add(IETFUtils.valueToString(x500name.getRDNs(BCStyle.EmailAddress)[0].getFirst().getValue()));
179		}
180		String name = x500name.getRDNs(BCStyle.CN).length > 0 ? IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[0].getFirst().getValue()) : null;
181		if (emails.size() >= 1) {
182			return new Pair<>(Jid.of(emails.get(0)), name);
183		} else if (name != null){
184			try {
185				Jid jid = Jid.of(name);
186				if (jid.isBareJid() && jid.getLocal() != null) {
187					return new Pair<>(jid,null);
188				}
189			} catch (IllegalArgumentException e) {
190				return null;
191			}
192		}
193		return null;
194	}
195
196	public static Bundle extractCertificateInformation(X509Certificate certificate) {
197		Bundle information = new Bundle();
198		try {
199			JcaX509CertificateHolder holder = new JcaX509CertificateHolder(certificate);
200			X500Name subject = holder.getSubject();
201			try {
202				information.putString("subject_cn", subject.getRDNs(BCStyle.CN)[0].getFirst().getValue().toString());
203			} catch (Exception e) {
204				//ignored
205			}
206			try {
207				information.putString("subject_o",subject.getRDNs(BCStyle.O)[0].getFirst().getValue().toString());
208			} catch (Exception e) {
209				//ignored
210			}
211
212			X500Name issuer = holder.getIssuer();
213			try {
214				information.putString("issuer_cn", issuer.getRDNs(BCStyle.CN)[0].getFirst().getValue().toString());
215			} catch (Exception e) {
216				//ignored
217			}
218			try {
219				information.putString("issuer_o", issuer.getRDNs(BCStyle.O)[0].getFirst().getValue().toString());
220			} catch (Exception e) {
221				//ignored
222			}
223			try {
224				information.putString("sha1", getFingerprintCert(certificate.getEncoded()));
225			} catch (Exception e) {
226
227			}
228			return information;
229		} catch (CertificateEncodingException e) {
230			return information;
231		}
232	}
233
234	public static String getFingerprintCert(byte[] input) throws NoSuchAlgorithmException {
235		MessageDigest md = MessageDigest.getInstance("SHA-1");
236		byte[] fingerprint = md.digest(input);
237		return prettifyFingerprintCert(bytesToHex(fingerprint));
238	}
239
240	public static String getAccountFingerprint(Account account, String androidId) {
241		return getFingerprint(account.getJid().asBareJid().toEscapedString()+"\00"+androidId);
242	}
243
244	public static String getFingerprint(String value) {
245		try {
246			MessageDigest md = MessageDigest.getInstance("SHA-1");
247			return bytesToHex(md.digest(value.getBytes("UTF-8")));
248		} catch (Exception e) {
249			return "";
250		}
251	}
252
253	public static int encryptionTypeToText(int encryption) {
254		switch (encryption) {
255			case Message.ENCRYPTION_OTR:
256				return R.string.encryption_choice_otr;
257			case Message.ENCRYPTION_AXOLOTL:
258			case Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE:
259				return R.string.encryption_choice_omemo;
260			case Message.ENCRYPTION_NONE:
261				return R.string.encryption_choice_unencrypted;
262			default:
263				return R.string.encryption_choice_pgp;
264		}
265	}
266
267	public static URL toAesGcmUrl(URL url) {
268		if (!url.getProtocol().equalsIgnoreCase("https")) {
269			return url;
270		}
271		try {
272			return new URL(AesGcmURLStreamHandler.PROTOCOL_NAME+url.toString().substring(url.getProtocol().length()));
273		} catch (MalformedURLException e) {
274			return url;
275		}
276	}
277
278	public static URL toHttpsUrl(URL url) {
279		if (!url.getProtocol().equalsIgnoreCase(AesGcmURLStreamHandler.PROTOCOL_NAME)) {
280			return url;
281		}
282		try {
283			return new URL("https"+url.toString().substring(url.getProtocol().length()));
284		} catch (MalformedURLException e) {
285			return url;
286		}
287	}
288
289	public static boolean isPgpEncryptedUrl(String url) {
290		if (url == null) {
291			return false;
292		}
293		final String u = url.toLowerCase();
294		return !u.contains(" ") && (u.startsWith("https://") || u.startsWith("http://") || u.startsWith("p1s3://")) && u.endsWith(".pgp");
295	}
296}