aboutsummaryrefslogtreecommitdiff
path: root/src/share/classes/sun/security/pkcs11/P11Mac.java
blob: deeb1631606fcd1d6ad6060993ff5d6b5ae2ec41 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/*
 * Copyright 2003-2010 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

package sun.security.pkcs11;

import java.util.*;
import java.nio.ByteBuffer;

import java.security.*;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.MacSpi;

import sun.nio.ch.DirectBuffer;

import sun.security.pkcs11.wrapper.*;
import static sun.security.pkcs11.wrapper.PKCS11Constants.*;

/**
 * MAC implementation class. This class currently supports HMAC using
 * MD5, SHA-1, SHA-256, SHA-384, and SHA-512 and the SSL3 MAC using MD5
 * and SHA-1.
 *
 * Note that unlike other classes (e.g. Signature), this does not
 * composite various operations if the token only supports part of the
 * required functionality. The MAC implementations in SunJCE already
 * do exactly that by implementing an MAC on top of MessageDigests. We
 * could not do any better than they.
 *
 * @author  Andreas Sterbenz
 * @since   1.5
 */
final class P11Mac extends MacSpi {

    /* unitialized, all fields except session have arbitrary values */
    private final static int S_UNINIT   = 1;

    /* session initialized, no data processed yet */
    private final static int S_RESET    = 2;

    /* session initialized, data processed */
    private final static int S_UPDATE   = 3;

    /* transitional state after doFinal() before we go to S_UNINIT */
    private final static int S_DOFINAL  = 4;

    // token instance
    private final Token token;

    // algorithm name
    private final String algorithm;

    // mechanism id
    private final long mechanism;

    // mechanism object
    private final CK_MECHANISM ckMechanism;

    // length of the MAC in bytes
    private final int macLength;

    // key instance used, if operation active
    private P11Key p11Key;

    // associated session, if any
    private Session session;

    // state, one of S_* above
    private int state;

    // one byte buffer for the update(byte) method, initialized on demand
    private byte[] oneByte;

    P11Mac(Token token, String algorithm, long mechanism)
            throws PKCS11Exception {
        super();
        this.token = token;
        this.algorithm = algorithm;
        this.mechanism = mechanism;
        Long params = null;
        switch ((int)mechanism) {
        case (int)CKM_MD5_HMAC:
            macLength = 16;
            break;
        case (int)CKM_SHA_1_HMAC:
            macLength = 20;
            break;
        case (int)CKM_SHA256_HMAC:
            macLength = 32;
            break;
        case (int)CKM_SHA384_HMAC:
            macLength = 48;
            break;
        case (int)CKM_SHA512_HMAC:
            macLength = 64;
            break;
        case (int)CKM_SSL3_MD5_MAC:
            macLength = 16;
            params = Long.valueOf(16);
            break;
        case (int)CKM_SSL3_SHA1_MAC:
            macLength = 20;
            params = Long.valueOf(20);
            break;
        default:
            throw new ProviderException("Unknown mechanism: " + mechanism);
        }
        ckMechanism = new CK_MECHANISM(mechanism, params);
        state = S_UNINIT;
        initialize();
    }

    private void ensureInitialized() throws PKCS11Exception {
        token.ensureValid();
        if (state == S_UNINIT) {
            initialize();
        }
    }

    private void cancelOperation() {
        token.ensureValid();
        if (state == S_UNINIT) {
            return;
        }
        state = S_UNINIT;
        if ((session == null) || (token.explicitCancel == false)) {
            return;
        }
        try {
            token.p11.C_SignFinal(session.id(), 0);
        } catch (PKCS11Exception e) {
            throw new ProviderException("Cancel failed", e);
        }
    }

    private void initialize() throws PKCS11Exception {
        if (state == S_RESET) {
            return;
        }
        if (session == null) {
            session = token.getOpSession();
        }
        if (p11Key != null) {
            token.p11.C_SignInit
                (session.id(), ckMechanism, p11Key.keyID);
            state = S_RESET;
        } else {
            state = S_UNINIT;
        }
    }

    // see JCE spec
    protected int engineGetMacLength() {
        return macLength;
    }

    // see JCE spec
    protected void engineReset() {
        // the framework insists on calling reset() after doFinal(),
        // but we prefer to take care of reinitialization ourselves
        if (state == S_DOFINAL) {
            state = S_UNINIT;
            return;
        }
        cancelOperation();
        try {
            initialize();
        } catch (PKCS11Exception e) {
            throw new ProviderException("reset() failed, ", e);
        }
    }

    // see JCE spec
    protected void engineInit(Key key, AlgorithmParameterSpec params)
            throws InvalidKeyException, InvalidAlgorithmParameterException {
        if (params != null) {
            throw new InvalidAlgorithmParameterException
                ("Parameters not supported");
        }
        cancelOperation();
        p11Key = P11SecretKeyFactory.convertKey(token, key, algorithm);
        try {
            initialize();
        } catch (PKCS11Exception e) {
            throw new InvalidKeyException("init() failed", e);
        }
    }

    // see JCE spec
    protected byte[] engineDoFinal() {
        try {
            ensureInitialized();
            byte[] mac = token.p11.C_SignFinal(session.id(), 0);
            state = S_DOFINAL;
            return mac;
        } catch (PKCS11Exception e) {
            throw new ProviderException("doFinal() failed", e);
        } finally {
            session = token.releaseSession(session);
        }
    }

    // see JCE spec
    protected void engineUpdate(byte input) {
        if (oneByte == null) {
           oneByte = new byte[1];
        }
        oneByte[0] = input;
        engineUpdate(oneByte, 0, 1);
    }

    // see JCE spec
    protected void engineUpdate(byte[] b, int ofs, int len) {
        try {
            ensureInitialized();
            token.p11.C_SignUpdate(session.id(), 0, b, ofs, len);
            state = S_UPDATE;
        } catch (PKCS11Exception e) {
            throw new ProviderException("update() failed", e);
        }
    }

    // see JCE spec
    protected void engineUpdate(ByteBuffer byteBuffer) {
        try {
            ensureInitialized();
            int len = byteBuffer.remaining();
            if (len <= 0) {
                return;
            }
            if (byteBuffer instanceof DirectBuffer == false) {
                super.engineUpdate(byteBuffer);
                return;
            }
            long addr = ((DirectBuffer)byteBuffer).address();
            int ofs = byteBuffer.position();
            token.p11.C_SignUpdate(session.id(), addr + ofs, null, 0, len);
            byteBuffer.position(ofs + len);
            state = S_UPDATE;
        } catch (PKCS11Exception e) {
            throw new ProviderException("update() failed", e);
        }
    }
}