P11RSACipher.java 25.5 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2003, 2018, 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 28 29 30 31
 */

package sun.security.pkcs11;

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

32 33
import java.util.Locale;

D
duke 已提交
34 35 36 37 38 39
import javax.crypto.*;
import javax.crypto.spec.*;

import static sun.security.pkcs11.TemplateManager.*;
import sun.security.pkcs11.wrapper.*;
import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
40 41
import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec;
import sun.security.util.KeyUtil;
D
duke 已提交
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

/**
 * RSA Cipher implementation class. We currently only support
 * PKCS#1 v1.5 padding on top of CKM_RSA_PKCS.
 *
 * @author  Andreas Sterbenz
 * @since   1.5
 */
final class P11RSACipher extends CipherSpi {

    // minimum length of PKCS#1 v1.5 padding
    private final static int PKCS1_MIN_PADDING_LENGTH = 11;

    // constant byte[] of length 0
    private final static byte[] B0 = new byte[0];

    // mode constant for public key encryption
    private final static int MODE_ENCRYPT = 1;
    // mode constant for private key decryption
    private final static int MODE_DECRYPT = 2;
    // mode constant for private key encryption (signing)
    private final static int MODE_SIGN    = 3;
    // mode constant for public key decryption (verifying)
    private final static int MODE_VERIFY  = 4;

67 68 69 70 71
    // padding type constant for NoPadding
    private final static int PAD_NONE = 1;
    // padding type constant for PKCS1Padding
    private final static int PAD_PKCS1 = 2;

D
duke 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    // token instance
    private final Token token;

    // algorithm name (always "RSA")
    private final String algorithm;

    // mechanism id
    private final long mechanism;

    // associated session, if any
    private Session session;

    // mode, one of MODE_* above
    private int mode;

87 88 89
    // padding, one of PAD_* above
    private int padType;

D
duke 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    private byte[] buffer;
    private int bufOfs;

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

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

    // maximum input data size allowed
    // for decryption, this is the length of the key
    // for encryption, length of the key minus minimum padding length
    private int maxInputSize;

    // maximum output size. this is the length of the key
    private int outputSize;

107 108 109 110 111 112
    // cipher parameter for TLS RSA premaster secret
    private AlgorithmParameterSpec spec = null;

    // the source of randomness
    private SecureRandom random;

D
duke 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    P11RSACipher(Token token, String algorithm, long mechanism)
            throws PKCS11Exception {
        super();
        this.token = token;
        this.algorithm = "RSA";
        this.mechanism = mechanism;
    }

    // modes do not make sense for RSA, but allow ECB
    // see JCE spec
    protected void engineSetMode(String mode) throws NoSuchAlgorithmException {
        if (mode.equalsIgnoreCase("ECB") == false) {
            throw new NoSuchAlgorithmException("Unsupported mode " + mode);
        }
    }

    protected void engineSetPadding(String padding)
            throws NoSuchPaddingException {
131
        String lowerPadding = padding.toLowerCase(Locale.ENGLISH);
132 133 134 135
        if (lowerPadding.equals("pkcs1padding")) {
            padType = PAD_PKCS1;
        } else if (lowerPadding.equals("nopadding")) {
            padType = PAD_NONE;
D
duke 已提交
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
        } else {
            throw new NoSuchPaddingException("Unsupported padding " + padding);
        }
    }

    // return 0 as block size, we are not a block cipher
    // see JCE spec
    protected int engineGetBlockSize() {
        return 0;
    }

    // return the output size
    // see JCE spec
    protected int engineGetOutputSize(int inputLen) {
        return outputSize;
    }

    // no IV, return null
    // see JCE spec
    protected byte[] engineGetIV() {
        return null;
    }

    // no parameters, return null
    // see JCE spec
    protected AlgorithmParameters engineGetParameters() {
        return null;
    }

    // see JCE spec
    protected void engineInit(int opmode, Key key, SecureRandom random)
            throws InvalidKeyException {
        implInit(opmode, key);
    }

