0N/A/*
2362N/A * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage sun.security.rsa;
0N/A
0N/Aimport java.math.BigInteger;
0N/Aimport java.util.*;
0N/A
0N/Aimport java.security.*;
0N/Aimport java.security.interfaces.*;
0N/Aimport java.security.spec.*;
0N/A
0N/Aimport javax.crypto.BadPaddingException;
0N/Aimport javax.crypto.spec.PSource;
0N/Aimport javax.crypto.spec.OAEPParameterSpec;
0N/A
0N/Aimport sun.security.jca.JCAUtil;
0N/A
0N/A/**
0N/A * RSA padding and unpadding.
0N/A *
0N/A * Format of PKCS#1 v1.5 padding is:
0N/A * 0x00 | BT | PS...PS | 0x00 | data...data
0N/A * where BT is the blocktype (1 or 2). The length of the entire string
0N/A * must be the same as the size of the modulus (i.e. 128 byte for a 1024 bit
0N/A * key). Per spec, the padding string must be at least 8 bytes long. That
0N/A * leaves up to (length of key in bytes) - 11 bytes for the data.
0N/A *
0N/A * OAEP padding is a bit more complicated and has a number of options.
0N/A * We support:
0N/A * . arbitrary hash functions ('Hash' in the specification), MessageDigest
0N/A * implementation must be available
0N/A * . MGF1 as the mask generation function
0N/A * . the empty string as the default value for label L and whatever
0N/A * specified in javax.crypto.spec.OAEPParameterSpec
0N/A *
0N/A * Note: RSA keys should be at least 512 bits long
0N/A *
0N/A * @since 1.5
0N/A * @author Andreas Sterbenz
0N/A */
0N/Apublic final class RSAPadding {
0N/A
0N/A // NOTE: the constants below are embedded in the JCE RSACipher class
0N/A // file. Do not change without coordinating the update
0N/A
0N/A // PKCS#1 v1.5 padding, blocktype 1 (signing)
0N/A public final static int PAD_BLOCKTYPE_1 = 1;
0N/A // PKCS#1 v1.5 padding, blocktype 2 (encryption)
0N/A public final static int PAD_BLOCKTYPE_2 = 2;
0N/A // nopadding. Does not do anything, but allows simpler RSACipher code
0N/A public final static int PAD_NONE = 3;
0N/A // PKCS#1 v2.1 OAEP padding
0N/A public final static int PAD_OAEP_MGF1 = 4;
0N/A
0N/A // type, one of PAD_*
0N/A private final int type;
0N/A
0N/A // size of the padded block (i.e. size of the modulus)
0N/A private final int paddedSize;
0N/A
0N/A // PRNG used to generate padding bytes (PAD_BLOCKTYPE_2, PAD_OAEP_MGF1)
0N/A private SecureRandom random;
0N/A
0N/A // maximum size of the data
0N/A private final int maxDataSize;
0N/A
0N/A // OAEP: main messagedigest
0N/A private MessageDigest md;
0N/A
0N/A // OAEP: message digest for MGF1
0N/A private MessageDigest mgfMd;
0N/A
0N/A // OAEP: value of digest of data (user-supplied or zero-length) using md
0N/A private byte[] lHash;
0N/A
0N/A /**
0N/A * Get a RSAPadding instance of the specified type.
0N/A * Keys used with this padding must be paddedSize bytes long.
0N/A */
0N/A public static RSAPadding getInstance(int type, int paddedSize)
0N/A throws InvalidKeyException, InvalidAlgorithmParameterException {
0N/A return new RSAPadding(type, paddedSize, null, null);
0N/A }
0N/A
0N/A /**
0N/A * Get a RSAPadding instance of the specified type.
0N/A * Keys used with this padding must be paddedSize bytes long.
0N/A */
0N/A public static RSAPadding getInstance(int type, int paddedSize,
0N/A SecureRandom random) throws InvalidKeyException,
0N/A InvalidAlgorithmParameterException {
0N/A return new RSAPadding(type, paddedSize, random, null);
0N/A }
0N/A
0N/A /**
0N/A * Get a RSAPadding instance of the specified type, which must be
0N/A * OAEP. Keys used with this padding must be paddedSize bytes long.
0N/A */
0N/A public static RSAPadding getInstance(int type, int paddedSize,
0N/A SecureRandom random, OAEPParameterSpec spec)
0N/A throws InvalidKeyException, InvalidAlgorithmParameterException {
0N/A return new RSAPadding(type, paddedSize, random, spec);
0N/A }
0N/A
0N/A // internal constructor
0N/A private RSAPadding(int type, int paddedSize, SecureRandom random,
0N/A OAEPParameterSpec spec) throws InvalidKeyException,
0N/A InvalidAlgorithmParameterException {
0N/A this.type = type;
0N/A this.paddedSize = paddedSize;
0N/A this.random = random;
0N/A if (paddedSize < 64) {
0N/A // sanity check, already verified in RSASignature/RSACipher
0N/A throw new InvalidKeyException("Padded size must be at least 64");
0N/A }
0N/A switch (type) {
0N/A case PAD_BLOCKTYPE_1:
0N/A case PAD_BLOCKTYPE_2:
0N/A maxDataSize = paddedSize - 11;
0N/A break;
0N/A case PAD_NONE:
0N/A maxDataSize = paddedSize;
0N/A break;
0N/A case PAD_OAEP_MGF1:
0N/A String mdName = "SHA-1";
0N/A String mgfMdName = "SHA-1";
0N/A byte[] digestInput = null;
0N/A try {
0N/A if (spec != null) {
0N/A mdName = spec.getDigestAlgorithm();
0N/A String mgfName = spec.getMGFAlgorithm();
0N/A if (!mgfName.equalsIgnoreCase("MGF1")) {
0N/A throw new InvalidAlgorithmParameterException
0N/A ("Unsupported MGF algo: " + mgfName);
0N/A }
0N/A mgfMdName = ((MGF1ParameterSpec)spec.getMGFParameters()).getDigestAlgorithm();
0N/A PSource pSrc = spec.getPSource();
0N/A String pSrcAlgo = pSrc.getAlgorithm();
0N/A if (!pSrcAlgo.equalsIgnoreCase("PSpecified")) {
0N/A throw new InvalidAlgorithmParameterException
0N/A ("Unsupported pSource algo: " + pSrcAlgo);
0N/A }
0N/A digestInput = ((PSource.PSpecified) pSrc).getValue();
0N/A }
0N/A md = MessageDigest.getInstance(mdName);
0N/A mgfMd = MessageDigest.getInstance(mgfMdName);
0N/A } catch (NoSuchAlgorithmException e) {
0N/A throw new InvalidKeyException
0N/A ("Digest " + mdName + " not available", e);
0N/A }
0N/A lHash = getInitialHash(md, digestInput);
0N/A int digestLen = lHash.length;
0N/A maxDataSize = paddedSize - 2 - 2 * digestLen;
0N/A if (maxDataSize <= 0) {
0N/A throw new InvalidKeyException
0N/A ("Key is too short for encryption using OAEPPadding" +
0N/A " with " + mdName + " and MGF1" + mgfMdName);
0N/A }
0N/A break;
0N/A default:
0N/A throw new InvalidKeyException("Invalid padding: " + type);
0N/A }
0N/A }
0N/A
0N/A // cache of hashes of zero length data
0N/A private static final Map<String,byte[]> emptyHashes =
0N/A Collections.synchronizedMap(new HashMap<String,byte[]>());
0N/A
0N/A /**
0N/A * Return the value of the digest using the specified message digest
0N/A * <code>md</code> and the digest input <code>digestInput</code>.
0N/A * if <code>digestInput</code> is null or 0-length, zero length
0N/A * is used to generate the initial digest.
0N/A * Note: the md object must be in reset state
0N/A */
0N/A private static byte[] getInitialHash(MessageDigest md,
0N/A byte[] digestInput) {
0N/A byte[] result = null;
0N/A if ((digestInput == null) || (digestInput.length == 0)) {
0N/A String digestName = md.getAlgorithm();
0N/A result = emptyHashes.get(digestName);
0N/A if (result == null) {
0N/A result = md.digest();
0N/A emptyHashes.put(digestName, result);
0N/A }
0N/A } else {
0N/A result = md.digest(digestInput);
0N/A }
0N/A return result;
0N/A }
0N/A
0N/A /**
0N/A * Return the maximum size of the plaintext data that can be processed using
0N/A * this object.
0N/A */
0N/A public int getMaxDataSize() {
0N/A return maxDataSize;
0N/A }
0N/A
0N/A /**
0N/A * Pad the data and return the padded block.
0N/A */
0N/A public byte[] pad(byte[] data, int ofs, int len)
0N/A throws BadPaddingException {
0N/A return pad(RSACore.convert(data, ofs, len));
0N/A }
0N/A
0N/A /**
0N/A * Pad the data and return the padded block.
0N/A */
0N/A public byte[] pad(byte[] data) throws BadPaddingException {
0N/A if (data.length > maxDataSize) {
0N/A throw new BadPaddingException("Data must be shorter than "
0N/A + (maxDataSize + 1) + " bytes");
0N/A }
0N/A switch (type) {
0N/A case PAD_NONE:
0N/A return data;
0N/A case PAD_BLOCKTYPE_1:
0N/A case PAD_BLOCKTYPE_2:
0N/A return padV15(data);
0N/A case PAD_OAEP_MGF1:
0N/A return padOAEP(data);
0N/A default:
0N/A throw new AssertionError();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Unpad the padded block and return the data.
0N/A */
0N/A public byte[] unpad(byte[] padded, int ofs, int len)
0N/A throws BadPaddingException {
0N/A return unpad(RSACore.convert(padded, ofs, len));
0N/A }
0N/A
0N/A /**
0N/A * Unpad the padded block and return the data.
0N/A */
0N/A public byte[] unpad(byte[] padded) throws BadPaddingException {
0N/A if (padded.length != paddedSize) {
0N/A throw new BadPaddingException("Padded length must be " + paddedSize);
0N/A }
0N/A switch (type) {
0N/A case PAD_NONE:
0N/A return padded;
0N/A case PAD_BLOCKTYPE_1:
0N/A case PAD_BLOCKTYPE_2:
0N/A return unpadV15(padded);
0N/A case PAD_OAEP_MGF1:
0N/A return unpadOAEP(padded);
0N/A default:
0N/A throw new AssertionError();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * PKCS#1 v1.5 padding (blocktype 1 and 2).
0N/A */
0N/A private byte[] padV15(byte[] data) throws BadPaddingException {
0N/A byte[] padded = new byte[paddedSize];
0N/A System.arraycopy(data, 0, padded, paddedSize - data.length, data.length);
0N/A int psSize = paddedSize - 3 - data.length;
0N/A int k = 0;
0N/A padded[k++] = 0;
0N/A padded[k++] = (byte)type;
0N/A if (type == PAD_BLOCKTYPE_1) {
0N/A // blocktype 1: all padding bytes are 0xff
0N/A while (psSize-- > 0) {
0N/A padded[k++] = (byte)0xff;
0N/A }
0N/A } else {
0N/A // blocktype 2: padding bytes are random non-zero bytes
0N/A if (random == null) {
0N/A random = JCAUtil.getSecureRandom();
0N/A }
0N/A // generate non-zero padding bytes
0N/A // use a buffer to reduce calls to SecureRandom
0N/A byte[] r = new byte[64];
0N/A int i = -1;
0N/A while (psSize-- > 0) {
0N/A int b;
0N/A do {
0N/A if (i < 0) {
0N/A random.nextBytes(r);
0N/A i = r.length - 1;
0N/A }
0N/A b = r[i--] & 0xff;
0N/A } while (b == 0);
0N/A padded[k++] = (byte)b;
0N/A }
0N/A }
0N/A return padded;
0N/A }
0N/A
0N/A /**
0N/A * PKCS#1 v1.5 unpadding (blocktype 1 and 2).
0N/A */
0N/A private byte[] unpadV15(byte[] padded) throws BadPaddingException {
0N/A int k = 0;
0N/A if (padded[k++] != 0) {
0N/A throw new BadPaddingException("Data must start with zero");
0N/A }
0N/A if (padded[k++] != type) {
0N/A throw new BadPaddingException("Blocktype mismatch: " + padded[1]);
0N/A }
0N/A while (true) {
0N/A int b = padded[k++] & 0xff;
0N/A if (b == 0) {
0N/A break;
0N/A }
0N/A if (k == padded.length) {
0N/A throw new BadPaddingException("Padding string not terminated");
0N/A }
0N/A if ((type == PAD_BLOCKTYPE_1) && (b != 0xff)) {
0N/A throw new BadPaddingException("Padding byte not 0xff: " + b);
0N/A }
0N/A }
0N/A int n = padded.length - k;
0N/A if (n > maxDataSize) {
0N/A throw new BadPaddingException("Padding string too short");
0N/A }
0N/A byte[] data = new byte[n];
0N/A System.arraycopy(padded, padded.length - n, data, 0, n);
0N/A return data;
0N/A }
0N/A
0N/A /**
0N/A * PKCS#1 v2.0 OAEP padding (MGF1).
0N/A * Paragraph references refer to PKCS#1 v2.1 (June 14, 2002)
0N/A */
0N/A private byte[] padOAEP(byte[] M) throws BadPaddingException {
0N/A if (random == null) {
0N/A random = JCAUtil.getSecureRandom();
0N/A }
0N/A int hLen = lHash.length;
0N/A
0N/A // 2.d: generate a random octet string seed of length hLen
0N/A // if necessary
0N/A byte[] seed = new byte[hLen];
0N/A random.nextBytes(seed);
0N/A
0N/A // buffer for encoded message EM
0N/A byte[] EM = new byte[paddedSize];
0N/A
0N/A // start and length of seed (as index into EM)
0N/A int seedStart = 1;
0N/A int seedLen = hLen;
0N/A
0N/A // copy seed into EM
0N/A System.arraycopy(seed, 0, EM, seedStart, seedLen);
0N/A
0N/A // start and length of data block DB in EM
0N/A // we place it inside of EM to reduce copying
0N/A int dbStart = hLen + 1;
0N/A int dbLen = EM.length - dbStart;
0N/A
0N/A // start of message M in EM
0N/A int mStart = paddedSize - M.length;
0N/A
0N/A // build DB
0N/A // 2.b: Concatenate lHash, PS, a single octet with hexadecimal value
0N/A // 0x01, and the message M to form a data block DB of length
0N/A // k - hLen -1 octets as DB = lHash || PS || 0x01 || M
0N/A // (note that PS is all zeros)
0N/A System.arraycopy(lHash, 0, EM, dbStart, hLen);
0N/A EM[mStart - 1] = 1;
0N/A System.arraycopy(M, 0, EM, mStart, M.length);
0N/A
0N/A // produce maskedDB
0N/A mgf1(EM, seedStart, seedLen, EM, dbStart, dbLen);
0N/A
0N/A // produce maskSeed
0N/A mgf1(EM, dbStart, dbLen, EM, seedStart, seedLen);
0N/A
0N/A return EM;
0N/A }
0N/A
0N/A /**
0N/A * PKCS#1 v2.1 OAEP unpadding (MGF1).
0N/A */
0N/A private byte[] unpadOAEP(byte[] padded) throws BadPaddingException {
0N/A byte[] EM = padded;
0N/A int hLen = lHash.length;
0N/A
0N/A if (EM[0] != 0) {
0N/A throw new BadPaddingException("Data must start with zero");
0N/A }
0N/A
0N/A int seedStart = 1;
0N/A int seedLen = hLen;
0N/A
0N/A int dbStart = hLen + 1;
0N/A int dbLen = EM.length - dbStart;
0N/A
0N/A mgf1(EM, dbStart, dbLen, EM, seedStart, seedLen);
0N/A mgf1(EM, seedStart, seedLen, EM, dbStart, dbLen);
0N/A
0N/A // verify lHash == lHash'
0N/A for (int i = 0; i < hLen; i++) {
0N/A if (lHash[i] != EM[dbStart + i]) {
0N/A throw new BadPaddingException("lHash mismatch");
0N/A }
0N/A }
0N/A
0N/A // skip over padding (0x00 bytes)
0N/A int i = dbStart + hLen;
0N/A while (EM[i] == 0) {
0N/A i++;
0N/A if (i >= EM.length) {
0N/A throw new BadPaddingException("Padding string not terminated");
0N/A }
0N/A }
0N/A
0N/A if (EM[i++] != 1) {
0N/A throw new BadPaddingException
0N/A ("Padding string not terminated by 0x01 byte");
0N/A }
0N/A
0N/A int mLen = EM.length - i;
0N/A byte[] m = new byte[mLen];
0N/A System.arraycopy(EM, i, m, 0, mLen);
0N/A
0N/A return m;
0N/A }
0N/A
0N/A /**
0N/A * Compute MGF1 using mgfMD as the message digest.
0N/A * Note that we combine MGF1 with the XOR operation to reduce data
0N/A * copying.
0N/A *
0N/A * We generate maskLen bytes of MGF1 from the seed and XOR it into
0N/A * out[] starting at outOfs;
0N/A */
0N/A private void mgf1(byte[] seed, int seedOfs, int seedLen,
0N/A byte[] out, int outOfs, int maskLen) throws BadPaddingException {
0N/A byte[] C = new byte[4]; // 32 bit counter
0N/A byte[] digest = new byte[20]; // 20 bytes is length of SHA-1 digest
0N/A while (maskLen > 0) {
0N/A mgfMd.update(seed, seedOfs, seedLen);
0N/A mgfMd.update(C);
0N/A try {
0N/A mgfMd.digest(digest, 0, digest.length);
0N/A } catch (DigestException e) {
0N/A // should never happen
0N/A throw new BadPaddingException(e.toString());
0N/A }
0N/A for (int i = 0; (i < digest.length) && (maskLen > 0); maskLen--) {
0N/A out[outOfs++] ^= digest[i++];
0N/A }
0N/A if (maskLen > 0) {
0N/A // increment counter
0N/A for (int i = C.length - 1; (++C[i] == 0) && (i > 0); i--) {
0N/A // empty
0N/A }
0N/A }
0N/A }
0N/A }
0N/A
0N/A}