P11Cipher.java 32.9 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * 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
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * 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.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27
 */
package sun.security.pkcs11;

import java.nio.ByteBuffer;
28
import java.util.Arrays;
29
import java.util.Locale;
D
duke 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

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

import javax.crypto.*;
import javax.crypto.spec.*;

import sun.nio.ch.DirectBuffer;
import sun.security.pkcs11.wrapper.*;
import static sun.security.pkcs11.wrapper.PKCS11Constants.*;

/**
 * Cipher implementation class. This class currently supports
 * DES, DESede, AES, ARCFOUR, and Blowfish.
 *
45 46 47
 * This class is designed to support ECB, CBC, CTR with NoPadding
 * and ECB, CBC with PKCS5Padding. It will use its own padding impl
 * if the native mechanism does not support padding.
D
duke 已提交
48
 *
49 50
 * Note that PKCS#11 currently only supports ECB, CBC, and CTR.
 * There are no provisions for other modes such as CFB, OFB, and PCBC.
D
duke 已提交
51 52 53 54 55 56 57 58 59 60
 *
 * @author  Andreas Sterbenz
 * @since   1.5
 */
final class P11Cipher extends CipherSpi {

    // mode constant for ECB mode
    private final static int MODE_ECB = 3;
    // mode constant for CBC mode
    private final static int MODE_CBC = 4;
61 62
    // mode constant for CTR mode
    private final static int MODE_CTR = 5;
D
duke 已提交
63 64

    // padding constant for NoPadding
65
    private final static int PAD_NONE = 5;
D
duke 已提交
66 67 68
    // padding constant for PKCS5Padding
    private final static int PAD_PKCS5 = 6;

69 70 71 72 73 74 75
    private static interface Padding {
        // ENC: format the specified buffer with padding bytes and return the
        // actual padding length
        int setPaddingBytes(byte[] paddingBuffer, int padLen);

        // DEC: return the length of trailing padding bytes given the specified
        // padded data
76
        int unpad(byte[] paddedData, int len)
77
                throws BadPaddingException, IllegalBlockSizeException;
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    }

    private static class PKCS5Padding implements Padding {

        private final int blockSize;

        PKCS5Padding(int blockSize)
                throws NoSuchPaddingException {
            if (blockSize == 0) {
                throw new NoSuchPaddingException
                        ("PKCS#5 padding not supported with stream ciphers");
            }
            this.blockSize = blockSize;
        }

        public int setPaddingBytes(byte[] paddingBuffer, int padLen) {
            Arrays.fill(paddingBuffer, 0, padLen, (byte) (padLen & 0x007f));
            return padLen;
        }

98
        public int unpad(byte[] paddedData, int len)
99 100 101 102
                throws BadPaddingException, IllegalBlockSizeException {
            if ((len < 1) || (len % blockSize != 0)) {
                throw new IllegalBlockSizeException
                    ("Input length must be multiples of " + blockSize);
103 104
            }
            byte padValue = paddedData[len - 1];
105 106 107 108
            if (padValue < 1 || padValue > blockSize) {
                throw new BadPaddingException("Invalid pad value!");
            }
            // sanity check padding bytes
109
            int padStartIndex = len - padValue;
110 111 112 113 114 115 116 117 118
            for (int i = padStartIndex; i < len; i++) {
                if (paddedData[i] != padValue) {
                    throw new BadPaddingException("Invalid pad bytes!");
                }
            }
            return padValue;
        }
    }

D
duke 已提交
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
    // token instance
    private final Token token;

    // algorithm name
    private final String algorithm;

    // name of the key algorithm, e.g. DES instead of algorithm DES/CBC/...
    private final String keyAlgorithm;

    // mechanism id
    private final long mechanism;

    // associated session, if any
    private Session session;

    // key, if init() was called
    private P11Key p11Key;

    // flag indicating whether an operation is initialized
    private boolean initialized;

    // falg indicating encrypt or decrypt mode
    private boolean encrypt;

    // mode, one of MODE_* above (MODE_ECB for stream ciphers)
    private int blockMode;

    // block size, 0 for stream ciphers
    private final int blockSize;

