RSASignature.java 16.7 KB
Newer Older
D
duke 已提交
1
/*
C
coffeys 已提交
2
 * Copyright (c) 2005, 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 32
 */

package sun.security.mscapi;

import java.nio.ByteBuffer;
import java.security.PublicKey;
import java.security.PrivateKey;
import java.security.InvalidKeyException;
import java.security.InvalidParameterException;
33
import java.security.KeyStoreException;
D
duke 已提交
34 35 36 37
import java.security.NoSuchAlgorithmException;
import java.security.ProviderException;
import java.security.MessageDigest;
import java.security.SignatureException;
38 39 40
import java.math.BigInteger;

import sun.security.rsa.RSAKeyFactory;
D
duke 已提交
41 42 43 44 45 46 47

/**
 * RSA signature implementation. Supports RSA signing using PKCS#1 v1.5 padding.
 *
 * Objects should be instantiated by calling Signature.getInstance() using the
 * following algorithm names:
 *
48
 *  . "NONEwithRSA"
D
duke 已提交
49
 *  . "SHA1withRSA"
50 51 52
 *  . "SHA256withRSA"
 *  . "SHA384withRSA"
 *  . "SHA512withRSA"
D
duke 已提交
53 54 55
 *  . "MD5withRSA"
 *  . "MD2withRSA"
 *
56 57 58 59
 * NOTE: RSA keys must be at least 512 bits long.
 *
 * NOTE: NONEwithRSA must be supplied with a pre-computed message digest.
 *       Only the following digest algorithms are supported: MD5, SHA-1,
60
 *       SHA-256, SHA-384, SHA-512 and a special-purpose digest
V
valeriep 已提交
61
 *       algorithm which is a concatenation of SHA-1 and MD5 digests.
D
duke 已提交
62 63 64 65 66 67 68 69 70
 *
 * @since   1.6
 * @author  Stanley Man-Kit Ho
 */
abstract class RSASignature extends java.security.SignatureSpi
{
    // message digest implementation we use
    private final MessageDigest messageDigest;

71
    // message digest name
72
    private String messageDigestAlgorithm;
73 74

    // flag indicating whether the digest has been reset
D
duke 已提交
75 76 77 78 79 80 81 82
    private boolean needsReset;

    // the signing key
    private Key privateKey = null;

    // the verification key
    private Key publicKey = null;

83 84 85 86 87 88 89
    /**
     * Constructs a new RSASignature. Used by Raw subclass.
     */
    RSASignature() {
        messageDigest = null;
        messageDigestAlgorithm = null;
    }
D
duke 已提交
90

91 92 93
    /**
     * Constructs a new RSASignature. Used by subclasses.
     */
D
duke 已提交
94 95 96 97
    RSASignature(String digestName) {

        try {
            messageDigest = MessageDigest.getInstance(digestName);
98 99
            // Get the digest's canonical name
            messageDigestAlgorithm = messageDigest.getAlgorithm();
D
duke 已提交
100 101 102 103 104 105 106 107

        } catch (NoSuchAlgorithmException e) {
           throw new ProviderException(e);
        }

        needsReset = false;
    }

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
    // Nested class for NONEwithRSA signatures
    public static final class Raw extends RSASignature {

        // the longest supported digest is 512 bits (SHA-512)
        private static final int RAW_RSA_MAX = 64;

        private final byte[] precomputedDigest;
        private int offset = 0;

        public Raw() {
            precomputedDigest = new byte[RAW_RSA_MAX];
        }

        // Stores the precomputed message digest value.
        @Override
        protected void engineUpdate(byte b) throws SignatureException {
            if (offset >= precomputedDigest.length) {
                offset = RAW_RSA_MAX + 1;
                return;
            }
            precomputedDigest[offset++] = b;
        }

        // Stores the precomputed message digest value.
        @Override
        protected void engineUpdate(byte[] b, int off, int len)
                throws SignatureException {
C
coffeys 已提交
135
            if (len > (precomputedDigest.length - offset)) {
136 137 138 139 140 141 142 143 144 145 146 147 148 149
                offset = RAW_RSA_MAX + 1;
                return;
            }
            System.arraycopy(b, off, precomputedDigest, offset, len);
            offset += len;
        }

