View Javadoc

1   package com.atlassian.asap.core.keys;
2   
3   import java.io.UnsupportedEncodingException;
4   import java.net.URLDecoder;
5   import java.nio.charset.StandardCharsets;
6   import java.util.Base64;
7   import java.util.regex.Matcher;
8   import java.util.regex.Pattern;
9   
10  public class DataUriUtil {
11      /**
12       * A regular expression pattern to match a data uri in the following format:
13       * <pre>
14       *  data:{key-mediatype};kid={key-identifier};base64,{encoded-key-data}
15       * </pre>
16       * The value of the kid parameter must be url encoded, in conformance to RFC2397.
17       *
18       * @see <a href="https://tools.ietf.org/html/rfc2397">RFC 2397 The "data" uri scheme</a>
19       */
20      private static Pattern DATA_URI_PATTERN = Pattern.compile("data:(?<mimeType>[\\w\\-]+/[\\w\\-]+);kid=(?<keyId>[\\w.\\-\\+%]*);base64," +
21              "(?<encodedData>[A-Za-z0-9+/=]+)");
22  
23      /**
24       * Extract the key data from the given data uri. The key data must be base64 encoded.
25       *
26       * @param dataUri the data uri to extract the key data from
27       * @return the decoded key data
28       */
29      public static byte[] getKeyData(String dataUri) {
30          String rawKeyData = getParameterFromDataUri(dataUri, "encodedData");
31          return Base64.getDecoder().decode(rawKeyData);
32      }
33  
34      /**
35       * Extract the key identifier from the given data uri. The key identifier must be url encoded.
36       *
37       * @param dataUri the data uri to extract the key id from
38       * @return the decoded key identifier
39       */
40      public static String getKeyId(String dataUri) {
41          String rawKeyId = getParameterFromDataUri(dataUri, "keyId");
42          try {
43              return URLDecoder.decode(rawKeyId, StandardCharsets.US_ASCII.name());
44          } catch (UnsupportedEncodingException e) {
45              throw new IllegalArgumentException("Could not decode key id parameter in data uri. Key id must be url encoded.", e);
46          }
47      }
48  
49      private static String getParameterFromDataUri(String dataUri, String parameter) {
50          Matcher dataUriMatcher = DATA_URI_PATTERN.matcher(dataUri);
51          if (!dataUriMatcher.matches() || dataUriMatcher.groupCount() != 3) {
52              throw new IllegalArgumentException("Unable to parse data uri parameter: " + parameter);
53          }
54          return dataUriMatcher.group(parameter);
55      }
56  
57  }