CryptoHelper.java

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