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