    // padding type, on of PAD_* above (PAD_NONE for stream ciphers)
    private int paddingType;

152 153 154 155 156 157 158 159
    // when the padding is requested but unsupported by the native mechanism,
    // we use the following to do padding and necessary data buffering.
    // padding object which generate padding and unpad the decrypted data
    private Padding paddingObj;
    // buffer for holding back the block which contains padding bytes
    private byte[] padBuffer;
    private int padBufferLen;

160
    // original IV, if in MODE_CBC or MODE_CTR
D
duke 已提交
161 162
    private byte[] iv;

163 164 165
    // number of bytes buffered internally by the native mechanism and padBuffer
    // if we do the padding
    private int bytesBuffered;
D
duke 已提交
166

167 168 169 170
    // length of key size in bytes; currently only used by AES given its oid
    // specification mandates a fixed size of the key
    private int fixedKeySize = -1;

D
duke 已提交
171
    P11Cipher(Token token, String algorithm, long mechanism)
172
            throws PKCS11Exception, NoSuchAlgorithmException {
D
duke 已提交
173 174 175 176
        super();
        this.token = token;
        this.algorithm = algorithm;
        this.mechanism = mechanism;
177 178 179

        String algoParts[] = algorithm.split("/");

180
        if (algoParts[0].startsWith("AES")) {
D
duke 已提交
181
            blockSize = 16;
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
            int index = algoParts[0].indexOf('_');
            if (index != -1) {
                // should be well-formed since we specify what we support
                fixedKeySize = Integer.parseInt(algoParts[0].substring(index+1))/8;
            }
            keyAlgorithm = "AES";
        } else {
            keyAlgorithm = algoParts[0];
            if (keyAlgorithm.equals("RC4") ||
                    keyAlgorithm.equals("ARCFOUR")) {
                blockSize = 0;
            } else { // DES, DESede, Blowfish
                blockSize = 8;
            }
        }
197 198
        this.blockMode =
            (algoParts.length > 1 ? parseMode(algoParts[1]) : MODE_ECB);
199 200 201 202 203 204 205 206
        String defPadding = (blockSize == 0 ? "NoPadding" : "PKCS5Padding");
        String paddingStr =
                (algoParts.length > 2 ? algoParts[2] : defPadding);
        try {
            engineSetPadding(paddingStr);
        } catch (NoSuchPaddingException nspe) {
            // should not happen
            throw new ProviderException(nspe);
D
duke 已提交
207 208 209 210
        }
    }

    protected void engineSetMode(String mode) throws NoSuchAlgorithmException {
211 212 213 214 215 216
        // Disallow change of mode for now since currently it's explicitly
        // defined in transformation strings
        throw new NoSuchAlgorithmException("Unsupported mode " + mode);
    }

    private int parseMode(String mode) throws NoSuchAlgorithmException {
217
        mode = mode.toUpperCase(Locale.ENGLISH);
218
        int result;
D
duke 已提交
219
        if (mode.equals("ECB")) {
220
            result = MODE_ECB;
D
duke 已提交
221 222 223 224 225
        } else if (mode.equals("CBC")) {
            if (blockSize == 0) {
                throw new NoSuchAlgorithmException
                        ("CBC mode not supported with stream ciphers");
            }
226
            result = MODE_CBC;
227 228
        } else if (mode.equals("CTR")) {
            result = MODE_CTR;
D
duke 已提交
229 230 231
        } else {
            throw new NoSuchAlgorithmException("Unsupported mode " + mode);
        }
232
        return result;
D
duke 已提交
233 234 235 236 237
    }

    // see JCE spec
    protected void engineSetPadding(String padding)
            throws NoSuchPaddingException {
238 239
        paddingObj = null;
        padBuffer = null;
240
        padding = padding.toUpperCase(Locale.ENGLISH);
241
        if (padding.equals("NOPADDING")) {
D
duke 已提交
242
            paddingType = PAD_NONE;
243
        } else if (padding.equals("PKCS5PADDING")) {
244 245 246 247
            if (this.blockMode == MODE_CTR) {
                throw new NoSuchPaddingException
                    ("PKCS#5 padding not supported with CTR mode");
            }
D
duke 已提交
248
            paddingType = PAD_PKCS5;
249 250 251 252 253 254
            if (mechanism != CKM_DES_CBC_PAD && mechanism != CKM_DES3_CBC_PAD &&
                    mechanism != CKM_AES_CBC_PAD) {
                // no native padding support; use our own padding impl
                paddingObj = new PKCS5Padding(blockSize);
                padBuffer = new byte[blockSize];
            }
D
duke 已提交
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
        } else {
            throw new NoSuchPaddingException("Unsupported padding " + padding);
        }
    }

