1 /*
2  * Copyright (c) 2018, 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.Optional;
36 
37 public class ECDSAOperations {
38 
39     public static class Seed {
40         private final byte[] seedValue;
41 
Seed(byte[] seedValue)42         public Seed(byte[] seedValue) {
43             this.seedValue = seedValue;
44         }
45 
getSeedValue()46         public byte[] getSeedValue() {
47             return seedValue;
48         }
49     }
50 
51     public static class Nonce {
52         private final byte[] nonceValue;
53 
Nonce(byte[] nonceValue)54         public Nonce(byte[] nonceValue) {
55             this.nonceValue = nonceValue;
56         }
57 
getNonceValue()58         public byte[] getNonceValue() {
59             return nonceValue;
60         }
61     }
62 
63     private final ECOperations ecOps;
64     private final AffinePoint basePoint;
65 
ECDSAOperations(ECOperations ecOps, ECPoint basePoint)66     public ECDSAOperations(ECOperations ecOps, ECPoint basePoint) {
67         this.ecOps = ecOps;
68         this.basePoint = toAffinePoint(basePoint, ecOps.getField());
69     }
70 
getEcOperations()71     public ECOperations getEcOperations() {
72         return ecOps;
73     }
74 
basePointMultiply(byte[] scalar)75     public AffinePoint basePointMultiply(byte[] scalar) {
76         return ecOps.multiply(basePoint, scalar).asAffine();
77     }
78 
toAffinePoint(ECPoint point, IntegerFieldModuloP field)79     public static AffinePoint toAffinePoint(ECPoint point,
80         IntegerFieldModuloP field) {
81 
82         ImmutableIntegerModuloP affineX = field.getElement(point.getAffineX());
83         ImmutableIntegerModuloP affineY = field.getElement(point.getAffineY());
84         return new AffinePoint(affineX, affineY);
85     }
86 
87     public static
forParameters(ECParameterSpec ecParams)88     Optional<ECDSAOperations> forParameters(ECParameterSpec ecParams) {
89         Optional<ECOperations> curveOps =
90             ECOperations.forParameters(ecParams);
91         return curveOps.map(
92             ops -> new ECDSAOperations(ops, ecParams.getGenerator())
93         );
94     }
95 
96     /**
97      *
98      * Sign a digest using the provided private key and seed.
99      * IMPORTANT: The private key is a scalar represented using a
100      * little-endian byte array. This is backwards from the conventional
101      * representation in ECDSA. The routines that produce and consume this
102      * value uses little-endian, so this deviation from convention removes
103      * the requirement to swap the byte order. The returned signature is in
104      * the conventional byte order.
105      *
106      * @param privateKey the private key scalar as a little-endian byte array
107      * @param digest the digest to be signed
108      * @param seed the seed that will be used to produce the nonce. This object
109      *             should contain an array that is at least 64 bits longer than
110      *             the number of bits required to represent the group order.
111      * @return the ECDSA signature value
112      * @throws IntermediateValueException if the signature cannot be produced
113      *      due to an unacceptable intermediate or final value. If this
114      *      exception is thrown, then the caller should discard the nonnce and
115      *      try again with an entirely new nonce value.
116      */
signDigest(byte[] privateKey, byte[] digest, Seed seed)117     public byte[] signDigest(byte[] privateKey, byte[] digest, Seed seed)
118         throws IntermediateValueException {
119 
120         byte[] nonceArr = ecOps.seedToScalar(seed.getSeedValue());
121 
122         Nonce nonce = new Nonce(nonceArr);
123         return signDigest(privateKey, digest, nonce);
124     }
125 
126     /**
127      *
128      * Sign a digest using the provided private key and nonce.
129      * IMPORTANT: The private key and nonce are scalars represented by a
130      * little-endian byte array. This is backwards from the conventional
131      * representation in ECDSA. The routines that produce and consume these
132      * values use little-endian, so this deviation from convention removes
133      * the requirement to swap the byte order. The returned signature is in
134      * the conventional byte order.
135      *
136      * @param privateKey the private key scalar as a little-endian byte array
137      * @param digest the digest to be signed
138      * @param nonce the nonce object containing a little-endian scalar value.
139      * @return the ECDSA signature value
140      * @throws IntermediateValueException if the signature cannot be produced
141      *      due to an unacceptable intermediate or final value. If this
142      *      exception is thrown, then the caller should discard the nonnce and
143      *      try again with an entirely new nonce value.
144      */
signDigest(byte[] privateKey, byte[] digest, Nonce nonce)145     public byte[] signDigest(byte[] privateKey, byte[] digest, Nonce nonce)
146         throws IntermediateValueException {
147 
148         IntegerFieldModuloP orderField = ecOps.getOrderField();
149         int orderBits = orderField.getSize().bitLength();
150         if (orderBits % 8 != 0 && orderBits < digest.length * 8) {
151             // This implementation does not support truncating digests to
152             // a length that is not a multiple of 8.
153             throw new ProviderException("Invalid digest length");
154         }
155 
156         byte[] k = nonce.getNonceValue();
157         // check nonce length
158         int length = (orderField.getSize().bitLength() + 7) / 8;
159         if (k.length != length) {
160             throw new ProviderException("Incorrect nonce length");
161         }
162 
163         MutablePoint R = ecOps.multiply(basePoint, k);
164         IntegerModuloP r = R.asAffine().getX();
165         // put r into the correct field by fully reducing to an array
166         byte[] temp = new byte[length];
167         r.asByteArray(temp);
168         r = orderField.getElement(temp);
169         // store r in result
170         r.asByteArray(temp);
171         byte[] result = new byte[2 * length];
172         ArrayUtil.reverse(temp);
173         System.arraycopy(temp, 0, result, 0, length);
174         // compare r to 0
175         if (ECOperations.allZero(temp)) {
176             throw new IntermediateValueException();
177         }
178 
179         IntegerModuloP dU = orderField.getElement(privateKey);
180         int lengthE = Math.min(length, digest.length);
181         byte[] E = new byte[lengthE];
182         System.arraycopy(digest, 0, E, 0, lengthE);
183         ArrayUtil.reverse(E);
184         IntegerModuloP e = orderField.getElement(E);
185         IntegerModuloP kElem = orderField.getElement(k);
186         IntegerModuloP kInv = kElem.multiplicativeInverse();
187         MutableIntegerModuloP s = r.mutable();
188         s.setProduct(dU).setSum(e).setProduct(kInv);
189         // store s in result
190         s.asByteArray(temp);
191         ArrayUtil.reverse(temp);
192         System.arraycopy(temp, 0, result, length, length);
193         // compare s to 0
194         if (ECOperations.allZero(temp)) {
195             throw new IntermediateValueException();
196         }
197 
198         return result;
199 
200     }
201 
202 }
203