        // Stores the precomputed message digest value.
        @Override
        protected void engineUpdate(ByteBuffer byteBuffer) {
            int len = byteBuffer.remaining();
            if (len <= 0) {
                return;
            }
C
coffeys 已提交
150
            if (len > (precomputedDigest.length - offset)) {
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
                offset = RAW_RSA_MAX + 1;
                return;
            }
            byteBuffer.get(precomputedDigest, offset, len);
            offset += len;
        }

        @Override
        protected void resetDigest(){
            offset = 0;
        }

        // Returns the precomputed message digest value.
        @Override
        protected byte[] getDigestValue() throws SignatureException {
            if (offset > RAW_RSA_MAX) {
                throw new SignatureException("Message digest is too long");
            }

            // Determine the digest algorithm from the digest length
            if (offset == 20) {
                setDigestName("SHA1");
            } else if (offset == 36) {
                setDigestName("SHA1+MD5");
            } else if (offset == 32) {
                setDigestName("SHA-256");
            } else if (offset == 48) {
                setDigestName("SHA-384");
            } else if (offset == 64) {
                setDigestName("SHA-512");
            } else if (offset == 16) {
                setDigestName("MD5");
            } else {
                throw new SignatureException(
                    "Message digest length is not supported");
            }

            byte[] result = new byte[offset];
            System.arraycopy(precomputedDigest, 0, result, 0, offset);
            offset = 0;

            return result;
        }
    }

D
duke 已提交
196 197 198 199 200 201
    public static final class SHA1 extends RSASignature {
        public SHA1() {
            super("SHA1");
        }
    }

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    public static final class SHA256 extends RSASignature {
        public SHA256() {
            super("SHA-256");
        }
    }

    public static final class SHA384 extends RSASignature {
        public SHA384() {
            super("SHA-384");
        }
    }

    public static final class SHA512 extends RSASignature {
        public SHA512() {
            super("SHA-512");
        }
    }

D
duke 已提交
220 221 222 223 224 225 226 227 228 229 230 231
    public static final class MD5 extends RSASignature {
        public MD5() {
            super("MD5");
        }
    }

    public static final class MD2 extends RSASignature {
        public MD2() {
            super("MD2");
        }
    }

232
    // initialize for signing. See JCA doc
D
duke 已提交
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    protected void engineInitVerify(PublicKey key)
        throws InvalidKeyException
    {
        // This signature accepts only RSAPublicKey
        if ((key instanceof java.security.interfaces.RSAPublicKey) == false) {
            throw new InvalidKeyException("Key type not supported");
        }

        java.security.interfaces.RSAPublicKey rsaKey =
            (java.security.interfaces.RSAPublicKey) key;

        if ((key instanceof sun.security.mscapi.RSAPublicKey) == false) {

            // convert key to MSCAPI format

248 249 250 251 252 253 254 255 256 257
            BigInteger modulus = rsaKey.getModulus();
            BigInteger exponent =  rsaKey.getPublicExponent();

            // Check against the local and global values to make sure
            // the sizes are ok.  Round up to the nearest byte.
            RSAKeyFactory.checkKeyLengths(((modulus.bitLength() + 7) & ~7),
                exponent, -1, RSAKeyPairGenerator.KEY_SIZE_MAX);

            byte[] modulusBytes = modulus.toByteArray();
            byte[] exponentBytes = exponent.toByteArray();
D
duke 已提交
258 259 260 261 262 263 264

            // Adjust key length due to sign bit
            int keyBitLength = (modulusBytes[0] == 0)
                ? (modulusBytes.length - 1) * 8
                : modulusBytes.length * 8;

            byte[] keyBlob = generatePublicKeyBlob(
265
                keyBitLength, modulusBytes, exponentBytes);
D
duke 已提交
266

267 268 269 270 271 272
            try {
                publicKey = importPublicKey(keyBlob, keyBitLength);

            } catch (KeyStoreException e) {
                throw new InvalidKeyException(e);
            }
D
duke 已提交
273 274 275 276 277

        } else {
            publicKey = (sun.security.mscapi.RSAPublicKey) key;
        }

278 279
        this.privateKey = null;
        resetDigest();
D
duke 已提交
280 281
    }

282 283
    // initialize for signing. See JCA doc
    protected void engineInitSign(PrivateKey key) throws InvalidKeyException
D
duke 已提交
284 285 286 287 288 289 290
    {
        // This signature accepts only RSAPrivateKey
        if ((key instanceof sun.security.mscapi.RSAPrivateKey) == false) {
            throw new InvalidKeyException("Key type not supported");
        }
        privateKey = (sun.security.mscapi.RSAPrivateKey) key;

291 292
        // Check against the local and global values to make sure
        // the sizes are ok.  Round up to nearest byte.
293
        RSAKeyFactory.checkKeyLengths(((privateKey.length() + 7) & ~7),
294 295
            null, RSAKeyPairGenerator.KEY_SIZE_MIN,
            RSAKeyPairGenerator.KEY_SIZE_MAX);
D
duke 已提交
296

297 298 299 300 301 302 303
        this.publicKey = null;
        resetDigest();
    }