    // see JCE spec
    protected int engineGetBlockSize() {
        return blockSize;
    }

    // see JCE spec
    protected int engineGetOutputSize(int inputLen) {
        return doFinalLength(inputLen);
    }

    // see JCE spec
    protected byte[] engineGetIV() {
272
        return (iv == null) ? null : iv.clone();
D
duke 已提交
273 274 275 276 277 278 279 280 281
    }

    // see JCE spec
    protected AlgorithmParameters engineGetParameters() {
        if (iv == null) {
            return null;
        }
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        try {
282 283 284
            AlgorithmParameters params =
                    AlgorithmParameters.getInstance(keyAlgorithm,
                    P11Util.getSunJceProvider());
D
duke 已提交
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
            params.init(ivSpec);
            return params;
        } catch (GeneralSecurityException e) {
            // NoSuchAlgorithmException, NoSuchProviderException
            // InvalidParameterSpecException
            throw new ProviderException("Could not encode parameters", e);
        }
    }

    // see JCE spec
    protected void engineInit(int opmode, Key key, SecureRandom random)
            throws InvalidKeyException {
        try {
            implInit(opmode, key, null, random);
        } catch (InvalidAlgorithmParameterException e) {
            throw new InvalidKeyException("init() failed", e);
        }
    }

    // see JCE spec
    protected void engineInit(int opmode, Key key,
            AlgorithmParameterSpec params, SecureRandom random)
            throws InvalidKeyException, InvalidAlgorithmParameterException {
308
        byte[] ivValue;
D
duke 已提交
309 310 311 312 313
        if (params != null) {
            if (params instanceof IvParameterSpec == false) {
                throw new InvalidAlgorithmParameterException
                        ("Only IvParameterSpec supported");
            }
314 315
            IvParameterSpec ivSpec = (IvParameterSpec) params;
            ivValue = ivSpec.getIV();
D
duke 已提交
316
        } else {
317
            ivValue = null;
D
duke 已提交
318
        }
319
        implInit(opmode, key, ivValue, random);
D
duke 已提交
320 321 322 323 324 325
    }

    // see JCE spec
    protected void engineInit(int opmode, Key key, AlgorithmParameters params,
            SecureRandom random)
            throws InvalidKeyException, InvalidAlgorithmParameterException {
326
        byte[] ivValue;
D
duke 已提交
327 328
        if (params != null) {
            try {
329
                IvParameterSpec ivSpec =
D
duke 已提交
330
                        params.getParameterSpec(IvParameterSpec.class);
331
                ivValue = ivSpec.getIV();
D
duke 已提交
332 333 334 335 336
            } catch (InvalidParameterSpecException e) {
                throw new InvalidAlgorithmParameterException
                        ("Could not decode IV", e);
            }
        } else {
337
            ivValue = null;
D
duke 已提交
338
        }
339
        implInit(opmode, key, ivValue, random);
D
duke 已提交
340 341 342 343 344 345 346
    }