    // see JCE spec
    protected void engineInit(int opmode, Key key,
            AlgorithmParameterSpec params, SecureRandom random)
            throws InvalidKeyException, InvalidAlgorithmParameterException {
        if (params != null) {
176 177 178 179 180 181
            if (!(params instanceof TlsRsaPremasterSecretParameterSpec)) {
                throw new InvalidAlgorithmParameterException(
                        "Parameters not supported");
            }
            spec = params;
            this.random = random;   // for TLS RSA premaster secret
D
duke 已提交
182 183 184 185 186 187 188 189 190
        }
        implInit(opmode, key);
    }

    // see JCE spec
    protected void engineInit(int opmode, Key key, AlgorithmParameters params,
            SecureRandom random)
            throws InvalidKeyException, InvalidAlgorithmParameterException {
        if (params != null) {
191 192
            throw new InvalidAlgorithmParameterException(
                        "Parameters not supported");
D
duke 已提交
193 194 195 196 197
        }
        implInit(opmode, key);
    }

    private void implInit(int opmode, Key key) throws InvalidKeyException {
198
        reset(true);
D
duke 已提交
199 200 201 202 203 204 205 206 207 208 209
        p11Key = P11KeyFactory.convertKey(token, key, algorithm);
        boolean encrypt;
        if (opmode == Cipher.ENCRYPT_MODE) {
            encrypt = true;
        } else if (opmode == Cipher.DECRYPT_MODE) {
            encrypt = false;
        } else if (opmode == Cipher.WRAP_MODE) {
            if (p11Key.isPublic() == false) {
                throw new InvalidKeyException
                                ("Wrap has to be used with public keys");
            }
210 211
            // No further setup needed for C_Wrap(). We'll initialize later if
            // we can't use C_Wrap().
D
duke 已提交
212 213 214 215 216 217
            return;
        } else if (opmode == Cipher.UNWRAP_MODE) {
            if (p11Key.isPrivate() == false) {
                throw new InvalidKeyException
                                ("Unwrap has to be used with private keys");
            }
218 219 220
            // No further setup needed for C_Unwrap(). We'll initialize later
            // if we can't use C_Unwrap().
            return;
D
duke 已提交
221 222 223 224 225 226 227 228 229 230
        } else {
            throw new InvalidKeyException("Unsupported mode: " + opmode);
        }
        if (p11Key.isPublic()) {
            mode = encrypt ? MODE_ENCRYPT : MODE_VERIFY;
        } else if (p11Key.isPrivate()) {
            mode = encrypt ? MODE_SIGN : MODE_DECRYPT;
        } else {
            throw new InvalidKeyException("Unknown key type: " + p11Key);
        }
231
        int n = (p11Key.length() + 7) >> 3;
D
duke 已提交
232 233
        outputSize = n;
        buffer = new byte[n];
234 235
        maxInputSize = ((padType == PAD_PKCS1 && encrypt) ?
                            (n - PKCS1_MIN_PADDING_LENGTH) : n);
D
duke 已提交
236 237 238 239 240 241 242
        try {
            initialize();
        } catch (PKCS11Exception e) {
            throw new InvalidKeyException("init() failed", e);
        }
    }

243 244 245
    // reset the states to the pre-initialized values
    private void reset(boolean doCancel) {
        if (!initialized) {
D
duke 已提交
246 247 248
            return;
        }
        initialized = false;
249 250 251 252 253 254 255 256 257 258
        try {
            if (session == null) {
                return;
            }
            if (doCancel && token.explicitCancel) {
                cancelOperation();
            }
        } finally {
            p11Key.releaseKeyID();
            session = token.releaseSession(session);
D
duke 已提交
259
        }
260 261 262 263 264 265
    }

