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