• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 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 com.android.internal.net.eap.crypto;
18 
19 import com.android.internal.net.crypto.KeyGenerationUtils;
20 import com.android.internal.net.crypto.KeyGenerationUtils.ByteSigner;
21 
22 import java.security.InvalidKeyException;
23 import java.security.NoSuchAlgorithmException;
24 
25 import javax.crypto.Mac;
26 import javax.crypto.spec.SecretKeySpec;
27 
28 /**
29  * HmacSha256ByteSigner is a {@link ByteSigner} to be used for computing HMAC-SHA-256 values for
30  * specific keys and data.
31  */
32 public class HmacSha256ByteSigner implements KeyGenerationUtils.ByteSigner {
33     private static final String TAG = HmacSha256ByteSigner.class.getSimpleName();
34     private static final String MAC_ALGORITHM_STRING = "HmacSHA256";
35     private static final HmacSha256ByteSigner sInstance = new HmacSha256ByteSigner();
36 
37     /**
38      * Gets instance of HmacSha256ByteSigner.
39      *
40      * @return HmacSha256ByteSigner instance.
41      */
getInstance()42     public static HmacSha256ByteSigner getInstance() {
43         return sInstance;
44     }
45 
46     @Override
signBytes(byte[] keyBytes, byte[] dataToSign)47     public byte[] signBytes(byte[] keyBytes, byte[] dataToSign) {
48         try {
49             Mac mac = Mac.getInstance(MAC_ALGORITHM_STRING);
50             mac.init(new SecretKeySpec(keyBytes, MAC_ALGORITHM_STRING));
51             return mac.doFinal(dataToSign);
52         } catch (NoSuchAlgorithmException | InvalidKeyException ex) {
53             throw new IllegalArgumentException(ex);
54         }
55     }
56 }
57