    // should only called by reset as this method does not update other
    // state variables such as "initialized"
    private void cancelOperation() {
        token.ensureValid();
D
duke 已提交
266 267 268
        if (session.hasObjects() == false) {
            session = token.killSession(session);
            return;
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
        } else {
            try {
                PKCS11 p11 = token.p11;
                int inLen = maxInputSize;
                int outLen = buffer.length;
                long sessId = session.id();
                switch (mode) {
                case MODE_ENCRYPT:
                    p11.C_Encrypt(sessId, buffer, 0, inLen, buffer, 0, outLen);
                    break;
                case MODE_DECRYPT:
                    p11.C_Decrypt(sessId, buffer, 0, inLen, buffer, 0, outLen);
                    break;
                case MODE_SIGN:
                    byte[] tmpBuffer = new byte[maxInputSize];
                    p11.C_Sign(sessId, tmpBuffer);
                    break;
                case MODE_VERIFY:
                    p11.C_VerifyRecover(sessId, buffer, 0, inLen, buffer,
                            0, outLen);
                    break;
                default:
                    throw new ProviderException("internal error");
                }
            } catch (PKCS11Exception e) {
                // XXX ensure this always works, ignore error
            }
        }
    }

    private void ensureInitialized() throws PKCS11Exception {
        token.ensureValid();
        if (!initialized) {
            initialize();
        }
    }

    private void initialize() throws PKCS11Exception {
        if (p11Key == null) {
            throw new ProviderException(
                    "Operation cannot be performed without " +
                    "calling engineInit first");
D
duke 已提交
311
        }
312
        long keyID = p11Key.getKeyID();
D
duke 已提交
313
        try {
314 315 316
            if (session == null) {
                session = token.getOpSession();
            }
D
duke 已提交
317
            PKCS11 p11 = token.p11;
318
            CK_MECHANISM ckMechanism = new CK_MECHANISM(mechanism);
D
duke 已提交
319 320
            switch (mode) {
            case MODE_ENCRYPT:
321
                p11.C_EncryptInit(session.id(), ckMechanism, keyID);
D
duke 已提交
322 323
                break;
            case MODE_DECRYPT:
324
                p11.C_DecryptInit(session.id(), ckMechanism, keyID);
D
duke 已提交
325 326
                break;
            case MODE_SIGN:
327
                p11.C_SignInit(session.id(), ckMechanism, keyID);
D
duke 已提交
328 329
                break;
            case MODE_VERIFY:
330
                p11.C_VerifyRecoverInit(session.id(), ckMechanism, keyID);
D
duke 已提交
331 332
                break;
            default:
333
                throw new AssertionError("internal error");
D
duke 已提交
334
            }
335 336
            bufOfs = 0;
            initialized = true;
D
duke 已提交
337
        } catch (PKCS11Exception e) {
338 339 340
            p11Key.releaseKeyID();
            session = token.releaseSession(session);
            throw e;
D
duke 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
        }
    }

    private void implUpdate(byte[] in, int inOfs, int inLen) {
        try {
            ensureInitialized();
        } catch (PKCS11Exception e) {
            throw new ProviderException("update() failed", e);
        }
        if ((inLen == 0) || (in == null)) {
            return;
        }
        if (bufOfs + inLen > maxInputSize) {
            bufOfs = maxInputSize + 1;
            return;
        }
        System.arraycopy(in, inOfs, buffer, bufOfs, inLen);
        bufOfs += inLen;
    }

    private int implDoFinal(byte[] out, int outOfs, int outLen)
            throws BadPaddingException, IllegalBlockSizeException {
        if (bufOfs > maxInputSize) {
            throw new IllegalBlockSizeException("Data must not be longer "
                + "than " + maxInputSize + " bytes");
        }
        try {
            ensureInitialized();
            PKCS11 p11 = token.p11;
            int n;
            switch (mode) {
            case MODE_ENCRYPT:
                n = p11.C_Encrypt
                        (session.id(), buffer, 0, bufOfs, out, outOfs, outLen);
                break;
            case MODE_DECRYPT:
                n = p11.C_Decrypt
                        (session.id(), buffer, 0, bufOfs, out, outOfs, outLen);
                break;
            case MODE_SIGN:
                byte[] tmpBuffer = new byte[bufOfs];
                System.arraycopy(buffer, 0, tmpBuffer, 0, bufOfs);
                tmpBuffer = p11.C_Sign(session.id(), tmpBuffer);
                if (tmpBuffer.length > outLen) {
385 386 387
                    throw new BadPaddingException(
                        "Output buffer (" + outLen + ") is too small to " +
                        "hold the produced data (" + tmpBuffer.length + ")");
D
duke 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
                }
                System.arraycopy(tmpBuffer, 0, out, outOfs, tmpBuffer.length);
                n = tmpBuffer.length;
                break;
            case MODE_VERIFY:
                n = p11.C_VerifyRecover
                        (session.id(), buffer, 0, bufOfs, out, outOfs, outLen);
                break;
            default:
                throw new ProviderException("internal error");
            }
            return n;
        } catch (PKCS11Exception e) {
            throw (BadPaddingException)new BadPaddingException
                ("doFinal() failed").initCause(e);
        } finally {
404
            reset(false);
D
duke 已提交
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
        }
    }

