Path: blob/master/src/java.base/share/classes/sun/security/provider/DSA.java
41159 views
/*1* Copyright (c) 1996, 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.provider;2627import java.io.*;28import java.util.*;29import java.math.BigInteger;30import java.nio.ByteBuffer;3132import java.security.*;33import java.security.SecureRandom;34import java.security.interfaces.*;35import java.security.spec.*;3637import sun.security.util.Debug;38import sun.security.util.DerValue;39import sun.security.util.DerInputStream;40import sun.security.util.DerOutputStream;41import sun.security.jca.JCAUtil;4243/**44* The Digital Signature Standard (using the Digital Signature45* Algorithm), as described in fips186-3 of the National Instute of46* Standards and Technology (NIST), using SHA digest algorithms47* from FIPS180-3.48*49* This file contains the signature implementation for the50* SHA1withDSA (DSS), SHA224withDSA, SHA256withDSA, SHA384withDSA,51* SHA512withDSA, SHA3-224withDSA, SHA3-256withDSA, SHA3-384withDSA,52* SHA3-512withDSA, as well as RawDSA, used by TLS among others.53* RawDSA expects the 20 byte SHA-1 digest as input via update rather54* than the original data like other signature implementations.55*56* In addition, IEEE P1363 signature format is supported. The57* corresponding implementation is registered under <sig>inP1363Format,58* e.g. SHA256withDSAinP1363Format.59*60* @author Benjamin Renaud61*62* @since 1.163*64* @see DSAPublicKey65* @see DSAPrivateKey66*/67abstract class DSA extends SignatureSpi {6869/* Are we debugging? */70private static final boolean debug = false;7172/* The number of bits used in exponent blinding */73private static final int BLINDING_BITS = 7;7475/* The constant component of the exponent blinding value */76private static final BigInteger BLINDING_CONSTANT =77BigInteger.valueOf(1 << BLINDING_BITS);7879/* The parameter object */80private DSAParams params;8182/* algorithm parameters */83private BigInteger presetP, presetQ, presetG;8485/* The public key, if any */86private BigInteger presetY;8788/* The private key, if any */89private BigInteger presetX;9091/* The RNG used to output a seed for generating k */92private SecureRandom signingRandom;9394/* The message digest object used */95private final MessageDigest md;9697/* The format. true for the IEEE P1363 format. false (default) for ASN.1 */98private final boolean p1363Format;99100/**101* Construct a blank DSA object. It must be102* initialized before being usable for signing or verifying.103*/104DSA(MessageDigest md) {105this(md, false);106}107108/**109* Construct a blank DSA object that will use the specified110* signature format. {@code p1363Format} should be {@code true} to111* use the IEEE P1363 format. If {@code p1363Format} is {@code false},112* the DER-encoded ASN.1 format will be used. The DSA object must be113* initialized before being usable for signing or verifying.114*/115DSA(MessageDigest md, boolean p1363Format) {116super();117this.md = md;118this.p1363Format = p1363Format;119}120121private static void checkKey(DSAParams params, int digestLen, String mdAlgo)122throws InvalidKeyException {123// FIPS186-3 states in sec4.2 that a hash function which provides124// a lower security strength than the (L, N) pair ordinarily should125// not be used.126int valueN = params.getQ().bitLength();127if (valueN > digestLen) {128throw new InvalidKeyException("The security strength of " +129mdAlgo + " digest algorithm is not sufficient for this key size");130}131}132133/**134* Initialize the DSA object with a DSA private key.135*136* @param privateKey the DSA private key137*138* @exception InvalidKeyException if the key is not a valid DSA private139* key.140*/141protected void engineInitSign(PrivateKey privateKey)142throws InvalidKeyException {143if (!(privateKey instanceof java.security.interfaces.DSAPrivateKey)) {144throw new InvalidKeyException("not a DSA private key: " +145privateKey);146}147148java.security.interfaces.DSAPrivateKey priv =149(java.security.interfaces.DSAPrivateKey)privateKey;150151// check for algorithm specific constraints before doing initialization152DSAParams params = priv.getParams();153if (params == null) {154throw new InvalidKeyException("DSA private key lacks parameters");155}156157// check key size against hash output size for signing158// skip this check for verification to minimize impact on existing apps159if (!"NullDigest20".equals(md.getAlgorithm())) {160checkKey(params, md.getDigestLength()*8, md.getAlgorithm());161}162163this.params = params;164this.presetX = priv.getX();165this.presetY = null;166this.presetP = params.getP();167this.presetQ = params.getQ();168this.presetG = params.getG();169this.md.reset();170}171/**172* Initialize the DSA object with a DSA public key.173*174* @param publicKey the DSA public key.175*176* @exception InvalidKeyException if the key is not a valid DSA public177* key.178*/179protected void engineInitVerify(PublicKey publicKey)180throws InvalidKeyException {181if (!(publicKey instanceof java.security.interfaces.DSAPublicKey)) {182throw new InvalidKeyException("not a DSA public key: " +183publicKey);184}185java.security.interfaces.DSAPublicKey pub =186(java.security.interfaces.DSAPublicKey)publicKey;187188// check for algorithm specific constraints before doing initialization189DSAParams params = pub.getParams();190if (params == null) {191throw new InvalidKeyException("DSA public key lacks parameters");192}193this.params = params;194this.presetY = pub.getY();195this.presetX = null;196this.presetP = params.getP();197this.presetQ = params.getQ();198this.presetG = params.getG();199this.md.reset();200}201202/**203* Update a byte to be signed or verified.204*/205protected void engineUpdate(byte b) {206md.update(b);207}208209/**210* Update an array of bytes to be signed or verified.211*/212protected void engineUpdate(byte[] data, int off, int len) {213md.update(data, off, len);214}215216protected void engineUpdate(ByteBuffer b) {217md.update(b);218}219220221/**222* Sign all the data thus far updated. The signature format is223* determined by {@code p1363Format}. If {@code p1363Format} is224* {@code false} (the default), then the signature is formatted225* according to the Canonical Encoding Rules, returned as a DER226* sequence of Integers, r and s. If {@code p1363Format} is227* {@code false}, the signature is returned in the IEEE P1363228* format, which is the concatenation or r and s.229*230* @return a signature block formatted according to the format231* indicated by {@code p1363Format}232*233* @exception SignatureException if the signature object was not234* properly initialized, or if another exception occurs.235*236* @see sun.security.DSA#engineUpdate237* @see sun.security.DSA#engineVerify238*/239protected byte[] engineSign() throws SignatureException {240BigInteger k = generateK(presetQ);241BigInteger r = generateR(presetP, presetQ, presetG, k);242BigInteger s = generateS(presetX, presetQ, r, k);243244if (p1363Format) {245// Return the concatenation of r and s246byte[] rBytes = r.toByteArray();247byte[] sBytes = s.toByteArray();248249int size = presetQ.bitLength() / 8;250byte[] outseq = new byte[size * 2];251252int rLength = rBytes.length;253int sLength = sBytes.length;254int i;255for (i = rLength; i > 0 && rBytes[rLength - i] == 0; i--);256257int j;258for (j = sLength;259j > 0 && sBytes[sLength - j] == 0; j--);260261System.arraycopy(rBytes, rLength - i, outseq, size - i, i);262System.arraycopy(sBytes, sLength - j, outseq, size * 2 - j, j);263264return outseq;265} else {266// Return the DER-encoded ASN.1 form267try {268DerOutputStream outseq = new DerOutputStream(100);269outseq.putInteger(r);270outseq.putInteger(s);271DerValue result = new DerValue(DerValue.tag_Sequence,272outseq.toByteArray());273274return result.toByteArray();275276} catch (IOException e) {277throw new SignatureException("error encoding signature");278}279}280}281282/**283* Verify all the data thus far updated.284*285* @param signature the alleged signature, encoded using the286* Canonical Encoding Rules, as a sequence of integers, r and s.287*288* @exception SignatureException if the signature object was not289* properly initialized, or if another exception occurs.290*291* @see sun.security.DSA#engineUpdate292* @see sun.security.DSA#engineSign293*/294protected boolean engineVerify(byte[] signature)295throws SignatureException {296return engineVerify(signature, 0, signature.length);297}298299/**300* Verify all the data thus far updated.301*302* @param signature the alleged signature, encoded using the303* format indicated by {@code p1363Format}. If {@code p1363Format}304* is {@code false} (the default), then the signature is formatted305* according to the Canonical Encoding Rules, as a DER sequence of306* Integers, r and s. If {@code p1363Format} is {@code false},307* the signature is in the IEEE P1363 format, which is the308* concatenation or r and s.309*310* @param offset the offset to start from in the array of bytes.311*312* @param length the number of bytes to use, starting at offset.313*314* @exception SignatureException if the signature object was not315* properly initialized, or if another exception occurs.316*317* @see sun.security.DSA#engineUpdate318* @see sun.security.DSA#engineSign319*/320protected boolean engineVerify(byte[] signature, int offset, int length)321throws SignatureException {322323BigInteger r = null;324BigInteger s = null;325326if (p1363Format) {327if ((length & 1) == 1) {328// length of signature byte array should be even329throw new SignatureException("invalid signature format");330}331int mid = length/2;332r = new BigInteger(Arrays.copyOfRange(signature, 0, mid));333s = new BigInteger(Arrays.copyOfRange(signature, mid, length));334} else {335// first decode the signature.336try {337// Enforce strict DER checking for signatures338DerInputStream in =339new DerInputStream(signature, offset, length, false);340DerValue[] values = in.getSequence(2);341342// check number of components in the read sequence343// and trailing data344if ((values.length != 2) || (in.available() != 0)) {345throw new IOException("Invalid encoding for signature");346}347r = values[0].getBigInteger();348s = values[1].getBigInteger();349} catch (IOException e) {350throw new SignatureException("Invalid encoding for signature", e);351}352}353354// some implementations do not correctly encode values in the ASN.1355// 2's complement format. force r and s to be positive in order to356// to validate those signatures357if (r.signum() < 0) {358r = new BigInteger(1, r.toByteArray());359}360if (s.signum() < 0) {361s = new BigInteger(1, s.toByteArray());362}363364if ((r.compareTo(presetQ) == -1) && (s.compareTo(presetQ) == -1)) {365BigInteger w = generateW(presetP, presetQ, presetG, s);366BigInteger v = generateV(presetY, presetP, presetQ, presetG, w, r);367return v.equals(r);368} else {369throw new SignatureException("invalid signature: out of range values");370}371}372373@Deprecated374protected void engineSetParameter(String key, Object param) {375throw new InvalidParameterException("No parameter accepted");376}377378@Override379protected void engineSetParameter(AlgorithmParameterSpec params)380throws InvalidAlgorithmParameterException {381if (params != null) {382throw new InvalidAlgorithmParameterException("No parameter accepted");383}384}385386@Deprecated387protected Object engineGetParameter(String key) {388return null;389}390391@Override392protected AlgorithmParameters engineGetParameters() {393return null;394}395396397private BigInteger generateR(BigInteger p, BigInteger q, BigInteger g,398BigInteger k) {399400// exponent blinding to hide information from timing channel401SecureRandom random = getSigningRandom();402// start with a random blinding component403BigInteger blindingValue = new BigInteger(BLINDING_BITS, random);404// add the fixed blinding component405blindingValue = blindingValue.add(BLINDING_CONSTANT);406// replace k with a blinded value that is congruent (mod q)407k = k.add(q.multiply(blindingValue));408409BigInteger temp = g.modPow(k, p);410return temp.mod(q);411}412413private BigInteger generateS(BigInteger x, BigInteger q,414BigInteger r, BigInteger k) throws SignatureException {415416byte[] s2;417try {418s2 = md.digest();419} catch (RuntimeException re) {420// Only for RawDSA due to its 20-byte length restriction421throw new SignatureException(re.getMessage());422}423// get the leftmost min(N, outLen) bits of the digest value424int nBytes = q.bitLength()/8;425if (nBytes < s2.length) {426s2 = Arrays.copyOfRange(s2, 0, nBytes);427}428BigInteger z = new BigInteger(1, s2);429BigInteger k1 = k.modInverse(q);430431return x.multiply(r).add(z).multiply(k1).mod(q);432}433434private BigInteger generateW(BigInteger p, BigInteger q,435BigInteger g, BigInteger s) {436return s.modInverse(q);437}438439private BigInteger generateV(BigInteger y, BigInteger p,440BigInteger q, BigInteger g, BigInteger w, BigInteger r)441throws SignatureException {442443byte[] s2;444try {445s2 = md.digest();446} catch (RuntimeException re) {447// Only for RawDSA due to its 20-byte length restriction448throw new SignatureException(re.getMessage());449}450// get the leftmost min(N, outLen) bits of the digest value451int nBytes = q.bitLength()/8;452if (nBytes < s2.length) {453s2 = Arrays.copyOfRange(s2, 0, nBytes);454}455BigInteger z = new BigInteger(1, s2);456457BigInteger u1 = z.multiply(w).mod(q);458BigInteger u2 = (r.multiply(w)).mod(q);459460BigInteger t1 = g.modPow(u1,p);461BigInteger t2 = y.modPow(u2,p);462BigInteger t3 = t1.multiply(t2);463BigInteger t5 = t3.mod(p);464return t5.mod(q);465}466467protected BigInteger generateK(BigInteger q) {468// Implementation defined in FIPS 186-4 AppendixB.2.1.469SecureRandom random = getSigningRandom();470byte[] kValue = new byte[(q.bitLength() + 7)/8 + 8];471472random.nextBytes(kValue);473return new BigInteger(1, kValue).mod(474q.subtract(BigInteger.ONE)).add(BigInteger.ONE);475}476477// Use the application-specified SecureRandom Object if provided.478// Otherwise, use our default SecureRandom Object.479protected SecureRandom getSigningRandom() {480if (signingRandom == null) {481if (appRandom != null) {482signingRandom = appRandom;483} else {484signingRandom = JCAUtil.getSecureRandom();485}486}487return signingRandom;488}489490/**491* Return a human readable rendition of the engine.492*/493public String toString() {494String printable = "DSA Signature";495if (presetP != null && presetQ != null && presetG != null) {496printable += "\n\tp: " + Debug.toHexString(presetP);497printable += "\n\tq: " + Debug.toHexString(presetQ);498printable += "\n\tg: " + Debug.toHexString(presetG);499} else {500printable += "\n\t P, Q or G not initialized.";501}502if (presetY != null) {503printable += "\n\ty: " + Debug.toHexString(presetY);504}505if (presetY == null && presetX == null) {506printable += "\n\tUNINIIALIZED";507}508return printable;509}510511/**512* SHA3-224withDSA implementation.513*/514public static final class SHA3_224withDSA extends DSA {515public SHA3_224withDSA() throws NoSuchAlgorithmException {516super(MessageDigest.getInstance("SHA3-224"));517}518}519520/**521* SHA3-224withDSA implementation that uses the IEEE P1363 format.522*/523public static final class SHA3_224withDSAinP1363Format extends DSA {524public SHA3_224withDSAinP1363Format() throws NoSuchAlgorithmException {525super(MessageDigest.getInstance("SHA3-224"), true);526}527}528529/**530* Standard SHA3-256withDSA implementation.531*/532public static final class SHA3_256withDSA extends DSA {533public SHA3_256withDSA() throws NoSuchAlgorithmException {534super(MessageDigest.getInstance("SHA3-256"));535}536}537538/**539* Standard SHA3-256withDSA implementation that uses the IEEE P1363 format.540*/541public static final class SHA3_256withDSAinP1363Format extends DSA {542public SHA3_256withDSAinP1363Format() throws NoSuchAlgorithmException {543super(MessageDigest.getInstance("SHA3-256"), true);544}545}546547/**548* Standard SHA3-384withDSA implementation.549*/550public static final class SHA3_384withDSA extends DSA {551public SHA3_384withDSA() throws NoSuchAlgorithmException {552super(MessageDigest.getInstance("SHA3-384"));553}554}555556/**557* Standard SHA3-384withDSA implementation that uses the IEEE P1363 format.558*/559public static final class SHA3_384withDSAinP1363Format extends DSA {560public SHA3_384withDSAinP1363Format() throws NoSuchAlgorithmException {561super(MessageDigest.getInstance("SHA3-384"), true);562}563}564565/**566* Standard SHA3-512withDSA implementation.567*/568public static final class SHA3_512withDSA extends DSA {569public SHA3_512withDSA() throws NoSuchAlgorithmException {570super(MessageDigest.getInstance("SHA3-512"));571}572}573574/**575* Standard SHA3-512withDSA implementation that uses the IEEE P1363 format.576*/577public static final class SHA3_512withDSAinP1363Format extends DSA {578public SHA3_512withDSAinP1363Format() throws NoSuchAlgorithmException {579super(MessageDigest.getInstance("SHA3-512"), true);580}581}582583/**584* Standard SHA224withDSA implementation as defined in FIPS186-3.585*/586public static final class SHA224withDSA extends DSA {587public SHA224withDSA() throws NoSuchAlgorithmException {588super(MessageDigest.getInstance("SHA-224"));589}590}591592/**593* SHA224withDSA implementation that uses the IEEE P1363 format.594*/595public static final class SHA224withDSAinP1363Format extends DSA {596public SHA224withDSAinP1363Format() throws NoSuchAlgorithmException {597super(MessageDigest.getInstance("SHA-224"), true);598}599}600601/**602* Standard SHA256withDSA implementation as defined in FIPS186-3.603*/604public static final class SHA256withDSA extends DSA {605public SHA256withDSA() throws NoSuchAlgorithmException {606super(MessageDigest.getInstance("SHA-256"));607}608}609610/**611* SHA256withDSA implementation that uses the IEEE P1363 format.612*/613public static final class SHA256withDSAinP1363Format extends DSA {614public SHA256withDSAinP1363Format() throws NoSuchAlgorithmException {615super(MessageDigest.getInstance("SHA-256"), true);616}617}618619/**620* Standard SHA384withDSA implementation as defined in FIPS186-3.621*/622public static final class SHA384withDSA extends DSA {623public SHA384withDSA() throws NoSuchAlgorithmException {624super(MessageDigest.getInstance("SHA-384"));625}626}627628/**629* SHA384withDSA implementation that uses the IEEE P1363 format.630*/631public static final class SHA384withDSAinP1363Format extends DSA {632public SHA384withDSAinP1363Format() throws NoSuchAlgorithmException {633super(MessageDigest.getInstance("SHA-384"), true);634}635}636637/**638* Standard SHA512withDSA implementation as defined in FIPS186-3.639*/640public static final class SHA512withDSA extends DSA {641public SHA512withDSA() throws NoSuchAlgorithmException {642super(MessageDigest.getInstance("SHA-512"));643}644}645646/**647* SHA512withDSA implementation that uses the IEEE P1363 format.648*/649public static final class SHA512withDSAinP1363Format extends DSA {650public SHA512withDSAinP1363Format() throws NoSuchAlgorithmException {651super(MessageDigest.getInstance("SHA-512"), true);652}653}654655/**656* Standard SHA1withDSA implementation.657*/658public static final class SHA1withDSA extends DSA {659public SHA1withDSA() throws NoSuchAlgorithmException {660super(MessageDigest.getInstance("SHA-1"));661}662}663664/**665* SHA1withDSA implementation that uses the IEEE P1363 format.666*/667public static final class SHA1withDSAinP1363Format extends DSA {668public SHA1withDSAinP1363Format() throws NoSuchAlgorithmException {669super(MessageDigest.getInstance("SHA-1"), true);670}671}672673/**674* Raw DSA.675*676* Raw DSA requires the data to be exactly 20 bytes long. If it is677* not, a SignatureException is thrown when sign()/verify() is called678* per JCA spec.679*/680static class Raw extends DSA {681// Internal special-purpose MessageDigest impl for RawDSA682// Only override whatever methods used683// NOTE: no clone support684public static final class NullDigest20 extends MessageDigest {685// 20 byte digest buffer686private final byte[] digestBuffer = new byte[20];687688// offset into the buffer; use Integer.MAX_VALUE to indicate689// out-of-bound condition690private int ofs = 0;691692protected NullDigest20() {693super("NullDigest20");694}695protected void engineUpdate(byte input) {696if (ofs == digestBuffer.length) {697ofs = Integer.MAX_VALUE;698} else {699digestBuffer[ofs++] = input;700}701}702protected void engineUpdate(byte[] input, int offset, int len) {703if (len > (digestBuffer.length - ofs)) {704ofs = Integer.MAX_VALUE;705} else {706System.arraycopy(input, offset, digestBuffer, ofs, len);707ofs += len;708}709}710protected final void engineUpdate(ByteBuffer input) {711int inputLen = input.remaining();712if (inputLen > (digestBuffer.length - ofs)) {713ofs = Integer.MAX_VALUE;714} else {715input.get(digestBuffer, ofs, inputLen);716ofs += inputLen;717}718}719protected byte[] engineDigest() throws RuntimeException {720if (ofs != digestBuffer.length) {721throw new RuntimeException722("Data for RawDSA must be exactly 20 bytes long");723}724reset();725return digestBuffer;726}727protected int engineDigest(byte[] buf, int offset, int len)728throws DigestException {729if (ofs != digestBuffer.length) {730throw new DigestException731("Data for RawDSA must be exactly 20 bytes long");732}733if (len < digestBuffer.length) {734throw new DigestException735("Output buffer too small; must be at least 20 bytes");736}737System.arraycopy(digestBuffer, 0, buf, offset, digestBuffer.length);738reset();739return digestBuffer.length;740}741742protected void engineReset() {743ofs = 0;744}745protected final int engineGetDigestLength() {746return digestBuffer.length;747}748}749750private Raw(boolean p1363Format) throws NoSuchAlgorithmException {751super(new NullDigest20(), p1363Format);752}753754}755756/**757* Standard Raw DSA implementation.758*/759public static final class RawDSA extends Raw {760public RawDSA() throws NoSuchAlgorithmException {761super(false);762}763}764765/**766* Raw DSA implementation that uses the IEEE P1363 format.767*/768public static final class RawDSAinP1363Format extends Raw {769public RawDSAinP1363Format() throws NoSuchAlgorithmException {770super(true);771}772}773}774775776