    // actual init() implementation
    private void implInit(int opmode, Key key, byte[] iv,
            SecureRandom random)
            throws InvalidKeyException, InvalidAlgorithmParameterException {
        cancelOperation();
347 348 349
        if (fixedKeySize != -1 && key.getEncoded().length != fixedKeySize) {
            throw new InvalidKeyException("Key size is invalid");
        }
D
duke 已提交
350
        switch (opmode) {
351 352 353 354 355 356 357 358 359
            case Cipher.ENCRYPT_MODE:
                encrypt = true;
                break;
            case Cipher.DECRYPT_MODE:
                encrypt = false;
                break;
            default:
                throw new InvalidAlgorithmParameterException
                        ("Unsupported mode: " + opmode);
D
duke 已提交
360 361 362 363 364
        }
        if (blockMode == MODE_ECB) { // ECB or stream cipher
            if (iv != null) {
                if (blockSize == 0) {
                    throw new InvalidAlgorithmParameterException
365
                            ("IV not used with stream ciphers");
D
duke 已提交
366 367
                } else {
                    throw new InvalidAlgorithmParameterException
368
                            ("IV not used in ECB mode");
D
duke 已提交
369 370
                }
            }
371
        } else { // MODE_CBC or MODE_CTR
D
duke 已提交
372 373
            if (iv == null) {
                if (encrypt == false) {
374 375 376 377 378
                    String exMsg =
                        (blockMode == MODE_CBC ?
                         "IV must be specified for decryption in CBC mode" :
                         "IV must be specified for decryption in CTR mode");
                    throw new InvalidAlgorithmParameterException(exMsg);
D
duke 已提交
379 380 381 382 383 384 385 386 387 388
                }
                // generate random IV
                if (random == null) {
                    random = new SecureRandom();
                }
                iv = new byte[blockSize];
                random.nextBytes(iv);
            } else {
                if (iv.length != blockSize) {
                    throw new InvalidAlgorithmParameterException
389
                            ("IV length must match block size");
D
duke 已提交
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
                }
            }
        }
        this.iv = iv;
        p11Key = P11SecretKeyFactory.convertKey(token, key, keyAlgorithm);
        try {
            initialize();
        } catch (PKCS11Exception e) {
            throw new InvalidKeyException("Could not initialize cipher", e);
        }
    }

    private void cancelOperation() {
        if (initialized == false) {
            return;
        }
        initialized = false;
        if ((session == null) || (token.explicitCancel == false)) {
            return;
        }
        // cancel operation by finishing it
        int bufLen = doFinalLength(0);
        byte[] buffer = new byte[bufLen];
        try {
            if (encrypt) {
                token.p11.C_EncryptFinal(session.id(), 0, buffer, 0, bufLen);
            } else {
                token.p11.C_DecryptFinal(session.id(), 0, buffer, 0, bufLen);
            }
        } catch (PKCS11Exception e) {
            throw new ProviderException("Cancel failed", e);
421 422
        } finally {
            reset();
D
duke 已提交
423 424 425 426 427 428 429 430 431 432 433 434 435
        }
    }

    private void ensureInitialized() throws PKCS11Exception {
        if (initialized == false) {
            initialize();
        }
    }

    private void initialize() throws PKCS11Exception {
        if (session == null) {
            session = token.getOpSession();
        }
436 437 438 439
        CK_MECHANISM mechParams = (blockMode == MODE_CTR?
            new CK_MECHANISM(mechanism, new CK_AES_CTR_PARAMS(iv)) :
            new CK_MECHANISM(mechanism, iv));

440 441
        try {
            if (encrypt) {
442
                token.p11.C_EncryptInit(session.id(), mechParams, p11Key.keyID);
443
            } else {
444
                token.p11.C_DecryptInit(session.id(), mechParams, p11Key.keyID);
445 446 447 448 449
            }
        } catch (PKCS11Exception ex) {
            // release session when initialization failed
            session = token.releaseSession(session);
            throw ex;
D
duke 已提交
450
        }
451 452
        bytesBuffered = 0;
        padBufferLen = 0;
D
duke 已提交
453 454 455 456 457 458 459 460
        initialized = true;
    }

    // if update(inLen) is called, how big does the output buffer have to be?
    private int updateLength(int inLen) {
        if (inLen <= 0) {
            return 0;
        }
461 462 463 464 465

        int result = inLen + bytesBuffered;
        if (blockSize != 0) {
            // minus the number of bytes in the last incomplete block.
            result -= (result & (blockSize - 1));
D
duke 已提交
466
        }
467
        return result;
D
duke 已提交
468 469 470 471 472 473 474
    }

    // if doFinal(inLen) is called, how big does the output buffer have to be?
    private int doFinalLength(int inLen) {
        if (inLen < 0) {
            return 0;
        }
475 476 477 478 479 480 481

        int result = inLen + bytesBuffered;
        if (blockSize != 0 && encrypt && paddingType != PAD_NONE) {
            // add the number of bytes to make the last block complete.
            result += (blockSize - (result & (blockSize - 1)));
        }
        return result;
D
duke 已提交
482 483
    }

484 485 486 487 488 489 490 491 492 493
    // reset the states to the pre-initialized values
    private void reset() {
        initialized = false;
        bytesBuffered = 0;
        padBufferLen = 0;
        if (session != null) {
            session = token.releaseSession(session);
        }
    }

D
duke 已提交
494 495 496 497 498 499 500
    // see JCE spec
    protected byte[] engineUpdate(byte[] in, int inOfs, int inLen) {
        try {
            byte[] out = new byte[updateLength(inLen)];
            int n = engineUpdate(in, inOfs, inLen, out, 0);
            return P11Util.convert(out, 0, n);
        } catch (ShortBufferException e) {
501
            // convert since the output length is calculated by updateLength()
D
duke 已提交
502 503 504 505 506 507 508 509 510 511 512 513
            throw new ProviderException(e);
        }
    }

