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