1 /*
2  * Copyright (C) 2020 The Android Open Source Project
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 
17 package android.appsecurity.cts.keyrotationtest.utils;
18 
19 import java.security.MessageDigest;
20 import java.security.NoSuchAlgorithmException;
21 import java.util.Optional;
22 
23 /** Provides utility methods that can be used for signature verification. */
24 public class SignatureUtils {
SignatureUtils()25     private SignatureUtils() {}
26 
27     private static final char[] HEX_CHARACTERS = "0123456789abcdef".toCharArray();
28 
29     /**
30      * Computes the sha256 digest of the provided {@code data}, returning an Optional containing a
31      * String representing the hex encoding of the digest.
32      *
33      * <p>If the SHA-256 MessageDigest instance is not available this method will return an empty
34      * Optional.
35      */
computeSha256Digest(byte[] data)36     public static Optional<String> computeSha256Digest(byte[] data) {
37         MessageDigest messageDigest;
38         try {
39             messageDigest = MessageDigest.getInstance("SHA-256");
40         } catch (NoSuchAlgorithmException e) {
41             return Optional.empty();
42         }
43         messageDigest.update(data);
44         return Optional.of(toHexString(messageDigest.digest()));
45     }
46 
47     /** Returns a String representing the hex encoding of the provided {@code data}. */
toHexString(byte[] data)48     public static String toHexString(byte[] data) {
49         char[] result = new char[data.length * 2];
50         for (int i = 0; i < data.length; i++) {
51             int resultIndex = i * 2;
52             result[resultIndex] = HEX_CHARACTERS[(data[i] >> 4) & 0x0f];
53             result[resultIndex + 1] = HEX_CHARACTERS[data[i] & 0x0f];
54         }
55         return new String(result);
56     }
57 }
58 
59