    // see JCE spec
    protected int engineUpdate(byte[] in, int inOfs, int inLen, byte[] out,
            int outOfs) throws ShortBufferException {
        int outLen = out.length - outOfs;
        return implUpdate(in, inOfs, inLen, out, outOfs, outLen);
    }

    // see JCE spec
514
    @Override
D
duke 已提交
515 516 517 518 519 520 521 522 523 524 525 526 527
    protected int engineUpdate(ByteBuffer inBuffer, ByteBuffer outBuffer)
            throws ShortBufferException {
        return implUpdate(inBuffer, outBuffer);
    }

    // see JCE spec
    protected byte[] engineDoFinal(byte[] in, int inOfs, int inLen)
            throws IllegalBlockSizeException, BadPaddingException {
        try {
            byte[] out = new byte[doFinalLength(inLen)];
            int n = engineDoFinal(in, inOfs, inLen, out, 0);
            return P11Util.convert(out, 0, n);
        } catch (ShortBufferException e) {
528
            // convert since the output length is calculated by doFinalLength()
D
duke 已提交
529 530 531 532 533 534
            throw new ProviderException(e);
        }
    }

    // see JCE spec
    protected int engineDoFinal(byte[] in, int inOfs, int inLen, byte[] out,
535 536
            int outOfs) throws ShortBufferException, IllegalBlockSizeException,
            BadPaddingException {
D
duke 已提交
537 538 539 540 541 542 543 544 545 546
        int n = 0;
        if ((inLen != 0) && (in != null)) {
            n = engineUpdate(in, inOfs, inLen, out, outOfs);
            outOfs += n;
        }
        n += implDoFinal(out, outOfs, out.length - outOfs);
        return n;
    }

    // see JCE spec
547
    @Override
D
duke 已提交
548
    protected int engineDoFinal(ByteBuffer inBuffer, ByteBuffer outBuffer)
549 550
            throws ShortBufferException, IllegalBlockSizeException,
            BadPaddingException {
D
duke 已提交
551 552 553 554 555 556 557 558 559 560 561 562
        int n = engineUpdate(inBuffer, outBuffer);
        n += implDoFinal(outBuffer);
        return n;
    }

    private int implUpdate(byte[] in, int inOfs, int inLen,
            byte[] out, int outOfs, int outLen) throws ShortBufferException {
        if (outLen < updateLength(inLen)) {
            throw new ShortBufferException();
        }
        try {
            ensureInitialized();
563
            int k = 0;
D
duke 已提交
564
            if (encrypt) {
565 566
                k = token.p11.C_EncryptUpdate(session.id(), 0, in, inOfs, inLen,
                        0, out, outOfs, outLen);
D
duke 已提交
567
            } else {
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
                int newPadBufferLen = 0;
                if (paddingObj != null) {
                    if (padBufferLen != 0) {
                        // NSS throws up when called with data not in multiple
                        // of blocks. Try to work around this by holding the
                        // extra data in padBuffer.
                        if (padBufferLen != padBuffer.length) {
                            int bufCapacity = padBuffer.length - padBufferLen;
                            if (inLen > bufCapacity) {
                                bufferInputBytes(in, inOfs, bufCapacity);
                                inOfs += bufCapacity;
                                inLen -= bufCapacity;
                            } else {
                                bufferInputBytes(in, inOfs, inLen);
                                return 0;
                            }
                        }
                        k = token.p11.C_DecryptUpdate(session.id(),
                                0, padBuffer, 0, padBufferLen,
                                0, out, outOfs, outLen);
                        padBufferLen = 0;
                    }
                    newPadBufferLen = inLen & (blockSize - 1);
                    if (newPadBufferLen == 0) {
                        newPadBufferLen = padBuffer.length;
                    }
                    inLen -= newPadBufferLen;
                }
                if (inLen > 0) {
                    k += token.p11.C_DecryptUpdate(session.id(), 0, in, inOfs,
                            inLen, 0, out, (outOfs + k), (outLen - k));
                }
                // update 'padBuffer' if using our own padding impl.
                if (paddingObj != null) {
                    bufferInputBytes(in, inOfs + inLen, newPadBufferLen);
                }
D
duke 已提交
604
            }
605
            bytesBuffered += (inLen - k);
D
duke 已提交
606 607
            return k;
        } catch (PKCS11Exception e) {
608 609 610 611
            if (e.getErrorCode() == CKR_BUFFER_TOO_SMALL) {
                throw (ShortBufferException)
                        (new ShortBufferException().initCause(e));
            }
612
            reset();
D
duke 已提交
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
            throw new ProviderException("update() failed", e);
        }
    }

