Path: blob/jdk8u272-b10-aarch32-20201026/jdk/src/share/classes/sun/security/rsa/RSAPadding.java
83409 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, int ofs, int len)241throws BadPaddingException {242return pad(RSACore.convert(data, ofs, len));243}244245/**246* Pad the data and return the padded block.247*/248public byte[] pad(byte[] data) throws BadPaddingException {249if (data.length > maxDataSize) {250throw new BadPaddingException("Data must be shorter than "251+ (maxDataSize + 1) + " bytes but received "252+ data.length + " bytes.");253}254switch (type) {255case PAD_NONE:256return data;257case PAD_BLOCKTYPE_1:258case PAD_BLOCKTYPE_2:259return padV15(data);260case PAD_OAEP_MGF1:261return padOAEP(data);262default:263throw new AssertionError();264}265}266267/**268* Unpad the padded block and return the data.269*/270public byte[] unpad(byte[] padded, int ofs, int len)271throws BadPaddingException {272return unpad(RSACore.convert(padded, ofs, len));273}274275/**276* Unpad the padded block and return the data.277*/278public byte[] unpad(byte[] padded) throws BadPaddingException {279if (padded.length != paddedSize) {280throw new BadPaddingException("Decryption error." +281"The padded array length (" + padded.length +282") is not the specified padded size (" + paddedSize + ")");283}284switch (type) {285case PAD_NONE:286return padded;287case PAD_BLOCKTYPE_1:288case PAD_BLOCKTYPE_2:289return unpadV15(padded);290case PAD_OAEP_MGF1:291return unpadOAEP(padded);292default:293throw new AssertionError();294}295}296297/**298* PKCS#1 v1.5 padding (blocktype 1 and 2).299*/300private byte[] padV15(byte[] data) throws BadPaddingException {301byte[] padded = new byte[paddedSize];302System.arraycopy(data, 0, padded, paddedSize - data.length,303data.length);304int psSize = paddedSize - 3 - data.length;305int k = 0;306padded[k++] = 0;307padded[k++] = (byte)type;308if (type == PAD_BLOCKTYPE_1) {309// blocktype 1: all padding bytes are 0xff310while (psSize-- > 0) {311padded[k++] = (byte)0xff;312}313} else {314// blocktype 2: padding bytes are random non-zero bytes315if (random == null) {316random = JCAUtil.getSecureRandom();317}318// generate non-zero padding bytes319// use a buffer to reduce calls to SecureRandom320byte[] r = new byte[64];321int i = -1;322while (psSize-- > 0) {323int b;324do {325if (i < 0) {326random.nextBytes(r);327i = r.length - 1;328}329b = r[i--] & 0xff;330} while (b == 0);331padded[k++] = (byte)b;332}333}334return padded;335}336337/**338* PKCS#1 v1.5 unpadding (blocktype 1 (signature) and 2 (encryption)).339*340* Note that we want to make it a constant-time operation341*/342private byte[] unpadV15(byte[] padded) throws BadPaddingException {343int k = 0;344boolean bp = false;345346if (padded[k++] != 0) {347bp = true;348}349if (padded[k++] != type) {350bp = true;351}352int p = 0;353while (k < padded.length) {354int b = padded[k++] & 0xff;355if ((b == 0) && (p == 0)) {356p = k;357}358if ((k == padded.length) && (p == 0)) {359bp = true;360}361if ((type == PAD_BLOCKTYPE_1) && (b != 0xff) &&362(p == 0)) {363bp = true;364}365}366int n = padded.length - p;367if (n > maxDataSize) {368bp = true;369}370371// copy useless padding array for a constant-time method372byte[] padding = new byte[p];373System.arraycopy(padded, 0, padding, 0, p);374375byte[] data = new byte[n];376System.arraycopy(padded, p, data, 0, n);377378BadPaddingException bpe = new BadPaddingException("Decryption error");379380if (bp) {381throw bpe;382} else {383return data;384}385}386387/**388* PKCS#1 v2.0 OAEP padding (MGF1).389* Paragraph references refer to PKCS#1 v2.1 (June 14, 2002)390*/391private byte[] padOAEP(byte[] M) throws BadPaddingException {392if (random == null) {393random = JCAUtil.getSecureRandom();394}395int hLen = lHash.length;396397// 2.d: generate a random octet string seed of length hLen398// if necessary399byte[] seed = new byte[hLen];400random.nextBytes(seed);401402// buffer for encoded message EM403byte[] EM = new byte[paddedSize];404405// start and length of seed (as index into EM)406int seedStart = 1;407int seedLen = hLen;408409// copy seed into EM410System.arraycopy(seed, 0, EM, seedStart, seedLen);411412// start and length of data block DB in EM413// we place it inside of EM to reduce copying414int dbStart = hLen + 1;415int dbLen = EM.length - dbStart;416417// start of message M in EM418int mStart = paddedSize - M.length;419420// build DB421// 2.b: Concatenate lHash, PS, a single octet with hexadecimal value422// 0x01, and the message M to form a data block DB of length423// k - hLen -1 octets as DB = lHash || PS || 0x01 || M424// (note that PS is all zeros)425System.arraycopy(lHash, 0, EM, dbStart, hLen);426EM[mStart - 1] = 1;427System.arraycopy(M, 0, EM, mStart, M.length);428429// produce maskedDB430mgf.generateAndXor(EM, seedStart, seedLen, dbLen, EM, dbStart);431432// produce maskSeed433mgf.generateAndXor(EM, dbStart, dbLen, seedLen, EM, seedStart);434435return EM;436}437438/**439* PKCS#1 v2.1 OAEP unpadding (MGF1).440*/441private byte[] unpadOAEP(byte[] padded) throws BadPaddingException {442byte[] EM = padded;443boolean bp = false;444int hLen = lHash.length;445446if (EM[0] != 0) {447bp = true;448}449450int seedStart = 1;451int seedLen = hLen;452453int dbStart = hLen + 1;454int dbLen = EM.length - dbStart;455456mgf.generateAndXor(EM, dbStart, dbLen, seedLen, EM, seedStart);457mgf.generateAndXor(EM, seedStart, seedLen, dbLen, EM, dbStart);458459// verify lHash == lHash'460for (int i = 0; i < hLen; i++) {461if (lHash[i] != EM[dbStart + i]) {462bp = true;463}464}465466int padStart = dbStart + hLen;467int onePos = -1;468469for (int i = padStart; i < EM.length; i++) {470int value = EM[i];471if (onePos == -1) {472if (value == 0x00) {473// continue;474} else if (value == 0x01) {475onePos = i;476} else { // Anything other than {0,1} is bad.477bp = true;478}479}480}481482// We either ran off the rails or found something other than 0/1.483if (onePos == -1) {484bp = true;485onePos = EM.length - 1; // Don't inadvertently return any data.486}487488int mStart = onePos + 1;489490// copy useless padding array for a constant-time method491byte [] tmp = new byte[mStart - padStart];492System.arraycopy(EM, padStart, tmp, 0, tmp.length);493494byte [] m = new byte[EM.length - mStart];495System.arraycopy(EM, mStart, m, 0, m.length);496497BadPaddingException bpe = new BadPaddingException("Decryption error");498499if (bp) {500throw bpe;501} else {502return m;503}504}505}506507508