Home | History | Annotate | Download | only in conscrypt
      1 /*
      2  * Copyright (C) 2012 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 org.conscrypt;
     18 
     19 import java.nio.ByteBuffer;
     20 import java.security.InvalidAlgorithmParameterException;
     21 import java.security.InvalidKeyException;
     22 import java.security.Key;
     23 import java.security.NoSuchAlgorithmException;
     24 import java.security.spec.AlgorithmParameterSpec;
     25 import javax.crypto.MacSpi;
     26 import javax.crypto.SecretKey;
     27 
     28 /**
     29  * An implementation of {@link javax.crypto.Mac} which uses BoringSSL to perform all the operations.
     30  *
     31  * @hide
     32  */
     33 @Internal
     34 public abstract class OpenSSLMac extends MacSpi {
     35     private NativeRef.HMAC_CTX ctx;
     36 
     37     /**
     38      * Holds the EVP_MD for the hashing algorithm, e.g.
     39      * EVP_get_digestbyname("sha1");
     40      */
     41     private final long evp_md;
     42 
     43     /**
     44      * The secret key used in this keyed MAC.
     45      */
     46     private byte[] keyBytes;
     47 
     48     /**
     49      * Holds the output size of the message digest.
     50      */
     51     private final int size;
     52 
     53     /**
     54      * Holds a dummy buffer for writing single bytes to the digest.
     55      */
     56     private final byte[] singleByte = new byte[1];
     57 
     58     private OpenSSLMac(long evp_md, int size) {
     59         this.evp_md = evp_md;
     60         this.size = size;
     61     }
     62 
     63     @Override
     64     protected int engineGetMacLength() {
     65         return size;
     66     }
     67 
     68     @Override
     69     protected void engineInit(Key key, AlgorithmParameterSpec params) throws InvalidKeyException,
     70             InvalidAlgorithmParameterException {
     71         if (!(key instanceof SecretKey)) {
     72             throw new InvalidKeyException("key must be a SecretKey");
     73         }
     74 
     75         if (params != null) {
     76             throw new InvalidAlgorithmParameterException("unknown parameter type");
     77         }
     78 
     79         keyBytes = key.getEncoded();
     80         if (keyBytes == null) {
     81             throw new InvalidKeyException("key cannot be encoded");
     82         }
     83 
     84         resetContext();
     85     }
     86 
     87     private final void resetContext() {
     88         NativeRef.HMAC_CTX ctxLocal = new NativeRef.HMAC_CTX(NativeCrypto.HMAC_CTX_new());
     89         if (keyBytes != null) {
     90             NativeCrypto.HMAC_Init_ex(ctxLocal, keyBytes, evp_md);
     91         }
     92 
     93         this.ctx = ctxLocal;
     94     }
     95 
     96     @Override
     97     protected void engineUpdate(byte input) {
     98         singleByte[0] = input;
     99         engineUpdate(singleByte, 0, 1);
    100     }
    101 
    102     @Override
    103     protected void engineUpdate(byte[] input, int offset, int len) {
    104         final NativeRef.HMAC_CTX ctxLocal = ctx;
    105         NativeCrypto.HMAC_Update(ctxLocal, input, offset, len);
    106     }
    107 
    108     @Override
    109     protected void engineUpdate(ByteBuffer input) {
    110         // Optimization: Avoid copying/allocation for direct buffers because their contents are
    111         // stored as a contiguous region in memory and thus can be efficiently accessed from native
    112         // code.
    113 
    114         if (!input.hasRemaining()) {
    115             return;
    116         }
    117 
    118         if (!input.isDirect()) {
    119             super.engineUpdate(input);
    120             return;
    121         }
    122 
    123         long baseAddress = NativeCrypto.getDirectBufferAddress(input);
    124         if (baseAddress == 0) {
    125             // Direct buffer's contents can't be accessed from JNI  -- superclass's implementation
    126             // is good enough to handle this.
    127             super.engineUpdate(input);
    128             return;
    129         }
    130 
    131         // MAC the contents between Buffer's position and limit (remaining() number of bytes)
    132         int position = input.position();
    133         if (position < 0) {
    134             throw new RuntimeException("Negative position");
    135         }
    136         long ptr = baseAddress + position;
    137         int len = input.remaining();
    138         if (len < 0) {
    139             throw new RuntimeException("Negative remaining amount");
    140         }
    141 
    142         final NativeRef.HMAC_CTX ctxLocal = ctx;
    143         NativeCrypto.HMAC_UpdateDirect(ctxLocal, ptr, len);
    144         input.position(position + len);
    145     }
    146 
    147     @Override
    148     protected byte[] engineDoFinal() {
    149         final NativeRef.HMAC_CTX ctxLocal = ctx;
    150         final byte[] output = NativeCrypto.HMAC_Final(ctxLocal);
    151         resetContext();
    152         return output;
    153     }
    154 
    155     @Override
    156     protected void engineReset() {
    157         resetContext();
    158     }
    159 
    160     public static final class HmacMD5 extends OpenSSLMac {
    161         public HmacMD5() {
    162             super(EvpMdRef.MD5.EVP_MD, EvpMdRef.MD5.SIZE_BYTES);
    163         }
    164     }
    165 
    166     public static final class HmacSHA1 extends OpenSSLMac {
    167         public HmacSHA1() {
    168             super(EvpMdRef.SHA1.EVP_MD, EvpMdRef.SHA1.SIZE_BYTES);
    169         }
    170     }
    171 
    172     public static final class HmacSHA224 extends OpenSSLMac {
    173         public HmacSHA224() throws NoSuchAlgorithmException {
    174             super(EvpMdRef.SHA224.EVP_MD, EvpMdRef.SHA224.SIZE_BYTES);
    175         }
    176     }
    177 
    178     public static final class HmacSHA256 extends OpenSSLMac {
    179         public HmacSHA256() throws NoSuchAlgorithmException {
    180             super(EvpMdRef.SHA256.EVP_MD, EvpMdRef.SHA256.SIZE_BYTES);
    181         }
    182     }
    183 
    184     public static final class HmacSHA384 extends OpenSSLMac {
    185         public HmacSHA384() throws NoSuchAlgorithmException {
    186             super(EvpMdRef.SHA384.EVP_MD, EvpMdRef.SHA384.SIZE_BYTES);
    187         }
    188     }
    189 
    190     public static final class HmacSHA512 extends OpenSSLMac {
    191         public HmacSHA512() {
    192             super(EvpMdRef.SHA512.EVP_MD, EvpMdRef.SHA512.SIZE_BYTES);
    193         }
    194     }
    195 }
    196