Path: blob/master/src/java.base/share/classes/sun/security/rsa/RSAPSSSignature.java
67760 views
/*1* Copyright (c) 2018, 2021, 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.io.IOException;28import java.nio.ByteBuffer;2930import java.security.*;31import java.security.spec.AlgorithmParameterSpec;32import java.security.spec.PSSParameterSpec;33import java.security.spec.MGF1ParameterSpec;34import java.security.interfaces.*;3536import java.util.Arrays;37import java.util.Hashtable;3839import sun.security.util.*;40import sun.security.jca.JCAUtil;414243/**44* PKCS#1 v2.2 RSASSA-PSS signatures with various message digest algorithms.45* RSASSA-PSS implementation takes the message digest algorithm, MGF algorithm,46* and salt length values through the required signature PSS parameters.47* We support SHA-1, SHA-2 family and SHA3 family of message digest algorithms,48* and MGF1 mask generation function.49*50* @since 1151*/52public class RSAPSSSignature extends SignatureSpi {5354private static final boolean DEBUG = false;5556// utility method for comparing digest algorithms57// NOTE that first argument is assumed to be standard digest name58private boolean isDigestEqual(String stdAlg, String givenAlg) {59if (stdAlg == null || givenAlg == null) return false;6061if (givenAlg.indexOf("-") != -1) {62return stdAlg.equalsIgnoreCase(givenAlg);63} else {64if (stdAlg.equals("SHA-1")) {65return (givenAlg.equalsIgnoreCase("SHA")66|| givenAlg.equalsIgnoreCase("SHA1"));67} else {68StringBuilder sb = new StringBuilder(givenAlg);69// case-insensitive check70if (givenAlg.regionMatches(true, 0, "SHA", 0, 3)) {71givenAlg = sb.insert(3, "-").toString();72return stdAlg.equalsIgnoreCase(givenAlg);73} else {74throw new ProviderException("Unsupported digest algorithm "75+ givenAlg);76}77}78}79}8081private static final byte[] EIGHT_BYTES_OF_ZEROS = new byte[8];8283private static final Hashtable<KnownOIDs, Integer> DIGEST_LENGTHS =84new Hashtable<KnownOIDs, Integer>();85static {86DIGEST_LENGTHS.put(KnownOIDs.SHA_1, 20);87DIGEST_LENGTHS.put(KnownOIDs.SHA_224, 28);88DIGEST_LENGTHS.put(KnownOIDs.SHA_256, 32);89DIGEST_LENGTHS.put(KnownOIDs.SHA_384, 48);90DIGEST_LENGTHS.put(KnownOIDs.SHA_512, 64);91DIGEST_LENGTHS.put(KnownOIDs.SHA_512$224, 28);92DIGEST_LENGTHS.put(KnownOIDs.SHA_512$256, 32);93DIGEST_LENGTHS.put(KnownOIDs.SHA3_224, 28);94DIGEST_LENGTHS.put(KnownOIDs.SHA3_256, 32);95DIGEST_LENGTHS.put(KnownOIDs.SHA3_384, 48);96DIGEST_LENGTHS.put(KnownOIDs.SHA3_512, 64);97}9899// message digest implementation we use for hashing the data100private MessageDigest md;101// flag indicating whether the digest is reset102private boolean digestReset = true;103104// private key, if initialized for signing105private RSAPrivateKey privKey = null;106// public key, if initialized for verifying107private RSAPublicKey pubKey = null;108// PSS parameters from signatures and keys respectively109private PSSParameterSpec sigParams = null; // required for PSS signatures110111// PRNG used to generate salt bytes if none given112private SecureRandom random;113114/**115* Construct a new RSAPSSSignatur with arbitrary digest algorithm116*/117public RSAPSSSignature() {118this.md = null;119}120121// initialize for verification. See JCA doc122@Override123protected void engineInitVerify(PublicKey publicKey)124throws InvalidKeyException {125if (publicKey instanceof RSAPublicKey rsaPubKey) {126isPublicKeyValid(rsaPubKey);127this.pubKey = rsaPubKey;128this.privKey = null;129resetDigest();130} else {131throw new InvalidKeyException("key must be RSAPublicKey");132}133}134135// initialize for signing. See JCA doc136@Override137protected void engineInitSign(PrivateKey privateKey)138throws InvalidKeyException {139engineInitSign(privateKey, null);140}141142// initialize for signing. See JCA doc143@Override144protected void engineInitSign(PrivateKey privateKey, SecureRandom random)145throws InvalidKeyException {146if (privateKey instanceof RSAPrivateKey rsaPrivateKey) {147isPrivateKeyValid(rsaPrivateKey);148this.privKey = rsaPrivateKey;149this.pubKey = null;150this.random =151(random == null ? JCAUtil.getSecureRandom() : random);152resetDigest();153} else {154throw new InvalidKeyException("key must be RSAPrivateKey");155}156}157158/**159* Utility method for checking the key PSS parameters against signature160* PSS parameters.161* Returns false if any of the digest/MGF algorithms and trailerField162* values does not match or if the salt length in key parameters is163* larger than the value in signature parameters.164*/165private static boolean isCompatible(AlgorithmParameterSpec keyParams,166PSSParameterSpec sigParams) {167if (keyParams == null) {168// key with null PSS parameters means no restriction169return true;170}171if (!(keyParams instanceof PSSParameterSpec)) {172return false;173}174// nothing to compare yet, defer the check to when sigParams is set175if (sigParams == null) {176return true;177}178PSSParameterSpec pssKeyParams = (PSSParameterSpec) keyParams;179// first check the salt length requirement180if (pssKeyParams.getSaltLength() > sigParams.getSaltLength()) {181return false;182}183184// compare equality of the rest of fields based on DER encoding185PSSParameterSpec keyParams2 =186new PSSParameterSpec(pssKeyParams.getDigestAlgorithm(),187pssKeyParams.getMGFAlgorithm(),188pssKeyParams.getMGFParameters(),189sigParams.getSaltLength(),190pssKeyParams.getTrailerField());191PSSParameters ap = new PSSParameters();192// skip the JCA overhead193try {194ap.engineInit(keyParams2);195byte[] encoded = ap.engineGetEncoded();196ap.engineInit(sigParams);197byte[] encoded2 = ap.engineGetEncoded();198return Arrays.equals(encoded, encoded2);199} catch (Exception e) {200if (DEBUG) {201e.printStackTrace();202}203return false;204}205}206207/**208* Validate the specified RSAPrivateKey209*/210private void isPrivateKeyValid(RSAPrivateKey prKey) throws InvalidKeyException {211try {212if (prKey instanceof RSAPrivateCrtKey crtKey) {213if (RSAPrivateCrtKeyImpl.checkComponents(crtKey)) {214RSAKeyFactory.checkRSAProviderKeyLengths(215crtKey.getModulus().bitLength(),216crtKey.getPublicExponent());217} else {218throw new InvalidKeyException(219"Some of the CRT-specific components are not available");220}221} else {222RSAKeyFactory.checkRSAProviderKeyLengths(223prKey.getModulus().bitLength(),224null);225}226} catch (InvalidKeyException ikEx) {227throw ikEx;228} catch (Exception e) {229throw new InvalidKeyException(230"Can not access private key components", e);231}232isValid(prKey);233}234235/**236* Validate the specified RSAPublicKey237*/238private void isPublicKeyValid(RSAPublicKey pKey) throws InvalidKeyException {239try {240RSAKeyFactory.checkRSAProviderKeyLengths(241pKey.getModulus().bitLength(),242pKey.getPublicExponent());243} catch (InvalidKeyException ikEx) {244throw ikEx;245} catch (Exception e) {246throw new InvalidKeyException(247"Can not access public key components", e);248}249isValid(pKey);250}251252/**253* Validate the specified RSAKey and its associated parameters against254* internal signature parameters.255*/256private void isValid(RSAKey rsaKey) throws InvalidKeyException {257AlgorithmParameterSpec keyParams = rsaKey.getParams();258// validate key parameters259if (!isCompatible(rsaKey.getParams(), this.sigParams)) {260throw new InvalidKeyException261("Key contains incompatible PSS parameter values");262}263// validate key length264if (this.sigParams != null) {265String digestAlgo = this.sigParams.getDigestAlgorithm();266KnownOIDs ko = KnownOIDs.findMatch(digestAlgo);267if (ko != null) {268Integer hLen = DIGEST_LENGTHS.get(ko);269if (hLen != null) {270checkKeyLength(rsaKey, hLen,271this.sigParams.getSaltLength());272} else {273// should never happen; checked in validateSigParams()274throw new ProviderException275("Unsupported digest algo: " + digestAlgo);276}277} else {278// should never happen; checked in validateSigParams()279throw new ProviderException280("Unrecognized digest algo: " + digestAlgo);281}282}283}284285/**286* Validate the specified Signature PSS parameters.287*/288private PSSParameterSpec validateSigParams(AlgorithmParameterSpec p)289throws InvalidAlgorithmParameterException {290if (p == null) {291throw new InvalidAlgorithmParameterException292("Parameters cannot be null");293}294if (!(p instanceof PSSParameterSpec)) {295throw new InvalidAlgorithmParameterException296("parameters must be type PSSParameterSpec");297}298// no need to validate again if same as current signature parameters299PSSParameterSpec params = (PSSParameterSpec) p;300if (params == this.sigParams) return params;301302RSAKey key = (this.privKey == null? this.pubKey : this.privKey);303// check against keyParams if set304if (key != null) {305if (!isCompatible(key.getParams(), params)) {306throw new InvalidAlgorithmParameterException307("Signature parameters does not match key parameters");308}309}310// now sanity check the parameter values311if (!(params.getMGFAlgorithm().equalsIgnoreCase("MGF1"))) {312throw new InvalidAlgorithmParameterException("Only supports MGF1");313314}315if (params.getTrailerField() != PSSParameterSpec.TRAILER_FIELD_BC) {316throw new InvalidAlgorithmParameterException317("Only supports TrailerFieldBC(1)");318319}320321// check key length again322if (key != null) {323String digestAlgo = params.getDigestAlgorithm();324KnownOIDs ko = KnownOIDs.findMatch(digestAlgo);325if (ko != null) {326Integer hLen = DIGEST_LENGTHS.get(ko);327if (hLen != null) {328try {329checkKeyLength(key, hLen, params.getSaltLength());330} catch (InvalidKeyException e) {331throw new InvalidAlgorithmParameterException(e);332}333} else {334throw new InvalidAlgorithmParameterException335("Unsupported digest algo: " + digestAlgo);336}337} else {338throw new InvalidAlgorithmParameterException339("Unrecognized digest algo: " + digestAlgo);340}341}342return params;343}344345/**346* Ensure the object is initialized with key and parameters and347* reset digest348*/349private void ensureInit() throws SignatureException {350RSAKey key = (this.privKey == null? this.pubKey : this.privKey);351if (key == null) {352throw new SignatureException("Missing key");353}354if (this.sigParams == null) {355// Parameters are required for signature verification356throw new SignatureException357("Parameters required for RSASSA-PSS signatures");358}359}360361/**362* Utility method for checking key length against digest length and363* salt length364*/365private static void checkKeyLength(RSAKey key, int digestLen,366int saltLen) throws InvalidKeyException {367if (key != null) {368int keyLength = (getKeyLengthInBits(key) + 7) >> 3;369int minLength = Math.addExact(Math.addExact(digestLen, saltLen), 2);370if (keyLength < minLength) {371throw new InvalidKeyException372("Key is too short, need min " + minLength + " bytes");373}374}375}376377/**378* Reset the message digest if it is not already reset.379*/380private void resetDigest() {381if (digestReset == false) {382this.md.reset();383digestReset = true;384}385}386387/**388* Return the message digest value.389*/390private byte[] getDigestValue() {391digestReset = true;392return this.md.digest();393}394395// update the signature with the plaintext data. See JCA doc396@Override397protected void engineUpdate(byte b) throws SignatureException {398ensureInit();399this.md.update(b);400digestReset = false;401}402403// update the signature with the plaintext data. See JCA doc404@Override405protected void engineUpdate(byte[] b, int off, int len)406throws SignatureException {407ensureInit();408this.md.update(b, off, len);409digestReset = false;410}411412// update the signature with the plaintext data. See JCA doc413@Override414protected void engineUpdate(ByteBuffer b) {415try {416ensureInit();417} catch (SignatureException se) {418// workaround for API bug419throw new RuntimeException(se.getMessage());420}421this.md.update(b);422digestReset = false;423}424425// sign the data and return the signature. See JCA doc426@Override427protected byte[] engineSign() throws SignatureException {428ensureInit();429byte[] mHash = getDigestValue();430try {431byte[] encoded = encodeSignature(mHash);432byte[] encrypted = RSACore.rsa(encoded, privKey, true);433return encrypted;434} catch (GeneralSecurityException e) {435throw new SignatureException("Could not sign data", e);436} catch (IOException e) {437throw new SignatureException("Could not encode data", e);438}439}440441// verify the data and return the result. See JCA doc442// should be reset to the state after engineInitVerify call.443@Override444protected boolean engineVerify(byte[] sigBytes) throws SignatureException {445ensureInit();446try {447if (sigBytes.length != RSACore.getByteLength(this.pubKey)) {448throw new SignatureException449("Signature length not correct: got "450+ sigBytes.length + " but was expecting "451+ RSACore.getByteLength(this.pubKey));452}453byte[] mHash = getDigestValue();454byte[] decrypted = RSACore.rsa(sigBytes, this.pubKey);455return decodeSignature(mHash, decrypted);456} catch (javax.crypto.BadPaddingException e) {457// occurs if the app has used the wrong RSA public key458// or if sigBytes is invalid459// return false rather than propagating the exception for460// compatibility/ease of use461return false;462} catch (IOException e) {463throw new SignatureException("Signature encoding error", e);464} finally {465resetDigest();466}467}468469// return the modulus length in bits470private static int getKeyLengthInBits(RSAKey k) {471if (k != null) {472return k.getModulus().bitLength();473}474return -1;475}476477/**478* Encode the digest 'mHash', return the to-be-signed data.479* Also used by the PKCS#11 provider.480*/481private byte[] encodeSignature(byte[] mHash)482throws IOException, DigestException {483AlgorithmParameterSpec mgfParams = this.sigParams.getMGFParameters();484String mgfDigestAlgo;485if (mgfParams != null) {486mgfDigestAlgo =487((MGF1ParameterSpec) mgfParams).getDigestAlgorithm();488} else {489mgfDigestAlgo = this.md.getAlgorithm();490}491try {492int emBits = getKeyLengthInBits(this.privKey) - 1;493int emLen = (emBits + 7) >> 3;494int hLen = this.md.getDigestLength();495int dbLen = emLen - hLen - 1;496int sLen = this.sigParams.getSaltLength();497498// maps DB into the corresponding region of EM and499// stores its bytes directly into EM500byte[] em = new byte[emLen];501502// step7 and some of step8503em[dbLen - sLen - 1] = (byte) 1; // set DB's padding2 into EM504em[em.length - 1] = (byte) 0xBC; // set trailer field of EM505506if (!digestReset) {507throw new ProviderException("Digest should be reset");508}509// step5: generates M' using padding1, mHash, and salt510this.md.update(EIGHT_BYTES_OF_ZEROS);511digestReset = false; // mark digest as it now has data512this.md.update(mHash);513if (sLen != 0) {514// step4: generate random salt515byte[] salt = new byte[sLen];516this.random.nextBytes(salt);517this.md.update(salt);518519// step8: set DB's salt into EM520System.arraycopy(salt, 0, em, dbLen - sLen, sLen);521}522// step6: generate H using M'523this.md.digest(em, dbLen, hLen); // set H field of EM524digestReset = true;525526// step7 and 8 are already covered by the code which setting up527// EM as above528529// step9 and 10: feed H into MGF and xor with DB in EM530MGF1 mgf1 = new MGF1(mgfDigestAlgo);531mgf1.generateAndXor(em, dbLen, hLen, dbLen, em, 0);532533// step11: set the leftmost (8emLen - emBits) bits of the leftmost534// octet to 0535int numZeroBits = (emLen << 3) - emBits;536537if (numZeroBits != 0) {538byte MASK = (byte) (0xff >>> numZeroBits);539em[0] = (byte) (em[0] & MASK);540}541542// step12: em should now holds maskedDB || hash h || 0xBC543return em;544} catch (NoSuchAlgorithmException e) {545throw new IOException(e.toString());546}547}548549/**550* Decode the signature data as under RFC8017 sec9.1.2 EMSA-PSS-VERIFY551*/552private boolean decodeSignature(byte[] mHash, byte[] em)553throws IOException {554int hLen = mHash.length;555int sLen = this.sigParams.getSaltLength();556int emBits = getKeyLengthInBits(this.pubKey) - 1;557int emLen = (emBits + 7) >> 3;558559// When key length is 8N+1 bits (N+1 bytes), emBits = 8N,560// emLen = N which is one byte shorter than em.length.561// Otherwise, emLen should be same as em.length562int emOfs = em.length - emLen;563if ((emOfs == 1) && (em[0] != 0)) {564return false;565}566567// step3568if (emLen < (hLen + sLen + 2)) {569return false;570}571572// step4573if (em[emOfs + emLen - 1] != (byte) 0xBC) {574return false;575}576577// step6: check if the leftmost (8emLen - emBits) bits of the leftmost578// octet are 0579int numZeroBits = (emLen << 3) - emBits;580581if (numZeroBits != 0) {582byte MASK = (byte) (0xff << (8 - numZeroBits));583if ((em[emOfs] & MASK) != 0) {584return false;585}586}587String mgfDigestAlgo;588AlgorithmParameterSpec mgfParams = this.sigParams.getMGFParameters();589if (mgfParams != null) {590mgfDigestAlgo =591((MGF1ParameterSpec) mgfParams).getDigestAlgorithm();592} else {593mgfDigestAlgo = this.md.getAlgorithm();594}595// step 7 and 8596int dbLen = emLen - hLen - 1;597try {598MGF1 mgf1 = new MGF1(mgfDigestAlgo);599mgf1.generateAndXor(em, emOfs + dbLen, hLen, dbLen,600em, emOfs);601} catch (NoSuchAlgorithmException nsae) {602throw new IOException(nsae.toString());603}604605// step9: set the leftmost (8emLen - emBits) bits of the leftmost606// octet to 0607if (numZeroBits != 0) {608byte MASK = (byte) (0xff >>> numZeroBits);609em[emOfs] = (byte) (em[emOfs] & MASK);610}611612// step10613int i = emOfs;614for (; i < emOfs + (dbLen - sLen - 1); i++) {615if (em[i] != 0) {616return false;617}618}619if (em[i] != 0x01) {620return false;621}622// step12 and 13623this.md.update(EIGHT_BYTES_OF_ZEROS);624digestReset = false;625this.md.update(mHash);626if (sLen > 0) {627this.md.update(em, emOfs + (dbLen - sLen), sLen);628}629byte[] digest2 = this.md.digest();630digestReset = true;631632// step14633byte[] digestInEM = Arrays.copyOfRange(em, emOfs + dbLen,634emOfs + emLen - 1);635return MessageDigest.isEqual(digest2, digestInEM);636}637638// set parameter, not supported. See JCA doc639@Deprecated640@Override641protected void engineSetParameter(String param, Object value)642throws InvalidParameterException {643throw new UnsupportedOperationException("setParameter() not supported");644}645646@Override647protected void engineSetParameter(AlgorithmParameterSpec params)648throws InvalidAlgorithmParameterException {649this.sigParams = validateSigParams(params);650// disallow changing parameters when digest has been used651if (!digestReset) {652throw new ProviderException653("Cannot set parameters during operations");654}655String newHashAlg = this.sigParams.getDigestAlgorithm();656// re-allocate md if not yet assigned or algorithm changed657if ((this.md == null) ||658!(this.md.getAlgorithm().equalsIgnoreCase(newHashAlg))) {659try {660this.md = MessageDigest.getInstance(newHashAlg);661} catch (NoSuchAlgorithmException nsae) {662// should not happen as we pick default digest algorithm663throw new InvalidAlgorithmParameterException664("Unsupported digest algorithm " +665newHashAlg, nsae);666}667}668}669670// get parameter, not supported. See JCA doc671@Deprecated672@Override673protected Object engineGetParameter(String param)674throws InvalidParameterException {675throw new UnsupportedOperationException("getParameter() not supported");676}677678@Override679protected AlgorithmParameters engineGetParameters() {680AlgorithmParameters ap = null;681if (this.sigParams != null) {682try {683ap = AlgorithmParameters.getInstance("RSASSA-PSS");684ap.init(this.sigParams);685} catch (GeneralSecurityException gse) {686throw new ProviderException(gse.getMessage());687}688}689return ap;690}691}692693694