OpenPgpUtils.java

 1/*
 2 * Copyright (C) 2014 Dominik Schürmann <dominik@dominikschuermann.de>
 3 *
 4 * Licensed under the Apache License, Version 2.0 (the "License");
 5 * you may not use this file except in compliance with the License.
 6 * You may obtain a copy of the License at
 7 *
 8 *      http://www.apache.org/licenses/LICENSE-2.0
 9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.openintents.openpgp.util;
18
19import java.util.List;
20import java.util.Locale;
21import java.util.regex.Matcher;
22import java.util.regex.Pattern;
23
24import android.content.Context;
25import android.content.Intent;
26import android.content.pm.ResolveInfo;
27
28public class OpenPgpUtils {
29
30    public static final Pattern PGP_MESSAGE = Pattern.compile(
31            ".*?(-----BEGIN PGP MESSAGE-----.*?-----END PGP MESSAGE-----).*",
32            Pattern.DOTALL);
33
34    public static final Pattern PGP_SIGNED_MESSAGE = Pattern.compile(
35            ".*?(-----BEGIN PGP SIGNED MESSAGE-----.*?-----BEGIN PGP SIGNATURE-----.*?-----END PGP SIGNATURE-----).*",
36            Pattern.DOTALL);
37
38    public static final int PARSE_RESULT_NO_PGP = -1;
39    public static final int PARSE_RESULT_MESSAGE = 0;
40    public static final int PARSE_RESULT_SIGNED_MESSAGE = 1;
41
42    public static int parseMessage(String message) {
43        Matcher matcherSigned = PGP_SIGNED_MESSAGE.matcher(message);
44        Matcher matcherMessage = PGP_MESSAGE.matcher(message);
45
46        if (matcherMessage.matches()) {
47            return PARSE_RESULT_MESSAGE;
48        } else if (matcherSigned.matches()) {
49            return PARSE_RESULT_SIGNED_MESSAGE;
50        } else {
51            return PARSE_RESULT_NO_PGP;
52        }
53    }
54
55    public static boolean isAvailable(Context context) {
56        Intent intent = new Intent(OpenPgpApi.SERVICE_INTENT);
57        List<ResolveInfo> resInfo = context.getPackageManager().queryIntentServices(intent, 0);
58        if (!resInfo.isEmpty()) {
59            return true;
60        } else {
61            return false;
62        }
63    }
64
65    public static String convertKeyIdToHex(long keyId) {
66        return "0x" + convertKeyIdToHex32bit(keyId >> 32) + convertKeyIdToHex32bit(keyId);
67    }
68
69    private static String convertKeyIdToHex32bit(long keyId) {
70        String hexString = Long.toHexString(keyId & 0xffffffffL).toLowerCase(Locale.ENGLISH);
71        while (hexString.length() < 8) {
72            hexString = "0" + hexString;
73        }
74        return hexString;
75    }
76}