    /**
     * Resets the message digest if needed.
     */
304
    protected void resetDigest() {
D
duke 已提交
305 306 307 308 309 310
        if (needsReset) {
            messageDigest.reset();
            needsReset = false;
        }
    }

311
    protected byte[] getDigestValue() throws SignatureException {
312 313 314 315
        needsReset = false;
        return messageDigest.digest();
    }

316 317 318 319
    protected void setDigestName(String name) {
        messageDigestAlgorithm = name;
    }

D
duke 已提交
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 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
    /**
     * Updates the data to be signed or verified
     * using the specified byte.
     *
     * @param b the byte to use for the update.
     *
     * @exception SignatureException if the engine is not initialized
     * properly.
     */
    protected void engineUpdate(byte b) throws SignatureException
    {
        messageDigest.update(b);
        needsReset = true;
    }

    /**
     * Updates the data to be signed or verified, using the
     * specified array of bytes, starting at the specified offset.
     *
     * @param b the array of bytes
     * @param off the offset to start from in the array of bytes
     * @param len the number of bytes to use, starting at offset
     *
     * @exception SignatureException if the engine is not initialized
     * properly
     */
    protected void engineUpdate(byte[] b, int off, int len)
        throws SignatureException
    {
        messageDigest.update(b, off, len);
        needsReset = true;
    }

    /**
     * Updates the data to be signed or verified, using the
     * specified ByteBuffer.
     *
     * @param input the ByteBuffer
     */
    protected void engineUpdate(ByteBuffer input)
    {
        messageDigest.update(input);
        needsReset = true;
    }

    /**
     * Returns the signature bytes of all the data
     * updated so far.
     * The format of the signature depends on the underlying
     * signature scheme.
     *
     * @return the signature bytes of the signing operation's result.
     *
     * @exception SignatureException if the engine is not
     * initialized properly or if this signature algorithm is unable to
     * process the input data provided.
     */
    protected byte[] engineSign() throws SignatureException {

379
        byte[] hash = getDigestValue();
D
duke 已提交
380

381 382 383
        // Omit the hash OID when generating a Raw signature
        boolean noHashOID = this instanceof Raw;

D
duke 已提交
384 385
        // Sign hash using MS Crypto APIs

386
        byte[] result = signHash(noHashOID, hash, hash.length,
387
            messageDigestAlgorithm, privateKey.getHCryptProvider(),
D
duke 已提交
388 389 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
            privateKey.getHCryptKey());

        // Convert signature array from little endian to big endian
        return convertEndianArray(result);
    }

    /**
     * Convert array from big endian to little endian, or vice versa.
     */
    private byte[] convertEndianArray(byte[] byteArray)
    {
        if (byteArray == null || byteArray.length == 0)
            return byteArray;

        byte [] retval = new byte[byteArray.length];

        // make it big endian
        for (int i=0;i < byteArray.length;i++)
            retval[i] = byteArray[byteArray.length - i - 1];

        return retval;
    }