    private int implUpdate(ByteBuffer inBuffer, ByteBuffer outBuffer)
            throws ShortBufferException {
        int inLen = inBuffer.remaining();
        if (inLen <= 0) {
            return 0;
        }

        int outLen = outBuffer.remaining();
        if (outLen < updateLength(inLen)) {
            throw new ShortBufferException();
        }
628
        int origPos = inBuffer.position();
D
duke 已提交
629 630 631 632
        try {
            ensureInitialized();

            long inAddr = 0;
633
            int inOfs = 0;
D
duke 已提交
634
            byte[] inArray = null;
635

D
duke 已提交
636
            if (inBuffer instanceof DirectBuffer) {
637 638 639 640 641
                inAddr = ((DirectBuffer) inBuffer).address();
                inOfs = origPos;
            } else if (inBuffer.hasArray()) {
                inArray = inBuffer.array();
                inOfs = (origPos + inBuffer.arrayOffset());
D
duke 已提交
642 643 644
            }

            long outAddr = 0;
645
            int outOfs = 0;
D
duke 已提交
646 647
            byte[] outArray = null;
            if (outBuffer instanceof DirectBuffer) {
648 649
                outAddr = ((DirectBuffer) outBuffer).address();
                outOfs = outBuffer.position();
D
duke 已提交
650 651 652
            } else {
                if (outBuffer.hasArray()) {
                    outArray = outBuffer.array();
653
                    outOfs = (outBuffer.position() + outBuffer.arrayOffset());
D
duke 已提交
654 655 656 657 658
                } else {
                    outArray = new byte[outLen];
                }
            }

659
            int k = 0;
D
duke 已提交
660
            if (encrypt) {
661 662 663 664 665 666 667 668 669
                if (inAddr == 0 && inArray == null) {
                    inArray = new byte[inLen];
                    inBuffer.get(inArray);
                } else {
                    inBuffer.position(origPos + inLen);
                }
                k = token.p11.C_EncryptUpdate(session.id(),
                        inAddr, inArray, inOfs, inLen,
                        outAddr, outArray, outOfs, outLen);
D
duke 已提交
670
            } else {
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
                int newPadBufferLen = 0;
                if (paddingObj != null) {
                    if (padBufferLen != 0) {
                        // NSS throws up when called with data not in multiple
                        // of blocks. Try to work around this by holding the
                        // extra data in padBuffer.
                        if (padBufferLen != padBuffer.length) {
                            int bufCapacity = padBuffer.length - padBufferLen;
                            if (inLen > bufCapacity) {
                                bufferInputBytes(inBuffer, bufCapacity);
                                inOfs += bufCapacity;
                                inLen -= bufCapacity;
                            } else {
                                bufferInputBytes(inBuffer, inLen);
                                return 0;
                            }
                        }
                        k = token.p11.C_DecryptUpdate(session.id(), 0,
                                padBuffer, 0, padBufferLen, outAddr, outArray,
                                outOfs, outLen);
                        padBufferLen = 0;
                    }
                    newPadBufferLen = inLen & (blockSize - 1);
                    if (newPadBufferLen == 0) {
                        newPadBufferLen = padBuffer.length;
                    }
                    inLen -= newPadBufferLen;
                }
                if (inLen > 0) {
                    if (inAddr == 0 && inArray == null) {
                        inArray = new byte[inLen];
                        inBuffer.get(inArray);
                    } else {
                        inBuffer.position(inBuffer.position() + inLen);
                    }
                    k += token.p11.C_DecryptUpdate(session.id(), inAddr,
                            inArray, inOfs, inLen, outAddr, outArray,
                            (outOfs + k), (outLen - k));
                }
                // update 'padBuffer' if using our own padding impl.
                if (paddingObj != null && newPadBufferLen != 0) {
                    bufferInputBytes(inBuffer, newPadBufferLen);
                }
D
duke 已提交
714
            }
715
            bytesBuffered += (inLen - k);
D
duke 已提交
716
            if (!(outBuffer instanceof DirectBuffer) &&
717
                    !outBuffer.hasArray()) {
D
duke 已提交
718 719 720 721 722 723
                outBuffer.put(outArray, outOfs, k);
            } else {
                outBuffer.position(outBuffer.position() + k);
            }
            return k;
        } catch (PKCS11Exception e) {
724 725 726 727 728
            // Reset input buffer to its original position for
            inBuffer.position(origPos);
            if (e.getErrorCode() == CKR_BUFFER_TOO_SMALL) {
                throw (ShortBufferException)
                        (new ShortBufferException().initCause(e));
D
duke 已提交
729
            }
730
            reset();
D
duke 已提交
731 732 733 734 735
            throw new ProviderException("update() failed", e);
        }
    }