    // see JCE spec
    protected byte[] engineUpdate(byte[] in, int inOfs, int inLen) {
        implUpdate(in, inOfs, inLen);
        return B0;
    }

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

    // see JCE spec
    protected byte[] engineDoFinal(byte[] in, int inOfs, int inLen)
            throws IllegalBlockSizeException, BadPaddingException {
        implUpdate(in, inOfs, inLen);
        int n = implDoFinal(buffer, 0, buffer.length);
        byte[] out = new byte[n];
        System.arraycopy(buffer, 0, out, 0, n);
        return out;
    }

    // see JCE spec
    protected int engineDoFinal(byte[] in, int inOfs, int inLen,
            byte[] out, int outOfs) throws ShortBufferException,
            IllegalBlockSizeException, BadPaddingException {
        implUpdate(in, inOfs, inLen);
        return implDoFinal(out, outOfs, out.length - outOfs);
    }

439 440
    private byte[] doFinal() throws BadPaddingException,
            IllegalBlockSizeException {
D
duke 已提交
441 442 443 444 445 446 447 448 449 450 451
        byte[] t = new byte[2048];
        int n = implDoFinal(t, 0, t.length);
        byte[] out = new byte[n];
        System.arraycopy(t, 0, out, 0, n);
        return out;
    }

    // see JCE spec
    protected byte[] engineWrap(Key key) throws InvalidKeyException,
            IllegalBlockSizeException {
        String keyAlg = key.getAlgorithm();
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
        P11Key sKey = null;
        try {
            // The conversion may fail, e.g. trying to wrap an AES key on
            // a token that does not support AES, or when the key size is
            // not within the range supported by the token.
            sKey = P11SecretKeyFactory.convertKey(token, key, keyAlg);
        } catch (InvalidKeyException ike) {
            byte[] toBeWrappedKey = key.getEncoded();
            if (toBeWrappedKey == null) {
                throw new InvalidKeyException
                        ("wrap() failed, no encoding available", ike);
            }
            // Directly encrypt the key encoding when key conversion failed
            implInit(Cipher.ENCRYPT_MODE, p11Key);
            implUpdate(toBeWrappedKey, 0, toBeWrappedKey.length);
            try {
                return doFinal();
            } catch (BadPaddingException bpe) {
                // should not occur
                throw new InvalidKeyException("wrap() failed", bpe);
            } finally {
                // Restore original mode
                implInit(Cipher.WRAP_MODE, p11Key);
            }
        }
D
duke 已提交
477
        Session s = null;
478 479
        long p11KeyID = p11Key.getKeyID();
        long sKeyID = sKey.getKeyID();
D
duke 已提交
480 481
        try {
            s = token.getOpSession();
482
            return token.p11.C_WrapKey(s.id(), new CK_MECHANISM(mechanism),
483
                    p11KeyID, sKeyID);
D
duke 已提交
484 485 486
        } catch (PKCS11Exception e) {
            throw new InvalidKeyException("wrap() failed", e);
        } finally {
487 488
            p11Key.releaseKeyID();
            sKey.releaseKeyID();
D
duke 已提交
489 490 491 492 493 494 495
            token.releaseSession(s);
        }
    }

