Path: blob/master/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Mac.java
41154 views
/*1* Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.security.pkcs11;2627import java.nio.ByteBuffer;2829import java.security.*;30import java.security.spec.AlgorithmParameterSpec;3132import javax.crypto.MacSpi;3334import sun.nio.ch.DirectBuffer;3536import sun.security.pkcs11.wrapper.*;37import static sun.security.pkcs11.wrapper.PKCS11Constants.*;38import static sun.security.pkcs11.wrapper.PKCS11Exception.*;3940/**41* MAC implementation class. This class currently supports HMAC using42* MD5, SHA-1, SHA-2 family (SHA-224, SHA-256, SHA-384, and SHA-512),43* SHA-3 family (SHA3-224, SHA3-256, SHA3-384, and SHA3-512), and the44* SSL3 MAC using MD5 and SHA-1.45*46* Note that unlike other classes (e.g. Signature), this does not47* composite various operations if the token only supports part of the48* required functionality. The MAC implementations in SunJCE already49* do exactly that by implementing an MAC on top of MessageDigests. We50* could not do any better than they.51*52* @author Andreas Sterbenz53* @since 1.554*/55final class P11Mac extends MacSpi {5657// token instance58private final Token token;5960// algorithm name61private final String algorithm;6263// mechanism object64private final CK_MECHANISM ckMechanism;6566// length of the MAC in bytes67private final int macLength;6869// key instance used, if operation active70private P11Key p11Key;7172// associated session, if any73private Session session;7475// initialization status76private boolean initialized;7778// one byte buffer for the update(byte) method, initialized on demand79private byte[] oneByte;8081P11Mac(Token token, String algorithm, long mechanism)82throws PKCS11Exception {83super();84this.token = token;85this.algorithm = algorithm;86Long params = null;87switch ((int)mechanism) {88case (int)CKM_MD5_HMAC:89macLength = 16;90break;91case (int)CKM_SHA_1_HMAC:92macLength = 20;93break;94case (int)CKM_SHA224_HMAC:95case (int)CKM_SHA512_224_HMAC:96case (int)CKM_SHA3_224_HMAC:97macLength = 28;98break;99case (int)CKM_SHA256_HMAC:100case (int)CKM_SHA512_256_HMAC:101case (int)CKM_SHA3_256_HMAC:102macLength = 32;103break;104case (int)CKM_SHA384_HMAC:105case (int)CKM_SHA3_384_HMAC:106macLength = 48;107break;108case (int)CKM_SHA512_HMAC:109case (int)CKM_SHA3_512_HMAC:110macLength = 64;111break;112case (int)CKM_SSL3_MD5_MAC:113macLength = 16;114params = Long.valueOf(16);115break;116case (int)CKM_SSL3_SHA1_MAC:117macLength = 20;118params = Long.valueOf(20);119break;120default:121throw new ProviderException("Unknown mechanism: " + mechanism);122}123ckMechanism = new CK_MECHANISM(mechanism, params);124}125126// reset the states to the pre-initialized values127private void reset(boolean doCancel) {128if (!initialized) {129return;130}131initialized = false;132133try {134if (session == null) {135return;136}137138if (doCancel && token.explicitCancel) {139cancelOperation();140}141} finally {142p11Key.releaseKeyID();143session = token.releaseSession(session);144}145}146147private void cancelOperation() {148token.ensureValid();149// cancel operation by finishing it; avoid killSession as some150// hardware vendors may require re-login151try {152token.p11.C_SignFinal(session.id(), 0);153} catch (PKCS11Exception e) {154if (e.getErrorCode() == CKR_OPERATION_NOT_INITIALIZED) {155// Cancel Operation may be invoked after an error on a PKCS#11156// call. If the operation inside the token was already cancelled,157// do not fail here. This is part of a defensive mechanism for158// PKCS#11 libraries that do not strictly follow the standard.159return;160}161throw new ProviderException("Cancel failed", e);162}163}164165private void ensureInitialized() throws PKCS11Exception {166if (!initialized) {167initialize();168}169}170171private void initialize() throws PKCS11Exception {172if (p11Key == null) {173throw new ProviderException(174"Operation cannot be performed without calling engineInit first");175}176token.ensureValid();177long p11KeyID = p11Key.getKeyID();178try {179if (session == null) {180session = token.getOpSession();181}182token.p11.C_SignInit(session.id(), ckMechanism, p11KeyID);183} catch (PKCS11Exception e) {184p11Key.releaseKeyID();185session = token.releaseSession(session);186throw e;187}188initialized = true;189}190191// see JCE spec192protected int engineGetMacLength() {193return macLength;194}195196// see JCE spec197protected void engineReset() {198reset(true);199}200201// see JCE spec202protected void engineInit(Key key, AlgorithmParameterSpec params)203throws InvalidKeyException, InvalidAlgorithmParameterException {204if (params != null) {205throw new InvalidAlgorithmParameterException206("Parameters not supported");207}208reset(true);209p11Key = P11SecretKeyFactory.convertKey(token, key, algorithm);210try {211initialize();212} catch (PKCS11Exception e) {213throw new InvalidKeyException("init() failed", e);214}215}216217// see JCE spec218protected byte[] engineDoFinal() {219try {220ensureInitialized();221return token.p11.C_SignFinal(session.id(), 0);222} catch (PKCS11Exception e) {223// As per the PKCS#11 standard, C_SignFinal may only224// keep the operation active on CKR_BUFFER_TOO_SMALL errors or225// successful calls to determine the output length. However,226// these cases are handled at OpenJDK's libj2pkcs11 native227// library. Thus, P11Mac::reset can be called with a 'false'228// doCancel argument from here.229throw new ProviderException("doFinal() failed", e);230} finally {231reset(false);232}233}234235// see JCE spec236protected void engineUpdate(byte input) {237if (oneByte == null) {238oneByte = new byte[1];239}240oneByte[0] = input;241engineUpdate(oneByte, 0, 1);242}243244// see JCE spec245protected void engineUpdate(byte[] b, int ofs, int len) {246try {247ensureInitialized();248token.p11.C_SignUpdate(session.id(), 0, b, ofs, len);249} catch (PKCS11Exception e) {250throw new ProviderException("update() failed", e);251}252}253254// see JCE spec255protected void engineUpdate(ByteBuffer byteBuffer) {256try {257ensureInitialized();258int len = byteBuffer.remaining();259if (len <= 0) {260return;261}262if (byteBuffer instanceof DirectBuffer == false) {263super.engineUpdate(byteBuffer);264return;265}266long addr = ((DirectBuffer)byteBuffer).address();267int ofs = byteBuffer.position();268token.p11.C_SignUpdate(session.id(), addr + ofs, null, 0, len);269byteBuffer.position(ofs + len);270} catch (PKCS11Exception e) {271throw new ProviderException("update() failed", e);272}273}274}275276277