    private int implDoFinal(byte[] out, int outOfs, int outLen)
736 737 738 739
            throws ShortBufferException, IllegalBlockSizeException,
            BadPaddingException {
        int requiredOutLen = doFinalLength(0);
        if (outLen < requiredOutLen) {
D
duke 已提交
740 741 742 743
            throw new ShortBufferException();
        }
        try {
            ensureInitialized();
744
            int k = 0;
D
duke 已提交
745
            if (encrypt) {
746 747 748 749 750 751 752 753 754
                if (paddingObj != null) {
                    int actualPadLen = paddingObj.setPaddingBytes(padBuffer,
                            requiredOutLen - bytesBuffered);
                    k = token.p11.C_EncryptUpdate(session.id(),
                            0, padBuffer, 0, actualPadLen,
                            0, out, outOfs, outLen);
                }
                k += token.p11.C_EncryptFinal(session.id(),
                        0, out, (outOfs + k), (outLen - k));
D
duke 已提交
755
            } else {
756 757 758 759 760 761 762 763
                if (paddingObj != null) {
                    if (padBufferLen != 0) {
                        k = token.p11.C_DecryptUpdate(session.id(), 0,
                                padBuffer, 0, padBufferLen, 0, padBuffer, 0,
                                padBuffer.length);
                    }
                    k += token.p11.C_DecryptFinal(session.id(), 0, padBuffer, k,
                            padBuffer.length - k);
764
                    int actualPadLen = paddingObj.unpad(padBuffer, k);
765 766 767 768 769 770
                    k -= actualPadLen;
                    System.arraycopy(padBuffer, 0, out, outOfs, k);
                } else {
                    k = token.p11.C_DecryptFinal(session.id(), 0, out, outOfs,
                            outLen);
                }
D
duke 已提交
771
            }
772
            return k;
D
duke 已提交
773 774 775 776
        } catch (PKCS11Exception e) {
            handleException(e);
            throw new ProviderException("doFinal() failed", e);
        } finally {
777
            reset();
D
duke 已提交
778 779 780 781
        }
    }