    // see JCE spec
    protected Key engineUnwrap(byte[] wrappedKey, String algorithm,
            int type) throws InvalidKeyException, NoSuchAlgorithmException {
X
xuelei 已提交
496

497 498 499 500 501 502 503 504 505
        boolean isTlsRsaPremasterSecret =
                algorithm.equals("TlsRsaPremasterSecret");
        Exception failover = null;

        // Should C_Unwrap be preferred for non-TLS RSA premaster secret?
        if (token.supportsRawSecretKeyImport()) {
            // XXX implement unwrap using C_Unwrap() for all keys
            implInit(Cipher.DECRYPT_MODE, p11Key);
            try {
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
                if (wrappedKey.length > maxInputSize) {
                    throw new InvalidKeyException("Key is too long for unwrapping");
                }

                byte[] encoded = null;
                implUpdate(wrappedKey, 0, wrappedKey.length);
                try {
                    encoded = doFinal();
                } catch (BadPaddingException e) {
                    if (isTlsRsaPremasterSecret) {
                        failover = e;
                    } else {
                        throw new InvalidKeyException("Unwrapping failed", e);
                    }
                } catch (IllegalBlockSizeException e) {
                    // should not occur, handled with length check above
522 523 524
                    throw new InvalidKeyException("Unwrapping failed", e);
                }

525 526 527 528 529 530 531 532 533 534 535 536
                if (isTlsRsaPremasterSecret) {
                    if (!(spec instanceof TlsRsaPremasterSecretParameterSpec)) {
                        throw new IllegalStateException(
                                "No TlsRsaPremasterSecretParameterSpec specified");
                    }

                    // polish the TLS premaster secret
                    TlsRsaPremasterSecretParameterSpec psps =
                            (TlsRsaPremasterSecretParameterSpec)spec;
                    encoded = KeyUtil.checkTlsPreMasterSecretKey(
                            psps.getClientVersion(), psps.getServerVersion(),
                            random, encoded, (failover != null));
537 538
                }

539 540 541 542
                return ConstructKeys.constructKey(encoded, algorithm, type);
            } finally {
                // Restore original mode
                implInit(Cipher.UNWRAP_MODE, p11Key);
543 544 545 546
            }
        } else {
            Session s = null;
            SecretKey secretKey = null;
547
            long p11KeyID = p11Key.getKeyID();
548 549 550 551 552 553 554 555 556 557
            try {
                try {
                    s = token.getObjSession();
                    long keyType = CKK_GENERIC_SECRET;
                    CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[] {
                            new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY),
                            new CK_ATTRIBUTE(CKA_KEY_TYPE, keyType),
                        };
                    attributes = token.getAttributes(
                            O_IMPORT, CKO_SECRET_KEY, keyType, attributes);
558

559
                    long keyID = token.p11.C_UnwrapKey(s.id(),
560 561
                                    new CK_MECHANISM(mechanism), p11KeyID,
                                    wrappedKey, attributes);
562 563 564 565 566 567 568 569 570 571 572 573 574 575
                    secretKey = P11Key.secretKey(s, keyID,
                            algorithm, 48 << 3, attributes);
                } catch (PKCS11Exception e) {
                    if (isTlsRsaPremasterSecret) {
                        failover = e;
                    } else {
                        throw new InvalidKeyException("unwrap() failed", e);
                    }
                }

                if (isTlsRsaPremasterSecret) {
                    TlsRsaPremasterSecretParameterSpec psps =
                            (TlsRsaPremasterSecretParameterSpec)spec;

576 577
                    // Please use the tricky failover as the parameter so that
                    // smart compiler won't dispose the unused variable.
578
                    secretKey = polishPreMasterSecretKey(token, s,
579
                            failover, secretKey,
580 581 582 583 584
                            psps.getClientVersion(), psps.getServerVersion());
                }

                return secretKey;
            } finally {
585
                p11Key.releaseKeyID();
586 587
                token.releaseSession(s);
            }
D
duke 已提交
588 589 590 591 592
        }
    }

    // see JCE spec
    protected int engineGetKeySize(Key key) throws InvalidKeyException {
593
        int n = P11KeyFactory.convertKey(token, key, algorithm).length();
D
duke 已提交
594 595
        return n;
    }