    /**
     * Sign hash using Microsoft Crypto API with HCRYPTKEY.
     * The returned data is in little-endian.
     */
415 416
    private native static byte[] signHash(boolean noHashOID, byte[] hash,
        int hashSize, String hashAlgorithm, long hCryptProv, long hCryptKey)
D
duke 已提交
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
            throws SignatureException;

    /**
     * Verify a signed hash using Microsoft Crypto API with HCRYPTKEY.
     */
    private native static boolean verifySignedHash(byte[] hash, int hashSize,
        String hashAlgorithm, byte[] signature, int signatureSize,
        long hCryptProv, long hCryptKey) throws SignatureException;

    /**
     * Verifies the passed-in signature.
     *
     * @param sigBytes the signature bytes to be verified.
     *
     * @return true if the signature was verified, false if not.
     *
     * @exception SignatureException if the engine is not
     * initialized properly, the passed-in signature is improperly
     * encoded or of the wrong type, if this signature algorithm is unable to
     * process the input data provided, etc.
     */
    protected boolean engineVerify(byte[] sigBytes)
        throws SignatureException
    {
441
        byte[] hash = getDigestValue();
D
duke 已提交
442 443

        return verifySignedHash(hash, hash.length,
444
            messageDigestAlgorithm, convertEndianArray(sigBytes),
D
duke 已提交
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
            sigBytes.length, publicKey.getHCryptProvider(),
            publicKey.getHCryptKey());
    }

    /**
     * Sets the specified algorithm parameter to the specified
     * value. This method supplies a general-purpose mechanism through
     * which it is possible to set the various parameters of this object.
     * A parameter may be any settable parameter for the algorithm, such as
     * a parameter size, or a source of random bits for signature generation
     * (if appropriate), or an indication of whether or not to perform
     * a specific but optional computation. A uniform algorithm-specific
     * naming scheme for each parameter is desirable but left unspecified
     * at this time.
     *
     * @param param the string identifier of the parameter.
     *
     * @param value the parameter value.
     *
     * @exception InvalidParameterException if <code>param</code> is an
     * invalid parameter for this signature algorithm engine,
     * the parameter is already set
     * and cannot be set again, a security exception occurs, and so on.
     *
     * @deprecated Replaced by {@link
     * #engineSetParameter(java.security.spec.AlgorithmParameterSpec)
     * engineSetParameter}.
     */
473
    @Deprecated
D
duke 已提交
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    protected void engineSetParameter(String param, Object value)
        throws InvalidParameterException
    {
        throw new InvalidParameterException("Parameter not supported");
    }


    /**
     * Gets the value of the specified algorithm parameter.
     * This method supplies a general-purpose mechanism through which it
     * is possible to get the various parameters of this object. A parameter
     * may be any settable parameter for the algorithm, such as a parameter
     * size, or  a source of random bits for signature generation (if
     * appropriate), or an indication of whether or not to perform a
     * specific but optional computation. A uniform algorithm-specific
     * naming scheme for each parameter is desirable but left unspecified
     * at this time.
     *
     * @param param the string name of the parameter.
     *
     * @return the object that represents the parameter value, or null if
     * there is none.
     *
     * @exception InvalidParameterException if <code>param</code> is an
     * invalid parameter for this engine, or another exception occurs while
     * trying to get this parameter.
     *
     * @deprecated
     */
503
    @Deprecated
D
duke 已提交
504 505 506 507 508 509 510 511 512
    protected Object engineGetParameter(String param)
        throws InvalidParameterException
    {
        throw new InvalidParameterException("Parameter not supported");
    }

    /**
     * Generates a public-key BLOB from a key's components.
     */
513 514
    // used by RSACipher
    static native byte[] generatePublicKeyBlob(
515 516
        int keyBitLength, byte[] modulus, byte[] publicExponent)
            throws InvalidKeyException;
D
duke 已提交
517 518 519 520

    /**
     * Imports a public-key BLOB.
     */
521
    // used by RSACipher
522 523
    static native RSAPublicKey importPublicKey(byte[] keyBlob, int keySize)
        throws KeyStoreException;
D
duke 已提交
524
}