    private int implDoFinal(ByteBuffer outBuffer)
782 783
            throws ShortBufferException, IllegalBlockSizeException,
            BadPaddingException {
D
duke 已提交
784
        int outLen = outBuffer.remaining();
785 786
        int requiredOutLen = doFinalLength(0);
        if (outLen < requiredOutLen) {
D
duke 已提交
787 788 789 790 791 792 793 794
            throw new ShortBufferException();
        }

        try {
            ensureInitialized();

            long outAddr = 0;
            byte[] outArray = null;
795
            int outOfs = 0;
D
duke 已提交
796
            if (outBuffer instanceof DirectBuffer) {
797 798
                outAddr = ((DirectBuffer) outBuffer).address();
                outOfs = outBuffer.position();
D
duke 已提交
799 800 801
            } else {
                if (outBuffer.hasArray()) {
                    outArray = outBuffer.array();
802
                    outOfs = outBuffer.position() + outBuffer.arrayOffset();
D
duke 已提交
803 804 805 806 807
                } else {
                    outArray = new byte[outLen];
                }
            }

808 809
            int k = 0;

D
duke 已提交
810
            if (encrypt) {
811 812 813 814 815 816 817 818 819
                if (paddingObj != null) {
                    int actualPadLen = paddingObj.setPaddingBytes(padBuffer,
                            requiredOutLen - bytesBuffered);
                    k = token.p11.C_EncryptUpdate(session.id(),
                            0, padBuffer, 0, actualPadLen,
                            outAddr, outArray, outOfs, outLen);
                }
                k += token.p11.C_EncryptFinal(session.id(),
                        outAddr, outArray, (outOfs + k), (outLen - k));
D
duke 已提交
820
            } else {
821 822 823 824 825 826 827 828 829
                if (paddingObj != null) {
                    if (padBufferLen != 0) {
                        k = token.p11.C_DecryptUpdate(session.id(),
                                0, padBuffer, 0, padBufferLen,
                                0, padBuffer, 0, padBuffer.length);
                        padBufferLen = 0;
                    }
                    k += token.p11.C_DecryptFinal(session.id(),
                            0, padBuffer, k, padBuffer.length - k);
830
                    int actualPadLen = paddingObj.unpad(padBuffer, k);
831 832 833 834 835 836 837
                    k -= actualPadLen;
                    outArray = padBuffer;
                    outOfs = 0;
                } else {
                    k = token.p11.C_DecryptFinal(session.id(),
                            outAddr, outArray, outOfs, outLen);
                }
D
duke 已提交
838
            }
839 840 841
            if ((!encrypt && paddingObj != null) ||
                    (!(outBuffer instanceof DirectBuffer) &&
                    !outBuffer.hasArray())) {
D
duke 已提交
842 843 844 845 846 847 848 849 850
                outBuffer.put(outArray, outOfs, k);
            } else {
                outBuffer.position(outBuffer.position() + k);
            }
            return k;
        } catch (PKCS11Exception e) {
            handleException(e);
            throw new ProviderException("doFinal() failed", e);
        } finally {
851
            reset();
D
duke 已提交
852 853 854 855
        }
    }

    private void handleException(PKCS11Exception e)
856
            throws ShortBufferException, IllegalBlockSizeException {
D
duke 已提交
857
        long errorCode = e.getErrorCode();
858 859 860
        if (errorCode == CKR_BUFFER_TOO_SMALL) {
            throw (ShortBufferException)
                    (new ShortBufferException().initCause(e));
861 862
        } else if (errorCode == CKR_DATA_LEN_RANGE ||
                   errorCode == CKR_ENCRYPTED_DATA_LEN_RANGE) {
863 864
            throw (IllegalBlockSizeException)
                    (new IllegalBlockSizeException(e.toString()).initCause(e));
D
duke 已提交
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
        }
    }

    // see JCE spec
    protected byte[] engineWrap(Key key) throws IllegalBlockSizeException,
            InvalidKeyException {
        // XXX key wrapping
        throw new UnsupportedOperationException("engineWrap()");
    }

    // see JCE spec
    protected Key engineUnwrap(byte[] wrappedKey, String wrappedKeyAlgorithm,
            int wrappedKeyType)
            throws InvalidKeyException, NoSuchAlgorithmException {
        // XXX key unwrapping
        throw new UnsupportedOperationException("engineUnwrap()");
    }

    // see JCE spec
884
    @Override
D
duke 已提交
885 886
    protected int engineGetKeySize(Key key) throws InvalidKeyException {
        int n = P11SecretKeyFactory.convertKey
887
                (token, key, keyAlgorithm).length();
D
duke 已提交
888 889 890
        return n;
    }

891 892 893 894 895 896 897 898 899 900 901
    private final void bufferInputBytes(byte[] in, int inOfs, int len) {
        System.arraycopy(in, inOfs, padBuffer, padBufferLen, len);
        padBufferLen += len;
        bytesBuffered += len;
    }

    private final void bufferInputBytes(ByteBuffer inBuffer, int len) {
        inBuffer.get(padBuffer, padBufferLen, len);
        padBufferLen += len;
        bytesBuffered += len;
    }
D
duke 已提交
902
}