Path: blob/master/src/jdk.crypto.ec/share/classes/sun/security/ec/ECDSASignature.java
41161 views
/*1* Copyright (c) 2009, 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.ec;2627import java.nio.ByteBuffer;2829import java.security.*;30import java.security.interfaces.*;31import java.security.spec.*;32import java.util.Optional;3334import sun.security.jca.JCAUtil;35import sun.security.util.*;36import static sun.security.ec.ECOperations.IntermediateValueException;3738/**39* ECDSA signature implementation. This class currently supports the40* following algorithm names:41*42* . "NONEwithECDSA"43* . "SHA1withECDSA"44* . "SHA224withECDSA"45* . "SHA256withECDSA"46* . "SHA384withECDSA"47* . "SHA512withECDSA"48* . "SHA3-224withECDSA"49* . "SHA3-256withECDSA"50* . "SHA3-384withECDSA"51* . "SHA3-512withECDSA"52* . "NONEwithECDSAinP1363Format"53* . "SHA1withECDSAinP1363Format"54* . "SHA224withECDSAinP1363Format"55* . "SHA256withECDSAinP1363Format"56* . "SHA384withECDSAinP1363Format"57* . "SHA512withECDSAinP1363Format"58* . "SHA3-224withECDSAinP1363Format"59* . "SHA3-256withECDSAinP1363Format"60* . "SHA3-384withECDSAinP1363Format"61* . "SHA3-512withECDSAinP1363Format"62*63* @since 1.764*/65abstract class ECDSASignature extends SignatureSpi {6667// message digest implementation we use68private final MessageDigest messageDigest;6970// supplied entropy71private SecureRandom random;7273// flag indicating whether the digest has been reset74private boolean needsReset;7576// private key, if initialized for signing77private ECPrivateKey privateKey;7879// public key, if initialized for verifying80private ECPublicKey publicKey;8182// signature parameters83private ECParameterSpec sigParams = null;8485// The format. true for the IEEE P1363 format. false (default) for ASN.186private final boolean p1363Format;8788/**89* Constructs a new ECDSASignature.90*91* @exception ProviderException if the native ECC library is unavailable.92*/93ECDSASignature() {94this(false);95}9697/**98* Constructs a new ECDSASignature that will use the specified99* signature format. {@code p1363Format} should be {@code true} to100* use the IEEE P1363 format. If {@code p1363Format} is {@code false},101* the DER-encoded ASN.1 format will be used. This constructor is102* used by the RawECDSA subclasses.103*/104ECDSASignature(boolean p1363Format) {105this.messageDigest = null;106this.p1363Format = p1363Format;107}108109/**110* Constructs a new ECDSASignature. Used by subclasses.111*/112ECDSASignature(String digestName) {113this(digestName, false);114}115116/**117* Constructs a new ECDSASignature that will use the specified118* digest and signature format. {@code p1363Format} should be119* {@code true} to use the IEEE P1363 format. If {@code p1363Format}120* is {@code false}, the DER-encoded ASN.1 format will be used. This121* constructor is used by subclasses.122*/123ECDSASignature(String digestName, boolean p1363Format) {124try {125messageDigest = MessageDigest.getInstance(digestName);126} catch (NoSuchAlgorithmException e) {127throw new ProviderException(e);128}129this.needsReset = false;130this.p1363Format = p1363Format;131}132133// Class for Raw ECDSA signatures.134static class RawECDSA extends ECDSASignature {135136// the longest supported digest is 512 bits (SHA-512)137private static final int RAW_ECDSA_MAX = 64;138139private final byte[] precomputedDigest;140private int offset = 0;141142RawECDSA(boolean p1363Format) {143super(p1363Format);144precomputedDigest = new byte[RAW_ECDSA_MAX];145}146147// Stores the precomputed message digest value.148@Override149protected void engineUpdate(byte b) throws SignatureException {150if (offset >= precomputedDigest.length) {151offset = RAW_ECDSA_MAX + 1;152return;153}154precomputedDigest[offset++] = b;155}156157// Stores the precomputed message digest value.158@Override159protected void engineUpdate(byte[] b, int off, int len)160throws SignatureException {161if (offset >= precomputedDigest.length) {162offset = RAW_ECDSA_MAX + 1;163return;164}165System.arraycopy(b, off, precomputedDigest, offset, len);166offset += len;167}168169// Stores the precomputed message digest value.170@Override171protected void engineUpdate(ByteBuffer byteBuffer) {172int len = byteBuffer.remaining();173if (len <= 0) {174return;175}176if (len >= precomputedDigest.length - offset) {177offset = RAW_ECDSA_MAX + 1;178return;179}180byteBuffer.get(precomputedDigest, offset, len);181offset += len;182}183184@Override185protected void resetDigest() {186offset = 0;187}188189// Returns the precomputed message digest value.190@Override191protected byte[] getDigestValue() throws SignatureException {192if (offset > RAW_ECDSA_MAX) {193throw new SignatureException("Message digest is too long");194195}196byte[] result = new byte[offset];197System.arraycopy(precomputedDigest, 0, result, 0, offset);198offset = 0;199200return result;201}202}203204// Nested class for NONEwithECDSA signatures205public static final class Raw extends RawECDSA {206public Raw() {207super(false);208}209}210211// Nested class for NONEwithECDSAinP1363Format signatures212public static final class RawinP1363Format extends RawECDSA {213public RawinP1363Format() {214super(true);215}216}217218// Nested class for SHA1withECDSA signatures219public static final class SHA1 extends ECDSASignature {220public SHA1() {221super("SHA1");222}223}224225// Nested class for SHA1withECDSAinP1363Format signatures226public static final class SHA1inP1363Format extends ECDSASignature {227public SHA1inP1363Format() {228super("SHA1", true);229}230}231232// Nested class for SHA224withECDSA signatures233public static final class SHA224 extends ECDSASignature {234public SHA224() {235super("SHA-224");236}237}238239// Nested class for SHA224withECDSAinP1363Format signatures240public static final class SHA224inP1363Format extends ECDSASignature {241public SHA224inP1363Format() {242super("SHA-224", true);243}244}245246// Nested class for SHA256withECDSA signatures247public static final class SHA256 extends ECDSASignature {248public SHA256() {249super("SHA-256");250}251}252253// Nested class for SHA256withECDSAinP1363Format signatures254public static final class SHA256inP1363Format extends ECDSASignature {255public SHA256inP1363Format() {256super("SHA-256", true);257}258}259260// Nested class for SHA384withECDSA signatures261public static final class SHA384 extends ECDSASignature {262public SHA384() {263super("SHA-384");264}265}266267// Nested class for SHA384withECDSAinP1363Format signatures268public static final class SHA384inP1363Format extends ECDSASignature {269public SHA384inP1363Format() {270super("SHA-384", true);271}272}273274// Nested class for SHA512withECDSA signatures275public static final class SHA512 extends ECDSASignature {276public SHA512() {277super("SHA-512");278}279}280281// Nested class for SHA512withECDSAinP1363Format signatures282public static final class SHA512inP1363Format extends ECDSASignature {283public SHA512inP1363Format() {284super("SHA-512", true);285}286}287288// Nested class for SHA3_224withECDSA signatures289public static final class SHA3_224 extends ECDSASignature {290public SHA3_224() {291super("SHA3-224");292}293}294295// Nested class for SHA3_224withECDSAinP1363Format signatures296public static final class SHA3_224inP1363Format extends ECDSASignature {297public SHA3_224inP1363Format() {298super("SHA3-224", true);299}300}301302// Nested class for SHA3_256withECDSA signatures303public static final class SHA3_256 extends ECDSASignature {304public SHA3_256() {305super("SHA3-256");306}307}308309// Nested class for SHA3_256withECDSAinP1363Format signatures310public static final class SHA3_256inP1363Format extends ECDSASignature {311public SHA3_256inP1363Format() {312super("SHA3-256", true);313}314}315316// Nested class for SHA3_384withECDSA signatures317public static final class SHA3_384 extends ECDSASignature {318public SHA3_384() {319super("SHA3-384");320}321}322323// Nested class for SHA3_384withECDSAinP1363Format signatures324public static final class SHA3_384inP1363Format extends ECDSASignature {325public SHA3_384inP1363Format() {326super("SHA3-384", true);327}328}329330// Nested class for SHA3_512withECDSA signatures331public static final class SHA3_512 extends ECDSASignature {332public SHA3_512() {333super("SHA3-512");334}335}336337// Nested class for SHA3_512withECDSAinP1363Format signatures338public static final class SHA3_512inP1363Format extends ECDSASignature {339public SHA3_512inP1363Format() {340super("SHA3-512", true);341}342}343344// initialize for verification. See JCA doc345@Override346protected void engineInitVerify(PublicKey publicKey)347throws InvalidKeyException {348ECPublicKey key = (ECPublicKey) ECKeyFactory.toECKey(publicKey);349if (!isCompatible(this.sigParams, key.getParams())) {350throw new InvalidKeyException("Key params does not match signature params");351}352353// Should check that the supplied key is appropriate for signature354// algorithm (e.g. P-256 for SHA256withECDSA)355this.publicKey = key;356this.privateKey = null;357resetDigest();358}359360// initialize for signing. See JCA doc361@Override362protected void engineInitSign(PrivateKey privateKey)363throws InvalidKeyException {364engineInitSign(privateKey, null);365}366367// initialize for signing. See JCA doc368@Override369protected void engineInitSign(PrivateKey privateKey, SecureRandom random)370throws InvalidKeyException {371ECPrivateKey key = (ECPrivateKey) ECKeyFactory.toECKey(privateKey);372if (!isCompatible(this.sigParams, key.getParams())) {373throw new InvalidKeyException("Key params does not match signature params");374}375376// Should check that the supplied key is appropriate for signature377// algorithm (e.g. P-256 for SHA256withECDSA)378this.privateKey = key;379this.publicKey = null;380this.random = random;381resetDigest();382}383384/**385* Resets the message digest if needed.386*/387protected void resetDigest() {388if (needsReset) {389if (messageDigest != null) {390messageDigest.reset();391}392needsReset = false;393}394}395396/**397* Returns the message digest value.398*/399protected byte[] getDigestValue() throws SignatureException {400needsReset = false;401return messageDigest.digest();402}403404// update the signature with the plaintext data. See JCA doc405@Override406protected void engineUpdate(byte b) throws SignatureException {407messageDigest.update(b);408needsReset = true;409}410411// update the signature with the plaintext data. See JCA doc412@Override413protected void engineUpdate(byte[] b, int off, int len)414throws SignatureException {415messageDigest.update(b, off, len);416needsReset = true;417}418419// update the signature with the plaintext data. See JCA doc420@Override421protected void engineUpdate(ByteBuffer byteBuffer) {422int len = byteBuffer.remaining();423if (len <= 0) {424return;425}426427messageDigest.update(byteBuffer);428needsReset = true;429}430431private static boolean isCompatible(ECParameterSpec sigParams,432ECParameterSpec keyParams) {433if (sigParams == null) {434// no restriction on key param435return true;436}437return ECUtil.equals(sigParams, keyParams);438}439440private byte[] signDigestImpl(ECDSAOperations ops, int seedBits,441byte[] digest, ECPrivateKey priv, SecureRandom random)442throws SignatureException {443444byte[] seedBytes = new byte[(seedBits + 7) / 8];445byte[] s = priv instanceof ECPrivateKeyImpl446? ((ECPrivateKeyImpl)priv).getArrayS()447: ECUtil.sArray(priv.getS(), priv.getParams());448449// Attempt to create the signature in a loop that uses new random input450// each time. The chance of failure is very small assuming the451// implementation derives the nonce using extra bits452int numAttempts = 128;453for (int i = 0; i < numAttempts; i++) {454random.nextBytes(seedBytes);455ECDSAOperations.Seed seed = new ECDSAOperations.Seed(seedBytes);456try {457return ops.signDigest(s, digest, seed);458} catch (IntermediateValueException ex) {459// try again in the next iteration460}461}462463throw new SignatureException("Unable to produce signature after "464+ numAttempts + " attempts");465}466467468// sign the data and return the signature. See JCA doc469@Override470protected byte[] engineSign() throws SignatureException {471472if (random == null) {473random = JCAUtil.getSecureRandom();474}475476byte[] digest = getDigestValue();477ECParameterSpec params = privateKey.getParams();478479// seed is the key size + 64 bits480int seedBits = params.getOrder().bitLength() + 64;481Optional<ECDSAOperations> opsOpt =482ECDSAOperations.forParameters(params);483if (opsOpt.isEmpty()) {484throw new SignatureException("Curve not supported: " +485params.toString());486}487byte[] sig = signDigestImpl(opsOpt.get(), seedBits, digest, privateKey,488random);489490if (p1363Format) {491return sig;492} else {493return ECUtil.encodeSignature(sig);494}495}496497// verify the data and return the result. See JCA doc498@Override499protected boolean engineVerify(byte[] signature) throws SignatureException {500501byte[] sig;502if (p1363Format) {503sig = signature;504} else {505sig = ECUtil.decodeSignature(signature);506}507508byte[] digest = getDigestValue();509510Optional<ECDSAOperations> opsOpt =511ECDSAOperations.forParameters(publicKey.getParams());512if (opsOpt.isEmpty()) {513throw new SignatureException("Curve not supported: " +514publicKey.getParams().toString());515}516return opsOpt.get().verifySignedDigest(digest, sig, publicKey.getW());517}518519// set parameter, not supported. See JCA doc520@Override521@Deprecated522protected void engineSetParameter(String param, Object value)523throws InvalidParameterException {524throw new UnsupportedOperationException("setParameter() not supported");525}526527@Override528protected void engineSetParameter(AlgorithmParameterSpec params)529throws InvalidAlgorithmParameterException {530if (params != null && !(params instanceof ECParameterSpec)) {531throw new InvalidAlgorithmParameterException("No parameter accepted");532}533ECKey key = (this.privateKey == null? this.publicKey : this.privateKey);534if ((key != null) && !isCompatible((ECParameterSpec)params, key.getParams())) {535throw new InvalidAlgorithmParameterException536("Signature params does not match key params");537}538539sigParams = (ECParameterSpec) params;540}541542// get parameter, not supported. See JCA doc543@Override544@Deprecated545protected Object engineGetParameter(String param)546throws InvalidParameterException {547throw new UnsupportedOperationException("getParameter() not supported");548}549550@Override551protected AlgorithmParameters engineGetParameters() {552if (sigParams == null) {553return null;554}555try {556AlgorithmParameters ap = AlgorithmParameters.getInstance("EC");557ap.init(sigParams);558return ap;559} catch (Exception e) {560// should never happen561throw new ProviderException("Error retrieving EC parameters", e);562}563}564}565566567