596 597 598

    private static SecretKey polishPreMasterSecretKey(
            Token token, Session session,
599
            Exception failover, SecretKey unwrappedKey,
600 601
            int clientVersion, int serverVersion) {

602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
        SecretKey newKey;
        CK_VERSION version = new CK_VERSION(
                (clientVersion >>> 8) & 0xFF, clientVersion & 0xFF);
        try {
            CK_ATTRIBUTE[] attributes = token.getAttributes(
                    O_GENERATE, CKO_SECRET_KEY,
                    CKK_GENERIC_SECRET, new CK_ATTRIBUTE[0]);
            long keyID = token.p11.C_GenerateKey(session.id(),
                    new CK_MECHANISM(CKM_SSL3_PRE_MASTER_KEY_GEN, version),
                    attributes);
            newKey = P11Key.secretKey(session,
                    keyID, "TlsRsaPremasterSecret", 48 << 3, attributes);
        } catch (PKCS11Exception e) {
            throw new ProviderException(
                    "Could not generate premaster secret", e);
617 618
        }

619
        return (failover == null) ? unwrappedKey : newKey;
620 621
    }

D
duke 已提交
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 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
}

final class ConstructKeys {
    /**
     * Construct a public key from its encoding.
     *
     * @param encodedKey the encoding of a public key.
     *
     * @param encodedKeyAlgorithm the algorithm the encodedKey is for.
     *
     * @return a public key constructed from the encodedKey.
     */
    private static final PublicKey constructPublicKey(byte[] encodedKey,
            String encodedKeyAlgorithm)
            throws InvalidKeyException, NoSuchAlgorithmException {
        try {
            KeyFactory keyFactory =
                KeyFactory.getInstance(encodedKeyAlgorithm);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey);
            return keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException nsae) {
            throw new NoSuchAlgorithmException("No installed providers " +
                                               "can create keys for the " +
                                               encodedKeyAlgorithm +
                                               "algorithm", nsae);
        } catch (InvalidKeySpecException ike) {
            throw new InvalidKeyException("Cannot construct public key", ike);
        }
    }

    /**
     * Construct a private key from its encoding.
     *
     * @param encodedKey the encoding of a private key.
     *
     * @param encodedKeyAlgorithm the algorithm the wrapped key is for.
     *
     * @return a private key constructed from the encodedKey.
     */
    private static final PrivateKey constructPrivateKey(byte[] encodedKey,
            String encodedKeyAlgorithm) throws InvalidKeyException,
            NoSuchAlgorithmException {
        try {
            KeyFactory keyFactory =
                KeyFactory.getInstance(encodedKeyAlgorithm);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
            return keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException nsae) {
            throw new NoSuchAlgorithmException("No installed providers " +
                                               "can create keys for the " +
                                               encodedKeyAlgorithm +
                                               "algorithm", nsae);
        } catch (InvalidKeySpecException ike) {
            throw new InvalidKeyException("Cannot construct private key", ike);
        }
    }

    /**
     * Construct a secret key from its encoding.
     *
     * @param encodedKey the encoding of a secret key.
     *
     * @param encodedKeyAlgorithm the algorithm the secret key is for.
     *
     * @return a secret key constructed from the encodedKey.
     */
    private static final SecretKey constructSecretKey(byte[] encodedKey,
            String encodedKeyAlgorithm) {
        return new SecretKeySpec(encodedKey, encodedKeyAlgorithm);
    }

    static final Key constructKey(byte[] encoding, String keyAlgorithm,
            int keyType) throws InvalidKeyException, NoSuchAlgorithmException {
        switch (keyType) {
        case Cipher.SECRET_KEY:
            return constructSecretKey(encoding, keyAlgorithm);
        case Cipher.PRIVATE_KEY:
            return constructPrivateKey(encoding, keyAlgorithm);
        case Cipher.PUBLIC_KEY:
            return constructPublicKey(encoding, keyAlgorithm);
        default:
            throw new InvalidKeyException("Unknown keytype " + keyType);
        }
    }
}