Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/security/rsa/RSAPadding.java
38830 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 final static int PAD_BLOCKTYPE_1 = 1;85// PKCS#1 v1.5 padding, blocktype 2 (encryption)86public final static int PAD_BLOCKTYPE_2 = 2;87// nopadding. Does not do anything, but allows simpler RSACipher code88public final static int PAD_NONE = 3;89// PKCS#1 v2.1 OAEP padding90public final static 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 SecureRandom311byte[] r = new byte[64];312int i = -1;313while (psSize-- > 0) {314int b;315do {316if (i < 0) {317random.nextBytes(r);318i = r.length - 1;319}320b = r[i--] & 0xff;321} while (b == 0);322padded[k++] = (byte)b;323}324}325return padded;326}327328/**329* PKCS#1 v1.5 unpadding (blocktype 1 (signature) and 2 (encryption)).330*331* Note that we want to make it a constant-time operation332*/333private byte[] unpadV15(byte[] padded) throws BadPaddingException {334int k = 0;335boolean bp = false;336337if (padded[k++] != 0) {338bp = true;339}340if (padded[k++] != type) {341bp = true;342}343int p = 0;344while (k < padded.length) {345int b = padded[k++] & 0xff;346if ((b == 0) && (p == 0)) {347p = k;348}349if ((k == padded.length) && (p == 0)) {350bp = true;351}352if ((type == PAD_BLOCKTYPE_1) && (b != 0xff) &&353(p == 0)) {354bp = true;355}356}357int n = padded.length - p;358if (n > maxDataSize) {359bp = true;360}361362// copy useless padding array for a constant-time method363byte[] padding = new byte[p];364System.arraycopy(padded, 0, padding, 0, p);365366byte[] data = new byte[n];367System.arraycopy(padded, p, data, 0, n);368369BadPaddingException bpe = new BadPaddingException("Decryption error");370371if (bp) {372throw bpe;373} else {374return data;375}376}377378/**379* PKCS#1 v2.0 OAEP padding (MGF1).380* Paragraph references refer to PKCS#1 v2.1 (June 14, 2002)381*/382private byte[] padOAEP(byte[] M, int ofs, int len) throws BadPaddingException {383if (random == null) {384random = JCAUtil.getSecureRandom();385}386int hLen = lHash.length;387388// 2.d: generate a random octet string seed of length hLen389// if necessary390byte[] seed = new byte[hLen];391random.nextBytes(seed);392393// buffer for encoded message EM394byte[] EM = new byte[paddedSize];395396// start and length of seed (as index into EM)397int seedStart = 1;398int seedLen = hLen;399400// copy seed into EM401System.arraycopy(seed, 0, EM, seedStart, seedLen);402403// start and length of data block DB in EM404// we place it inside of EM to reduce copying405int dbStart = hLen + 1;406int dbLen = EM.length - dbStart;407408// start of message M in EM409int mStart = paddedSize - len;410411// build DB412// 2.b: Concatenate lHash, PS, a single octet with hexadecimal value413// 0x01, and the message M to form a data block DB of length414// k - hLen -1 octets as DB = lHash || PS || 0x01 || M415// (note that PS is all zeros)416System.arraycopy(lHash, 0, EM, dbStart, hLen);417EM[mStart - 1] = 1;418System.arraycopy(M, ofs, EM, mStart, len);419420// produce maskedDB421mgf.generateAndXor(EM, seedStart, seedLen, dbLen, EM, dbStart);422423// produce maskSeed424mgf.generateAndXor(EM, dbStart, dbLen, seedLen, EM, seedStart);425426return EM;427}428429/**430* PKCS#1 v2.1 OAEP unpadding (MGF1).431*/432private byte[] unpadOAEP(byte[] padded) throws BadPaddingException {433byte[] EM = padded;434boolean bp = false;435int hLen = lHash.length;436437if (EM[0] != 0) {438bp = true;439}440441int seedStart = 1;442int seedLen = hLen;443444int dbStart = hLen + 1;445int dbLen = EM.length - dbStart;446447mgf.generateAndXor(EM, dbStart, dbLen, seedLen, EM, seedStart);448mgf.generateAndXor(EM, seedStart, seedLen, dbLen, EM, dbStart);449450// verify lHash == lHash'451for (int i = 0; i < hLen; i++) {452if (lHash[i] != EM[dbStart + i]) {453bp = true;454}455}456457int padStart = dbStart + hLen;458int onePos = -1;459460for (int i = padStart; i < EM.length; i++) {461int value = EM[i];462if (onePos == -1) {463if (value == 0x00) {464// continue;465} else if (value == 0x01) {466onePos = i;467} else { // Anything other than {0,1} is bad.468bp = true;469}470}471}472473// We either ran off the rails or found something other than 0/1.474if (onePos == -1) {475bp = true;476onePos = EM.length - 1; // Don't inadvertently return any data.477}478479int mStart = onePos + 1;480481// copy useless padding array for a constant-time method482byte [] tmp = new byte[mStart - padStart];483System.arraycopy(EM, padStart, tmp, 0, tmp.length);484485byte [] m = new byte[EM.length - mStart];486System.arraycopy(EM, mStart, m, 0, m.length);487488BadPaddingException bpe = new BadPaddingException("Decryption error");489490if (bp) {491throw bpe;492} else {493return m;494}495}496}497498499