Path: blob/master/src/java.base/share/classes/sun/security/rsa/RSAPadding.java
41159 views
/*1* Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.security.rsa;2627import java.util.*;2829import java.security.*;30import java.security.spec.*;3132import javax.crypto.BadPaddingException;33import javax.crypto.spec.PSource;34import javax.crypto.spec.OAEPParameterSpec;3536import sun.security.jca.JCAUtil;3738/**39* RSA padding and unpadding.40*41* The various PKCS#1 versions can be found in the IETF RFCs42* tracking the corresponding PKCS#1 standards.43*44* RFC 2313: PKCS#1 v1.545* RFC 2437: PKCS#1 v2.046* RFC 3447: PKCS#1 v2.147* RFC 8017: PKCS#1 v2.248*49* The format of PKCS#1 v1.5 padding is:50*51* 0x00 | BT | PS...PS | 0x00 | data...data52*53* where BT is the blocktype (1 or 2). The length of the entire string54* must be the same as the size of the modulus (i.e. 128 byte for a 1024 bit55* key). Per spec, the padding string must be at least 8 bytes long. That56* leaves up to (length of key in bytes) - 11 bytes for the data.57*58* OAEP padding was introduced in PKCS#1 v2.0 and is a bit more complicated59* and has a number of options. We support:60*61* . arbitrary hash functions ('Hash' in the specification), MessageDigest62* implementation must be available63* . MGF1 as the mask generation function64* . the empty string as the default value for label L and whatever65* specified in javax.crypto.spec.OAEPParameterSpec66*67* The algorithms (representations) are forwards-compatible: that is,68* the algorithm described in previous releases are in later releases.69* However, additional comments/checks/clarifications were added to the70* later versions based on real-world experience (e.g. stricter v1.571* format checking.)72*73* Note: RSA keys should be at least 512 bits long74*75* @since 1.576* @author Andreas Sterbenz77*/78public final class RSAPadding {7980// NOTE: the constants below are embedded in the JCE RSACipher class81// file. Do not change without coordinating the update8283// PKCS#1 v1.5 padding, blocktype 1 (signing)84public static final int PAD_BLOCKTYPE_1 = 1;85// PKCS#1 v1.5 padding, blocktype 2 (encryption)86public static final int PAD_BLOCKTYPE_2 = 2;87// nopadding. Does not do anything, but allows simpler RSACipher code88public static final int PAD_NONE = 3;89// PKCS#1 v2.1 OAEP padding90public static final int PAD_OAEP_MGF1 = 4;9192// type, one of PAD_*93private final int type;9495// size of the padded block (i.e. size of the modulus)96private final int paddedSize;9798// PRNG used to generate padding bytes (PAD_BLOCKTYPE_2, PAD_OAEP_MGF1)99private SecureRandom random;100101// maximum size of the data102private final int maxDataSize;103104// OAEP: main message digest105private MessageDigest md;106107// OAEP: MGF1108private MGF1 mgf;109110// OAEP: value of digest of data (user-supplied or zero-length) using md111private byte[] lHash;112113/**114* Get a RSAPadding instance of the specified type.115* Keys used with this padding must be paddedSize bytes long.116*/117public static RSAPadding getInstance(int type, int paddedSize)118throws InvalidKeyException, InvalidAlgorithmParameterException {119return new RSAPadding(type, paddedSize, null, null);120}121122/**123* Get a RSAPadding instance of the specified type.124* Keys used with this padding must be paddedSize bytes long.125*/126public static RSAPadding getInstance(int type, int paddedSize,127SecureRandom random) throws InvalidKeyException,128InvalidAlgorithmParameterException {129return new RSAPadding(type, paddedSize, random, null);130}131132/**133* Get a RSAPadding instance of the specified type, which must be134* OAEP. Keys used with this padding must be paddedSize bytes long.135*/136public static RSAPadding getInstance(int type, int paddedSize,137SecureRandom random, OAEPParameterSpec spec)138throws InvalidKeyException, InvalidAlgorithmParameterException {139return new RSAPadding(type, paddedSize, random, spec);140}141142// internal constructor143private RSAPadding(int type, int paddedSize, SecureRandom random,144OAEPParameterSpec spec) throws InvalidKeyException,145InvalidAlgorithmParameterException {146this.type = type;147this.paddedSize = paddedSize;148this.random = random;149if (paddedSize < 64) {150// sanity check, already verified in RSASignature/RSACipher151throw new InvalidKeyException("Padded size must be at least 64");152}153switch (type) {154case PAD_BLOCKTYPE_1:155case PAD_BLOCKTYPE_2:156maxDataSize = paddedSize - 11;157break;158case PAD_NONE:159maxDataSize = paddedSize;160break;161case PAD_OAEP_MGF1:162String mdName = "SHA-1";163String mgfMdName = mdName;164byte[] digestInput = null;165try {166if (spec != null) {167mdName = spec.getDigestAlgorithm();168String mgfName = spec.getMGFAlgorithm();169if (!mgfName.equalsIgnoreCase("MGF1")) {170throw new InvalidAlgorithmParameterException171("Unsupported MGF algo: " + mgfName);172}173mgfMdName = ((MGF1ParameterSpec)spec.getMGFParameters())174.getDigestAlgorithm();175PSource pSrc = spec.getPSource();176String pSrcAlgo = pSrc.getAlgorithm();177if (!pSrcAlgo.equalsIgnoreCase("PSpecified")) {178throw new InvalidAlgorithmParameterException179("Unsupported pSource algo: " + pSrcAlgo);180}181digestInput = ((PSource.PSpecified) pSrc).getValue();182}183md = MessageDigest.getInstance(mdName);184mgf = new MGF1(mgfMdName);185} catch (NoSuchAlgorithmException e) {186throw new InvalidKeyException("Digest not available", e);187}188lHash = getInitialHash(md, digestInput);189int digestLen = lHash.length;190maxDataSize = paddedSize - 2 - 2 * digestLen;191if (maxDataSize <= 0) {192throw new InvalidKeyException193("Key is too short for encryption using OAEPPadding" +194" with " + mdName + " and " + mgf.getName());195}196break;197default:198throw new InvalidKeyException("Invalid padding: " + type);199}200}201202// cache of hashes of zero length data203private static final Map<String,byte[]> emptyHashes =204Collections.synchronizedMap(new HashMap<String,byte[]>());205206/**207* Return the value of the digest using the specified message digest208* <code>md</code> and the digest input <code>digestInput</code>.209* if <code>digestInput</code> is null or 0-length, zero length210* is used to generate the initial digest.211* Note: the md object must be in reset state212*/213private static byte[] getInitialHash(MessageDigest md,214byte[] digestInput) {215byte[] result;216if ((digestInput == null) || (digestInput.length == 0)) {217String digestName = md.getAlgorithm();218result = emptyHashes.get(digestName);219if (result == null) {220result = md.digest();221emptyHashes.put(digestName, result);222}223} else {224result = md.digest(digestInput);225}226return result;227}228229/**230* Return the maximum size of the plaintext data that can be processed231* using this object.232*/233public int getMaxDataSize() {234return maxDataSize;235}236237/**238* Pad the data and return the padded block.239*/240public byte[] pad(byte[] data) throws BadPaddingException {241return pad(data, 0, data.length);242}243244/**245* Pad the data and return the padded block.246*/247public byte[] pad(byte[] data, int ofs, int len)248throws BadPaddingException {249if (len > maxDataSize) {250throw new BadPaddingException("Data must be shorter than "251+ (maxDataSize + 1) + " bytes but received "252+ len + " bytes.");253}254switch (type) {255case PAD_NONE:256return RSACore.convert(data, ofs, len);257case PAD_BLOCKTYPE_1:258case PAD_BLOCKTYPE_2:259return padV15(data, ofs, len);260case PAD_OAEP_MGF1:261return padOAEP(data, ofs, len);262default:263throw new AssertionError();264}265}266267/**268* Unpad the padded block and return the data.269*/270public byte[] unpad(byte[] padded) throws BadPaddingException {271if (padded.length != paddedSize) {272throw new BadPaddingException("Decryption error." +273"The padded array length (" + padded.length +274") is not the specified padded size (" + paddedSize + ")");275}276switch (type) {277case PAD_NONE:278return padded;279case PAD_BLOCKTYPE_1:280case PAD_BLOCKTYPE_2:281return unpadV15(padded);282case PAD_OAEP_MGF1:283return unpadOAEP(padded);284default:285throw new AssertionError();286}287}288289/**290* PKCS#1 v1.5 padding (blocktype 1 and 2).291*/292private byte[] padV15(byte[] data, int ofs, int len) throws BadPaddingException {293byte[] padded = new byte[paddedSize];294System.arraycopy(data, ofs, padded, paddedSize - len, len);295int psSize = paddedSize - 3 - len;296int k = 0;297padded[k++] = 0;298padded[k++] = (byte)type;299if (type == PAD_BLOCKTYPE_1) {300// blocktype 1: all padding bytes are 0xff301while (psSize-- > 0) {302padded[k++] = (byte)0xff;303}304} else {305// blocktype 2: padding bytes are random non-zero bytes306if (random == null) {307random = JCAUtil.getSecureRandom();308}309// generate non-zero padding bytes310// use a buffer to reduce calls to SecureRandom311while (psSize > 0) {312// extra bytes to avoid zero bytes,313// number of zero bytes <= 4 in 98% cases314byte[] r = new byte[psSize + 4];315random.nextBytes(r);316for (int i = 0; i < r.length && psSize > 0; i++) {317if (r[i] != 0) {318padded[k++] = r[i];319psSize--;320}321}322}323}324return padded;325}326327/**328* PKCS#1 v1.5 unpadding (blocktype 1 (signature) and 2 (encryption)).329*330* Note that we want to make it a constant-time operation331*/332private byte[] unpadV15(byte[] padded) throws BadPaddingException {333int k = 0;334boolean bp = false;335336if (padded[k++] != 0) {337bp = true;338}339if (padded[k++] != type) {340bp = true;341}342int p = 0;343while (k < padded.length) {344int b = padded[k++] & 0xff;345if ((b == 0) && (p == 0)) {346p = k;347}348if ((k == padded.length) && (p == 0)) {349bp = true;350}351if ((type == PAD_BLOCKTYPE_1) && (b != 0xff) &&352(p == 0)) {353bp = true;354}355}356int n = padded.length - p;357if (n > maxDataSize) {358bp = true;359}360361// copy useless padding array for a constant-time method362byte[] padding = new byte[p];363System.arraycopy(padded, 0, padding, 0, p);364365byte[] data = new byte[n];366System.arraycopy(padded, p, data, 0, n);367368BadPaddingException bpe = new BadPaddingException("Decryption error");369370if (bp) {371throw bpe;372} else {373return data;374}375}376377/**378* PKCS#1 v2.0 OAEP padding (MGF1).379* Paragraph references refer to PKCS#1 v2.1 (June 14, 2002)380*/381private byte[] padOAEP(byte[] M, int ofs, int len) throws BadPaddingException {382if (random == null) {383random = JCAUtil.getSecureRandom();384}385int hLen = lHash.length;386387// 2.d: generate a random octet string seed of length hLen388// if necessary389byte[] seed = new byte[hLen];390random.nextBytes(seed);391392// buffer for encoded message EM393byte[] EM = new byte[paddedSize];394395// start and length of seed (as index into EM)396int seedStart = 1;397int seedLen = hLen;398399// copy seed into EM400System.arraycopy(seed, 0, EM, seedStart, seedLen);401402// start and length of data block DB in EM403// we place it inside of EM to reduce copying404int dbStart = hLen + 1;405int dbLen = EM.length - dbStart;406407// start of message M in EM408int mStart = paddedSize - len;409410// build DB411// 2.b: Concatenate lHash, PS, a single octet with hexadecimal value412// 0x01, and the message M to form a data block DB of length413// k - hLen -1 octets as DB = lHash || PS || 0x01 || M414// (note that PS is all zeros)415System.arraycopy(lHash, 0, EM, dbStart, hLen);416EM[mStart - 1] = 1;417System.arraycopy(M, ofs, EM, mStart, len);418419// produce maskedDB420mgf.generateAndXor(EM, seedStart, seedLen, dbLen, EM, dbStart);421422// produce maskSeed423mgf.generateAndXor(EM, dbStart, dbLen, seedLen, EM, seedStart);424425return EM;426}427428/**429* PKCS#1 v2.1 OAEP unpadding (MGF1).430*/431private byte[] unpadOAEP(byte[] padded) throws BadPaddingException {432byte[] EM = padded;433boolean bp = false;434int hLen = lHash.length;435436if (EM[0] != 0) {437bp = true;438}439440int seedStart = 1;441int seedLen = hLen;442443int dbStart = hLen + 1;444int dbLen = EM.length - dbStart;445446mgf.generateAndXor(EM, dbStart, dbLen, seedLen, EM, seedStart);447mgf.generateAndXor(EM, seedStart, seedLen, dbLen, EM, dbStart);448449// verify lHash == lHash'450for (int i = 0; i < hLen; i++) {451if (lHash[i] != EM[dbStart + i]) {452bp = true;453}454}455456int padStart = dbStart + hLen;457int onePos = -1;458459for (int i = padStart; i < EM.length; i++) {460int value = EM[i];461if (onePos == -1) {462if (value == 0x00) {463// continue;464} else if (value == 0x01) {465onePos = i;466} else { // Anything other than {0,1} is bad.467bp = true;468}469}470}471472// We either ran off the rails or found something other than 0/1.473if (onePos == -1) {474bp = true;475onePos = EM.length - 1; // Don't inadvertently return any data.476}477478int mStart = onePos + 1;479480// copy useless padding array for a constant-time method481byte [] tmp = new byte[mStart - padStart];482System.arraycopy(EM, padStart, tmp, 0, tmp.length);483484byte [] m = new byte[EM.length - mStart];485System.arraycopy(EM, mStart, m, 0, m.length);486487BadPaddingException bpe = new BadPaddingException("Decryption error");488489if (bp) {490throw bpe;491} else {492return m;493}494}495}496497498