1 /*
2  * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 package sun.security.ec;
27 
28 import sun.security.ec.point.*;
29 import sun.security.util.ArrayUtil;
30 import sun.security.util.math.*;
31 import static sun.security.ec.ECOperations.IntermediateValueException;
32 
33 import java.security.ProviderException;
34 import java.security.spec.*;
35 import java.util.Arrays;
36 import java.util.Optional;
37 
38 public class ECDSAOperations {
39 
40     public static class Seed {
41         private final byte[] seedValue;
42 
Seed(byte[] seedValue)43         public Seed(byte[] seedValue) {
44             this.seedValue = seedValue;
45         }
46 
getSeedValue()47         public byte[] getSeedValue() {
48             return seedValue;
49         }
50     }
51 
52     public static class Nonce {
53         private final byte[] nonceValue;
54 
Nonce(byte[] nonceValue)55         public Nonce(byte[] nonceValue) {
56             this.nonceValue = nonceValue;
57         }
58 
getNonceValue()59         public byte[] getNonceValue() {
60             return nonceValue;
61         }
62     }
63 
64     private final ECOperations ecOps;
65     private final AffinePoint basePoint;
66 
ECDSAOperations(ECOperations ecOps, ECPoint basePoint)67     public ECDSAOperations(ECOperations ecOps, ECPoint basePoint) {
68         this.ecOps = ecOps;
69         this.basePoint = toAffinePoint(basePoint, ecOps.getField());
70     }
71 
getEcOperations()72     public ECOperations getEcOperations() {
73         return ecOps;
74     }
75 
basePointMultiply(byte[] scalar)76     public AffinePoint basePointMultiply(byte[] scalar) {
77         return ecOps.multiply(basePoint, scalar).asAffine();
78     }
79 
toAffinePoint(ECPoint point, IntegerFieldModuloP field)80     public static AffinePoint toAffinePoint(ECPoint point,
81         IntegerFieldModuloP field) {
82 
83         ImmutableIntegerModuloP affineX = field.getElement(point.getAffineX());
84         ImmutableIntegerModuloP affineY = field.getElement(point.getAffineY());
85         return new AffinePoint(affineX, affineY);
86     }
87 
88     public static
forParameters(ECParameterSpec ecParams)89     Optional<ECDSAOperations> forParameters(ECParameterSpec ecParams) {
90         Optional<ECOperations> curveOps =
91             ECOperations.forParameters(ecParams);
92         return curveOps.map(
93             ops -> new ECDSAOperations(ops, ecParams.getGenerator())
94         );
95     }
96 
97     /**
98      *
99      * Sign a digest using the provided private key and seed.
100      * IMPORTANT: The private key is a scalar represented using a
101      * little-endian byte array. This is backwards from the conventional
102      * representation in ECDSA. The routines that produce and consume this
103      * value uses little-endian, so this deviation from convention removes
104      * the requirement to swap the byte order. The returned signature is in
105      * the conventional byte order.
106      *
107      * @param privateKey the private key scalar as a little-endian byte array
108      * @param digest the digest to be signed
109      * @param seed the seed that will be used to produce the nonce. This object
110      *             should contain an array that is at least 64 bits longer than
111      *             the number of bits required to represent the group order.
112      * @return the ECDSA signature value
113      * @throws IntermediateValueException if the signature cannot be produced
114      *      due to an unacceptable intermediate or final value. If this
115      *      exception is thrown, then the caller should discard the nonnce and
116      *      try again with an entirely new nonce value.
117      */
signDigest(byte[] privateKey, byte[] digest, Seed seed)118     public byte[] signDigest(byte[] privateKey, byte[] digest, Seed seed)
119         throws IntermediateValueException {
120 
121         byte[] nonceArr = ecOps.seedToScalar(seed.getSeedValue());
122 
123         Nonce nonce = new Nonce(nonceArr);
124         return signDigest(privateKey, digest, nonce);
125     }
126 
127     /**
128      *
129      * Sign a digest using the provided private key and nonce.
130      * IMPORTANT: The private key and nonce are scalars represented by a
131      * little-endian byte array. This is backwards from the conventional
132      * representation in ECDSA. The routines that produce and consume these
133      * values use little-endian, so this deviation from convention removes
134      * the requirement to swap the byte order. The returned signature is in
135      * the conventional byte order.
136      *
137      * @param privateKey the private key scalar as a little-endian byte array
138      * @param digest the digest to be signed
139      * @param nonce the nonce object containing a little-endian scalar value.
140      * @return the ECDSA signature value
141      * @throws IntermediateValueException if the signature cannot be produced
142      *      due to an unacceptable intermediate or final value. If this
143      *      exception is thrown, then the caller should discard the nonnce and
144      *      try again with an entirely new nonce value.
145      */
signDigest(byte[] privateKey, byte[] digest, Nonce nonce)146     public byte[] signDigest(byte[] privateKey, byte[] digest, Nonce nonce)
147         throws IntermediateValueException {
148 
149         IntegerFieldModuloP orderField = ecOps.getOrderField();
150         int orderBits = orderField.getSize().bitLength();
151         if (orderBits % 8 != 0 && orderBits < digest.length * 8) {
152             // This implementation does not support truncating digests to
153             // a length that is not a multiple of 8.
154             throw new ProviderException("Invalid digest length");
155         }
156 
157         byte[] k = nonce.getNonceValue();
158         // check nonce length
159         int length = (orderField.getSize().bitLength() + 7) / 8;
160         if (k.length != length) {
161             throw new ProviderException("Incorrect nonce length");
162         }
163 
164         MutablePoint R = ecOps.multiply(basePoint, k);
165         IntegerModuloP r = R.asAffine().getX();
166         // put r into the correct field by fully reducing to an array
167         byte[] temp = new byte[length];
168         r = b2a(r, orderField, temp);
169         byte[] result = new byte[2 * length];
170         ArrayUtil.reverse(temp);
171         System.arraycopy(temp, 0, result, 0, length);
172         // compare r to 0
173         if (ECOperations.allZero(temp)) {
174             throw new IntermediateValueException();
175         }
176 
177         IntegerModuloP dU = orderField.getElement(privateKey);
178         int lengthE = Math.min(length, digest.length);
179         byte[] E = new byte[lengthE];
180         System.arraycopy(digest, 0, E, 0, lengthE);
181         ArrayUtil.reverse(E);
182         IntegerModuloP e = orderField.getElement(E);
183         IntegerModuloP kElem = orderField.getElement(k);
184         IntegerModuloP kInv = kElem.multiplicativeInverse();
185         MutableIntegerModuloP s = r.mutable();
186         s.setProduct(dU).setSum(e).setProduct(kInv);
187         // store s in result
188         s.asByteArray(temp);
189         ArrayUtil.reverse(temp);
190         System.arraycopy(temp, 0, result, length, length);
191         // compare s to 0
192         if (ECOperations.allZero(temp)) {
193             throw new IntermediateValueException();
194         }
195 
196         return result;
197 
198     }
verifySignedDigest(byte[] digest, byte[] sig, ECPoint pp)199     public boolean verifySignedDigest(byte[] digest, byte[] sig, ECPoint pp) {
200 
201         IntegerFieldModuloP field = ecOps.getField();
202         IntegerFieldModuloP orderField = ecOps.getOrderField();
203         int length = (orderField.getSize().bitLength() + 7) / 8;
204 
205         byte[] r;
206         byte[] s;
207 
208         int encodeLength = sig.length / 2;
209         if (sig.length %2 != 0 || encodeLength > length) {
210             return false;
211         } else if (encodeLength == length) {
212             r = Arrays.copyOf(sig, length);
213             s = Arrays.copyOfRange(sig, length, length * 2);
214         } else {
215             r = new byte[length];
216             s = new byte[length];
217             System.arraycopy(sig, 0, r, length - encodeLength, encodeLength);
218             System.arraycopy(sig, encodeLength, s, length - encodeLength, encodeLength);
219         }
220 
221         ArrayUtil.reverse(r);
222         ArrayUtil.reverse(s);
223         IntegerModuloP ri = orderField.getElement(r);
224         IntegerModuloP si = orderField.getElement(s);
225         // z
226         int lengthE = Math.min(length, digest.length);
227         byte[] E = new byte[lengthE];
228         System.arraycopy(digest, 0, E, 0, lengthE);
229         ArrayUtil.reverse(E);
230         IntegerModuloP e = orderField.getElement(E);
231 
232         IntegerModuloP sInv = si.multiplicativeInverse();
233         ImmutableIntegerModuloP u1 = e.multiply(sInv);
234         ImmutableIntegerModuloP u2 = ri.multiply(sInv);
235 
236         AffinePoint pub = new AffinePoint(field.getElement(pp.getAffineX()),
237                 field.getElement(pp.getAffineY()));
238 
239         byte[] temp1 = new byte[length];
240         b2a(u1, orderField, temp1);
241 
242         byte[] temp2 = new byte[length];
243         b2a(u2, orderField, temp2);
244 
245         MutablePoint p1 = ecOps.multiply(basePoint, temp1);
246         MutablePoint p2 = ecOps.multiply(pub, temp2);
247 
248         ecOps.setSum(p1, p2.asAffine());
249         IntegerModuloP result = p1.asAffine().getX();
250         result = result.additiveInverse().add(ri);
251 
252         b2a(result, orderField, temp1);
253         return ECOperations.allZero(temp1);
254     }
255 
b2a(IntegerModuloP b, IntegerFieldModuloP orderField, byte[] temp1)256     static public ImmutableIntegerModuloP b2a(IntegerModuloP b,
257             IntegerFieldModuloP orderField, byte[] temp1) {
258         b.asByteArray(temp1);
259         ImmutableIntegerModuloP b2 = orderField.getElement(temp1);
260         b2.asByteArray(temp1);
261         return b2;
262     }
263 }
264