Path: blob/master/src/java.base/share/classes/sun/security/rsa/RSAPSSSignature.java
41159 views
/*1* Copyright (c) 2018, 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.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)) {126throw new InvalidKeyException("key must be RSAPublicKey");127}128this.pubKey = (RSAPublicKey) isValid((RSAKey)publicKey);129this.privKey = null;130resetDigest();131}132133// initialize for signing. See JCA doc134@Override135protected void engineInitSign(PrivateKey privateKey)136throws InvalidKeyException {137engineInitSign(privateKey, null);138}139140// initialize for signing. See JCA doc141@Override142protected void engineInitSign(PrivateKey privateKey, SecureRandom random)143throws InvalidKeyException {144if (!(privateKey instanceof RSAPrivateKey)) {145throw new InvalidKeyException("key must be RSAPrivateKey");146}147this.privKey = (RSAPrivateKey) isValid((RSAKey)privateKey);148this.pubKey = null;149this.random =150(random == null? JCAUtil.getSecureRandom() : random);151resetDigest();152}153154/**155* Utility method for checking the key PSS parameters against signature156* PSS parameters.157* Returns false if any of the digest/MGF algorithms and trailerField158* values does not match or if the salt length in key parameters is159* larger than the value in signature parameters.160*/161private static boolean isCompatible(AlgorithmParameterSpec keyParams,162PSSParameterSpec sigParams) {163if (keyParams == null) {164// key with null PSS parameters means no restriction165return true;166}167if (!(keyParams instanceof PSSParameterSpec)) {168return false;169}170// nothing to compare yet, defer the check to when sigParams is set171if (sigParams == null) {172return true;173}174PSSParameterSpec pssKeyParams = (PSSParameterSpec) keyParams;175// first check the salt length requirement176if (pssKeyParams.getSaltLength() > sigParams.getSaltLength()) {177return false;178}179180// compare equality of the rest of fields based on DER encoding181PSSParameterSpec keyParams2 =182new PSSParameterSpec(pssKeyParams.getDigestAlgorithm(),183pssKeyParams.getMGFAlgorithm(),184pssKeyParams.getMGFParameters(),185sigParams.getSaltLength(),186pssKeyParams.getTrailerField());187PSSParameters ap = new PSSParameters();188// skip the JCA overhead189try {190ap.engineInit(keyParams2);191byte[] encoded = ap.engineGetEncoded();192ap.engineInit(sigParams);193byte[] encoded2 = ap.engineGetEncoded();194return Arrays.equals(encoded, encoded2);195} catch (Exception e) {196if (DEBUG) {197e.printStackTrace();198}199return false;200}201}202203/**204* Validate the specified RSAKey and its associated parameters against205* internal signature parameters.206*/207private RSAKey isValid(RSAKey rsaKey) throws InvalidKeyException {208AlgorithmParameterSpec keyParams = rsaKey.getParams();209// validate key parameters210if (!isCompatible(rsaKey.getParams(), this.sigParams)) {211throw new InvalidKeyException212("Key contains incompatible PSS parameter values");213}214// validate key length215if (this.sigParams != null) {216String digestAlgo = this.sigParams.getDigestAlgorithm();217KnownOIDs ko = KnownOIDs.findMatch(digestAlgo);218if (ko != null) {219Integer hLen = DIGEST_LENGTHS.get(ko);220if (hLen != null) {221checkKeyLength(rsaKey, hLen,222this.sigParams.getSaltLength());223} else {224// should never happen; checked in validateSigParams()225throw new ProviderException226("Unsupported digest algo: " + digestAlgo);227}228} else {229// should never happen; checked in validateSigParams()230throw new ProviderException231("Unrecognized digest algo: " + digestAlgo);232}233}234return rsaKey;235}236237/**238* Validate the specified Signature PSS parameters.239*/240private PSSParameterSpec validateSigParams(AlgorithmParameterSpec p)241throws InvalidAlgorithmParameterException {242if (p == null) {243throw new InvalidAlgorithmParameterException244("Parameters cannot be null");245}246if (!(p instanceof PSSParameterSpec)) {247throw new InvalidAlgorithmParameterException248("parameters must be type PSSParameterSpec");249}250// no need to validate again if same as current signature parameters251PSSParameterSpec params = (PSSParameterSpec) p;252if (params == this.sigParams) return params;253254RSAKey key = (this.privKey == null? this.pubKey : this.privKey);255// check against keyParams if set256if (key != null) {257if (!isCompatible(key.getParams(), params)) {258throw new InvalidAlgorithmParameterException259("Signature parameters does not match key parameters");260}261}262// now sanity check the parameter values263if (!(params.getMGFAlgorithm().equalsIgnoreCase("MGF1"))) {264throw new InvalidAlgorithmParameterException("Only supports MGF1");265266}267if (params.getTrailerField() != PSSParameterSpec.TRAILER_FIELD_BC) {268throw new InvalidAlgorithmParameterException269("Only supports TrailerFieldBC(1)");270271}272273// check key length again274if (key != null) {275String digestAlgo = params.getDigestAlgorithm();276KnownOIDs ko = KnownOIDs.findMatch(digestAlgo);277if (ko != null) {278Integer hLen = DIGEST_LENGTHS.get(ko);279if (hLen != null) {280try {281checkKeyLength(key, hLen, params.getSaltLength());282} catch (InvalidKeyException e) {283throw new InvalidAlgorithmParameterException(e);284}285} else {286throw new InvalidAlgorithmParameterException287("Unsupported digest algo: " + digestAlgo);288}289} else {290throw new InvalidAlgorithmParameterException291("Unrecognized digest algo: " + digestAlgo);292}293}294return params;295}296297/**298* Ensure the object is initialized with key and parameters and299* reset digest300*/301private void ensureInit() throws SignatureException {302RSAKey key = (this.privKey == null? this.pubKey : this.privKey);303if (key == null) {304throw new SignatureException("Missing key");305}306if (this.sigParams == null) {307// Parameters are required for signature verification308throw new SignatureException309("Parameters required for RSASSA-PSS signatures");310}311}312313/**314* Utility method for checking key length against digest length and315* salt length316*/317private static void checkKeyLength(RSAKey key, int digestLen,318int saltLen) throws InvalidKeyException {319if (key != null) {320int keyLength = (getKeyLengthInBits(key) + 7) >> 3;321int minLength = Math.addExact(Math.addExact(digestLen, saltLen), 2);322if (keyLength < minLength) {323throw new InvalidKeyException324("Key is too short, need min " + minLength + " bytes");325}326}327}328329/**330* Reset the message digest if it is not already reset.331*/332private void resetDigest() {333if (digestReset == false) {334this.md.reset();335digestReset = true;336}337}338339/**340* Return the message digest value.341*/342private byte[] getDigestValue() {343digestReset = true;344return this.md.digest();345}346347// update the signature with the plaintext data. See JCA doc348@Override349protected void engineUpdate(byte b) throws SignatureException {350ensureInit();351this.md.update(b);352digestReset = false;353}354355// update the signature with the plaintext data. See JCA doc356@Override357protected void engineUpdate(byte[] b, int off, int len)358throws SignatureException {359ensureInit();360this.md.update(b, off, len);361digestReset = false;362}363364// update the signature with the plaintext data. See JCA doc365@Override366protected void engineUpdate(ByteBuffer b) {367try {368ensureInit();369} catch (SignatureException se) {370// hack for working around API bug371throw new RuntimeException(se.getMessage());372}373this.md.update(b);374digestReset = false;375}376377// sign the data and return the signature. See JCA doc378@Override379protected byte[] engineSign() throws SignatureException {380ensureInit();381byte[] mHash = getDigestValue();382try {383byte[] encoded = encodeSignature(mHash);384byte[] encrypted = RSACore.rsa(encoded, privKey, true);385return encrypted;386} catch (GeneralSecurityException e) {387throw new SignatureException("Could not sign data", e);388} catch (IOException e) {389throw new SignatureException("Could not encode data", e);390}391}392393// verify the data and return the result. See JCA doc394// should be reset to the state after engineInitVerify call.395@Override396protected boolean engineVerify(byte[] sigBytes) throws SignatureException {397ensureInit();398try {399if (sigBytes.length != RSACore.getByteLength(this.pubKey)) {400throw new SignatureException401("Signature length not correct: got "402+ sigBytes.length + " but was expecting "403+ RSACore.getByteLength(this.pubKey));404}405byte[] mHash = getDigestValue();406byte[] decrypted = RSACore.rsa(sigBytes, this.pubKey);407return decodeSignature(mHash, decrypted);408} catch (javax.crypto.BadPaddingException e) {409// occurs if the app has used the wrong RSA public key410// or if sigBytes is invalid411// return false rather than propagating the exception for412// compatibility/ease of use413return false;414} catch (IOException e) {415throw new SignatureException("Signature encoding error", e);416} finally {417resetDigest();418}419}420421// return the modulus length in bits422private static int getKeyLengthInBits(RSAKey k) {423if (k != null) {424return k.getModulus().bitLength();425}426return -1;427}428429/**430* Encode the digest 'mHash', return the to-be-signed data.431* Also used by the PKCS#11 provider.432*/433private byte[] encodeSignature(byte[] mHash)434throws IOException, DigestException {435AlgorithmParameterSpec mgfParams = this.sigParams.getMGFParameters();436String mgfDigestAlgo;437if (mgfParams != null) {438mgfDigestAlgo =439((MGF1ParameterSpec) mgfParams).getDigestAlgorithm();440} else {441mgfDigestAlgo = this.md.getAlgorithm();442}443try {444int emBits = getKeyLengthInBits(this.privKey) - 1;445int emLen = (emBits + 7) >> 3;446int hLen = this.md.getDigestLength();447int dbLen = emLen - hLen - 1;448int sLen = this.sigParams.getSaltLength();449450// maps DB into the corresponding region of EM and451// stores its bytes directly into EM452byte[] em = new byte[emLen];453454// step7 and some of step8455em[dbLen - sLen - 1] = (byte) 1; // set DB's padding2 into EM456em[em.length - 1] = (byte) 0xBC; // set trailer field of EM457458if (!digestReset) {459throw new ProviderException("Digest should be reset");460}461// step5: generates M' using padding1, mHash, and salt462this.md.update(EIGHT_BYTES_OF_ZEROS);463digestReset = false; // mark digest as it now has data464this.md.update(mHash);465if (sLen != 0) {466// step4: generate random salt467byte[] salt = new byte[sLen];468this.random.nextBytes(salt);469this.md.update(salt);470471// step8: set DB's salt into EM472System.arraycopy(salt, 0, em, dbLen - sLen, sLen);473}474// step6: generate H using M'475this.md.digest(em, dbLen, hLen); // set H field of EM476digestReset = true;477478// step7 and 8 are already covered by the code which setting up479// EM as above480481// step9 and 10: feed H into MGF and xor with DB in EM482MGF1 mgf1 = new MGF1(mgfDigestAlgo);483mgf1.generateAndXor(em, dbLen, hLen, dbLen, em, 0);484485// step11: set the leftmost (8emLen - emBits) bits of the leftmost486// octet to 0487int numZeroBits = (emLen << 3) - emBits;488489if (numZeroBits != 0) {490byte MASK = (byte) (0xff >>> numZeroBits);491em[0] = (byte) (em[0] & MASK);492}493494// step12: em should now holds maskedDB || hash h || 0xBC495return em;496} catch (NoSuchAlgorithmException e) {497throw new IOException(e.toString());498}499}500501/**502* Decode the signature data as under RFC8017 sec9.1.2 EMSA-PSS-VERIFY503*/504private boolean decodeSignature(byte[] mHash, byte[] em)505throws IOException {506int hLen = mHash.length;507int sLen = this.sigParams.getSaltLength();508int emBits = getKeyLengthInBits(this.pubKey) - 1;509int emLen = (emBits + 7) >> 3;510511// When key length is 8N+1 bits (N+1 bytes), emBits = 8N,512// emLen = N which is one byte shorter than em.length.513// Otherwise, emLen should be same as em.length514int emOfs = em.length - emLen;515if ((emOfs == 1) && (em[0] != 0)) {516return false;517}518519// step3520if (emLen < (hLen + sLen + 2)) {521return false;522}523524// step4525if (em[emOfs + emLen - 1] != (byte) 0xBC) {526return false;527}528529// step6: check if the leftmost (8emLen - emBits) bits of the leftmost530// octet are 0531int numZeroBits = (emLen << 3) - emBits;532533if (numZeroBits != 0) {534byte MASK = (byte) (0xff << (8 - numZeroBits));535if ((em[emOfs] & MASK) != 0) {536return false;537}538}539String mgfDigestAlgo;540AlgorithmParameterSpec mgfParams = this.sigParams.getMGFParameters();541if (mgfParams != null) {542mgfDigestAlgo =543((MGF1ParameterSpec) mgfParams).getDigestAlgorithm();544} else {545mgfDigestAlgo = this.md.getAlgorithm();546}547// step 7 and 8548int dbLen = emLen - hLen - 1;549try {550MGF1 mgf1 = new MGF1(mgfDigestAlgo);551mgf1.generateAndXor(em, emOfs + dbLen, hLen, dbLen,552em, emOfs);553} catch (NoSuchAlgorithmException nsae) {554throw new IOException(nsae.toString());555}556557// step9: set the leftmost (8emLen - emBits) bits of the leftmost558// octet to 0559if (numZeroBits != 0) {560byte MASK = (byte) (0xff >>> numZeroBits);561em[emOfs] = (byte) (em[emOfs] & MASK);562}563564// step10565int i = emOfs;566for (; i < emOfs + (dbLen - sLen - 1); i++) {567if (em[i] != 0) {568return false;569}570}571if (em[i] != 0x01) {572return false;573}574// step12 and 13575this.md.update(EIGHT_BYTES_OF_ZEROS);576digestReset = false;577this.md.update(mHash);578if (sLen > 0) {579this.md.update(em, emOfs + (dbLen - sLen), sLen);580}581byte[] digest2 = this.md.digest();582digestReset = true;583584// step14585byte[] digestInEM = Arrays.copyOfRange(em, emOfs + dbLen,586emOfs + emLen - 1);587return MessageDigest.isEqual(digest2, digestInEM);588}589590// set parameter, not supported. See JCA doc591@Deprecated592@Override593protected void engineSetParameter(String param, Object value)594throws InvalidParameterException {595throw new UnsupportedOperationException("setParameter() not supported");596}597598@Override599protected void engineSetParameter(AlgorithmParameterSpec params)600throws InvalidAlgorithmParameterException {601this.sigParams = validateSigParams(params);602// disallow changing parameters when digest has been used603if (!digestReset) {604throw new ProviderException605("Cannot set parameters during operations");606}607String newHashAlg = this.sigParams.getDigestAlgorithm();608// re-allocate md if not yet assigned or algorithm changed609if ((this.md == null) ||610!(this.md.getAlgorithm().equalsIgnoreCase(newHashAlg))) {611try {612this.md = MessageDigest.getInstance(newHashAlg);613} catch (NoSuchAlgorithmException nsae) {614// should not happen as we pick default digest algorithm615throw new InvalidAlgorithmParameterException616("Unsupported digest algorithm " +617newHashAlg, nsae);618}619}620}621622// get parameter, not supported. See JCA doc623@Deprecated624@Override625protected Object engineGetParameter(String param)626throws InvalidParameterException {627throw new UnsupportedOperationException("getParameter() not supported");628}629630@Override631protected AlgorithmParameters engineGetParameters() {632AlgorithmParameters ap = null;633if (this.sigParams != null) {634try {635ap = AlgorithmParameters.getInstance("RSASSA-PSS");636ap.init(this.sigParams);637} catch (GeneralSecurityException gse) {638throw new ProviderException(gse.getMessage());639}640}641return ap;642}643}644645646