Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/security/rsa/RSAPSSSignature.java
38830 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-224, SHA-256, SHA-384, SHA-512, SHA-512/224, and48* SHA-512/256 message digest algorithms and MGF1 mask generation function.49*50* @since 851*/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<String, Integer> DIGEST_LENGTHS =84new Hashtable<String, Integer>();85static {86DIGEST_LENGTHS.put("SHA-1", 20);87DIGEST_LENGTHS.put("SHA", 20);88DIGEST_LENGTHS.put("SHA1", 20);89DIGEST_LENGTHS.put("SHA-224", 28);90DIGEST_LENGTHS.put("SHA224", 28);91DIGEST_LENGTHS.put("SHA-256", 32);92DIGEST_LENGTHS.put("SHA256", 32);93DIGEST_LENGTHS.put("SHA-384", 48);94DIGEST_LENGTHS.put("SHA384", 48);95DIGEST_LENGTHS.put("SHA-512", 64);96DIGEST_LENGTHS.put("SHA512", 64);97DIGEST_LENGTHS.put("SHA-512/224", 28);98DIGEST_LENGTHS.put("SHA512/224", 28);99DIGEST_LENGTHS.put("SHA-512/256", 32);100DIGEST_LENGTHS.put("SHA512/256", 32);101}102103// message digest implementation we use for hashing the data104private MessageDigest md;105// flag indicating whether the digest is reset106private boolean digestReset = true;107108// private key, if initialized for signing109private RSAPrivateKey privKey = null;110// public key, if initialized for verifying111private RSAPublicKey pubKey = null;112// PSS parameters from signatures and keys respectively113private PSSParameterSpec sigParams = null; // required for PSS signatures114115// PRNG used to generate salt bytes if none given116private SecureRandom random;117118/**119* Construct a new RSAPSSSignatur with arbitrary digest algorithm120*/121public RSAPSSSignature() {122this.md = null;123}124125// initialize for verification. See JCA doc126@Override127protected void engineInitVerify(PublicKey publicKey)128throws InvalidKeyException {129if (!(publicKey instanceof RSAPublicKey)) {130throw new InvalidKeyException("key must be RSAPublicKey");131}132this.pubKey = (RSAPublicKey) isValid((RSAKey)publicKey);133this.privKey = null;134resetDigest();135}136137// initialize for signing. See JCA doc138@Override139protected void engineInitSign(PrivateKey privateKey)140throws InvalidKeyException {141engineInitSign(privateKey, null);142}143144// initialize for signing. See JCA doc145@Override146protected void engineInitSign(PrivateKey privateKey, SecureRandom random)147throws InvalidKeyException {148if (!(privateKey instanceof RSAPrivateKey)) {149throw new InvalidKeyException("key must be RSAPrivateKey");150}151this.privKey = (RSAPrivateKey) isValid((RSAKey)privateKey);152this.pubKey = null;153this.random =154(random == null? JCAUtil.getSecureRandom() : random);155resetDigest();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 RSAKey and its associated parameters against209* internal signature parameters.210*/211private RSAKey isValid(RSAKey rsaKey) throws InvalidKeyException {212try {213AlgorithmParameterSpec keyParams = rsaKey.getParams();214// validate key parameters215if (!isCompatible(rsaKey.getParams(), this.sigParams)) {216throw new InvalidKeyException217("Key contains incompatible PSS parameter values");218}219// validate key length220if (this.sigParams != null) {221Integer hLen =222DIGEST_LENGTHS.get(this.sigParams.getDigestAlgorithm());223if (hLen == null) {224throw new ProviderException("Unsupported digest algo: " +225this.sigParams.getDigestAlgorithm());226}227checkKeyLength(rsaKey, hLen, this.sigParams.getSaltLength());228}229return rsaKey;230} catch (SignatureException e) {231throw new InvalidKeyException(e);232}233}234235/**236* Validate the specified Signature PSS parameters.237*/238private PSSParameterSpec validateSigParams(AlgorithmParameterSpec p)239throws InvalidAlgorithmParameterException {240if (p == null) {241throw new InvalidAlgorithmParameterException242("Parameters cannot be null");243}244if (!(p instanceof PSSParameterSpec)) {245throw new InvalidAlgorithmParameterException246("parameters must be type PSSParameterSpec");247}248// no need to validate again if same as current signature parameters249PSSParameterSpec params = (PSSParameterSpec) p;250if (params == this.sigParams) return params;251252RSAKey key = (this.privKey == null? this.pubKey : this.privKey);253// check against keyParams if set254if (key != null) {255if (!isCompatible(key.getParams(), params)) {256throw new InvalidAlgorithmParameterException257("Signature parameters does not match key parameters");258}259}260// now sanity check the parameter values261if (!(params.getMGFAlgorithm().equalsIgnoreCase("MGF1"))) {262throw new InvalidAlgorithmParameterException("Only supports MGF1");263264}265if (params.getTrailerField() != PSSParameterSpec.TRAILER_FIELD_BC) {266throw new InvalidAlgorithmParameterException267("Only supports TrailerFieldBC(1)");268269}270String digestAlgo = params.getDigestAlgorithm();271// check key length again272if (key != null) {273try {274int hLen = DIGEST_LENGTHS.get(digestAlgo);275checkKeyLength(key, hLen, params.getSaltLength());276} catch (SignatureException e) {277throw new InvalidAlgorithmParameterException(e);278}279}280return params;281}282283/**284* Ensure the object is initialized with key and parameters and285* reset digest286*/287private void ensureInit() throws SignatureException {288RSAKey key = (this.privKey == null? this.pubKey : this.privKey);289if (key == null) {290throw new SignatureException("Missing key");291}292if (this.sigParams == null) {293// Parameters are required for signature verification294throw new SignatureException295("Parameters required for RSASSA-PSS signatures");296}297}298299/**300* Utility method for checking key length against digest length and301* salt length302*/303private static void checkKeyLength(RSAKey key, int digestLen,304int saltLen) throws SignatureException {305if (key != null) {306int keyLength = (getKeyLengthInBits(key) + 7) >> 3;307int minLength = Math.addExact(Math.addExact(digestLen, saltLen), 2);308if (keyLength < minLength) {309throw new SignatureException310("Key is too short, need min " + minLength + " bytes");311}312}313}314315/**316* Reset the message digest if it is not already reset.317*/318private void resetDigest() {319if (digestReset == false) {320this.md.reset();321digestReset = true;322}323}324325/**326* Return the message digest value.327*/328private byte[] getDigestValue() {329digestReset = true;330return this.md.digest();331}332333// update the signature with the plaintext data. See JCA doc334@Override335protected void engineUpdate(byte b) throws SignatureException {336ensureInit();337this.md.update(b);338digestReset = false;339}340341// update the signature with the plaintext data. See JCA doc342@Override343protected void engineUpdate(byte[] b, int off, int len)344throws SignatureException {345ensureInit();346this.md.update(b, off, len);347digestReset = false;348}349350// update the signature with the plaintext data. See JCA doc351@Override352protected void engineUpdate(ByteBuffer b) {353try {354ensureInit();355} catch (SignatureException se) {356// hack for working around API bug357throw new RuntimeException(se.getMessage());358}359this.md.update(b);360digestReset = false;361}362363// sign the data and return the signature. See JCA doc364@Override365protected byte[] engineSign() throws SignatureException {366ensureInit();367byte[] mHash = getDigestValue();368try {369byte[] encoded = encodeSignature(mHash);370byte[] encrypted = RSACore.rsa(encoded, privKey, true);371return encrypted;372} catch (GeneralSecurityException e) {373throw new SignatureException("Could not sign data", e);374} catch (IOException e) {375throw new SignatureException("Could not encode data", e);376}377}378379// verify the data and return the result. See JCA doc380// should be reset to the state after engineInitVerify call.381@Override382protected boolean engineVerify(byte[] sigBytes) throws SignatureException {383ensureInit();384try {385if (sigBytes.length != RSACore.getByteLength(this.pubKey)) {386throw new SignatureException387("Signature length not correct: got "388+ sigBytes.length + " but was expecting "389+ RSACore.getByteLength(this.pubKey));390}391byte[] mHash = getDigestValue();392byte[] decrypted = RSACore.rsa(sigBytes, this.pubKey);393return decodeSignature(mHash, decrypted);394} catch (javax.crypto.BadPaddingException e) {395// occurs if the app has used the wrong RSA public key396// or if sigBytes is invalid397// return false rather than propagating the exception for398// compatibility/ease of use399return false;400} catch (IOException e) {401throw new SignatureException("Signature encoding error", e);402} finally {403resetDigest();404}405}406407// return the modulus length in bits408private static int getKeyLengthInBits(RSAKey k) {409if (k != null) {410return k.getModulus().bitLength();411}412return -1;413}414415/**416* Encode the digest 'mHash', return the to-be-signed data.417* Also used by the PKCS#11 provider.418*/419private byte[] encodeSignature(byte[] mHash)420throws IOException, DigestException {421AlgorithmParameterSpec mgfParams = this.sigParams.getMGFParameters();422String mgfDigestAlgo;423if (mgfParams != null) {424mgfDigestAlgo =425((MGF1ParameterSpec) mgfParams).getDigestAlgorithm();426} else {427mgfDigestAlgo = this.md.getAlgorithm();428}429try {430int emBits = getKeyLengthInBits(this.privKey) - 1;431int emLen = (emBits + 7) >> 3;432int hLen = this.md.getDigestLength();433int dbLen = emLen - hLen - 1;434int sLen = this.sigParams.getSaltLength();435436// maps DB into the corresponding region of EM and437// stores its bytes directly into EM438byte[] em = new byte[emLen];439440// step7 and some of step8441em[dbLen - sLen - 1] = (byte) 1; // set DB's padding2 into EM442em[em.length - 1] = (byte) 0xBC; // set trailer field of EM443444if (!digestReset) {445throw new ProviderException("Digest should be reset");446}447// step5: generates M' using padding1, mHash, and salt448this.md.update(EIGHT_BYTES_OF_ZEROS);449digestReset = false; // mark digest as it now has data450this.md.update(mHash);451if (sLen != 0) {452// step4: generate random salt453byte[] salt = new byte[sLen];454this.random.nextBytes(salt);455this.md.update(salt);456457// step8: set DB's salt into EM458System.arraycopy(salt, 0, em, dbLen - sLen, sLen);459}460// step6: generate H using M'461this.md.digest(em, dbLen, hLen); // set H field of EM462digestReset = true;463464// step7 and 8 are already covered by the code which setting up465// EM as above466467// step9 and 10: feed H into MGF and xor with DB in EM468MGF1 mgf1 = new MGF1(mgfDigestAlgo);469mgf1.generateAndXor(em, dbLen, hLen, dbLen, em, 0);470471// step11: set the leftmost (8emLen - emBits) bits of the leftmost472// octet to 0473int numZeroBits = (emLen << 3) - emBits;474475if (numZeroBits != 0) {476byte MASK = (byte) (0xff >>> numZeroBits);477em[0] = (byte) (em[0] & MASK);478}479480// step12: em should now holds maskedDB || hash h || 0xBC481return em;482} catch (NoSuchAlgorithmException e) {483throw new IOException(e.toString());484}485}486487/**488* Decode the signature data as under RFC8017 sec9.1.2 EMSA-PSS-VERIFY489*/490private boolean decodeSignature(byte[] mHash, byte[] em)491throws IOException {492int hLen = mHash.length;493int sLen = this.sigParams.getSaltLength();494int emBits = getKeyLengthInBits(this.pubKey) - 1;495int emLen = (emBits + 7) >> 3;496497// When key length is 8N+1 bits (N+1 bytes), emBits = 8N,498// emLen = N which is one byte shorter than em.length.499// Otherwise, emLen should be same as em.length500int emOfs = em.length - emLen;501if ((emOfs == 1) && (em[0] != 0)) {502return false;503}504505// step3506if (emLen < (hLen + sLen + 2)) {507return false;508}509510// step4511if (em[emOfs + emLen - 1] != (byte) 0xBC) {512return false;513}514515// step6: check if the leftmost (8emLen - emBits) bits of the leftmost516// octet are 0517int numZeroBits = (emLen << 3) - emBits;518519if (numZeroBits != 0) {520byte MASK = (byte) (0xff << (8 - numZeroBits));521if ((em[emOfs] & MASK) != 0) {522return false;523}524}525String mgfDigestAlgo;526AlgorithmParameterSpec mgfParams = this.sigParams.getMGFParameters();527if (mgfParams != null) {528mgfDigestAlgo =529((MGF1ParameterSpec) mgfParams).getDigestAlgorithm();530} else {531mgfDigestAlgo = this.md.getAlgorithm();532}533// step 7 and 8534int dbLen = emLen - hLen - 1;535try {536MGF1 mgf1 = new MGF1(mgfDigestAlgo);537mgf1.generateAndXor(em, emOfs + dbLen, hLen, dbLen,538em, emOfs);539} catch (NoSuchAlgorithmException nsae) {540throw new IOException(nsae.toString());541}542543// step9: set the leftmost (8emLen - emBits) bits of the leftmost544// octet to 0545if (numZeroBits != 0) {546byte MASK = (byte) (0xff >>> numZeroBits);547em[emOfs] = (byte) (em[emOfs] & MASK);548}549550// step10551int i = emOfs;552for (; i < emOfs + (dbLen - sLen - 1); i++) {553if (em[i] != 0) {554return false;555}556}557if (em[i] != 0x01) {558return false;559}560// step12 and 13561this.md.update(EIGHT_BYTES_OF_ZEROS);562digestReset = false;563this.md.update(mHash);564if (sLen > 0) {565this.md.update(em, emOfs + (dbLen - sLen), sLen);566}567byte[] digest2 = this.md.digest();568digestReset = true;569570// step14571byte[] digestInEM = Arrays.copyOfRange(em, emOfs + dbLen,572emOfs + emLen - 1);573return MessageDigest.isEqual(digest2, digestInEM);574}575576// set parameter, not supported. See JCA doc577@Deprecated578@Override579protected void engineSetParameter(String param, Object value)580throws InvalidParameterException {581throw new UnsupportedOperationException("setParameter() not supported");582}583584@Override585protected void engineSetParameter(AlgorithmParameterSpec params)586throws InvalidAlgorithmParameterException {587this.sigParams = validateSigParams(params);588// disallow changing parameters when digest has been used589if (!digestReset) {590throw new ProviderException591("Cannot set parameters during operations");592}593String newHashAlg = this.sigParams.getDigestAlgorithm();594// re-allocate md if not yet assigned or algorithm changed595if ((this.md == null) ||596!(this.md.getAlgorithm().equalsIgnoreCase(newHashAlg))) {597try {598this.md = MessageDigest.getInstance(newHashAlg);599} catch (NoSuchAlgorithmException nsae) {600// should not happen as we pick default digest algorithm601throw new InvalidAlgorithmParameterException602("Unsupported digest algorithm " +603newHashAlg, nsae);604}605}606}607608// get parameter, not supported. See JCA doc609@Deprecated610@Override611protected Object engineGetParameter(String param)612throws InvalidParameterException {613throw new UnsupportedOperationException("getParameter() not supported");614}615616@Override617protected AlgorithmParameters engineGetParameters() {618AlgorithmParameters ap = null;619if (this.sigParams != null) {620try {621ap = AlgorithmParameters.getInstance("RSASSA-PSS");622ap.init(this.sigParams);623} catch (GeneralSecurityException gse) {624throw new ProviderException(gse.getMessage());625}626}627return ap;628}629}630631632