History

My first initial commit with all of mine experimental changes.

Dmitry Kabak (userdima committed 13 years ago

Commit d37b88d1 parent 3f5b46618352 files · +2598093 −-8690Browse files

Showing the changes to java/pkg/sun/security/ec/ECDSASignature.java (1 of 18352 files). Show all

Unified · Split

java/pkg/sun/security/ec/ECDSASignature.java+422−0
@@ -0,0 +1,422 @@
1/*
2 * Copyright (c) 2009, 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
26package sun.security.ec;
27
28import java.io.IOException;
29import java.nio.ByteBuffer;
30import java.math.BigInteger;
31import java.util.Arrays;
32
33import java.security.*;
34import java.security.interfaces.*;
35import java.security.spec.*;
36
37import sun.security.jca.JCAUtil;
38import sun.security.util.*;
39import sun.security.x509.AlgorithmId;
40
41/**
42 * ECDSA signature implementation. This class currently supports the
43 * following algorithm names:
44 *
45 * . "NONEwithECDSA"
46 * . "SHA1withECDSA"
47 * . "SHA256withECDSA"
48 * . "SHA384withECDSA"
49 * . "SHA512withECDSA"
50 *
51 * @since 1.7
52 */
53abstract class ECDSASignature extends SignatureSpi {
54
55 // message digest implementation we use
56 private final MessageDigest messageDigest;
57
58 // supplied entropy
59 private SecureRandom random;
60
61 // flag indicating whether the digest has been reset
62 private boolean needsReset;
63
64 // private key, if initialized for signing
65 private ECPrivateKey privateKey;
66
67 // public key, if initialized for verifying
68 private ECPublicKey publicKey;
69
70 /**
71 * Constructs a new ECDSASignature. Used by Raw subclass.
72 *
73 * @exception ProviderException if the native ECC library is unavailable.
74 */
75 ECDSASignature() {
76 messageDigest = null;
77 }
78
79 /**
80 * Constructs a new ECDSASignature. Used by subclasses.
81 */
82 ECDSASignature(String digestName) {
83 try {
84 messageDigest = MessageDigest.getInstance(digestName);
85 } catch (NoSuchAlgorithmException e) {
86 throw new ProviderException(e);
87 }
88 needsReset = false;
89 }
90
91 // Nested class for NONEwithECDSA signatures
92 public static final class Raw extends ECDSASignature {
93
94 // the longest supported digest is 512 bits (SHA-512)
95 private static final int RAW_ECDSA_MAX = 64;
96
97 private final byte[] precomputedDigest;
98 private int offset = 0;
99
100 public Raw() {
101 precomputedDigest = new byte[RAW_ECDSA_MAX];
102 }
103
104 // Stores the precomputed message digest value.
105 @Override
106 protected void engineUpdate(byte b) throws SignatureException {
107 if (offset >= precomputedDigest.length) {
108 offset = RAW_ECDSA_MAX + 1;
109 return;
110 }
111 precomputedDigest[offset++] = b;
112 }
113
114 // Stores the precomputed message digest value.
115 @Override
116 protected void engineUpdate(byte[] b, int off, int len)
117 throws SignatureException {
118 if (offset >= precomputedDigest.length) {
119 offset = RAW_ECDSA_MAX + 1;
120 return;
121 }
122 System.arraycopy(b, off, precomputedDigest, offset, len);
123 offset += len;
124 }
125
126 // Stores the precomputed message digest value.
127 @Override
128 protected void engineUpdate(ByteBuffer byteBuffer) {
129 int len = byteBuffer.remaining();
130 if (len <= 0) {
131 return;
132 }
133 if (offset + len >= precomputedDigest.length) {
134 offset = RAW_ECDSA_MAX + 1;
135 return;
136 }
137 byteBuffer.get(precomputedDigest, offset, len);
138 offset += len;
139 }
140
141 @Override
142 protected void resetDigest(){
143 offset = 0;
144 }
145
146 // Returns the precomputed message digest value.
147 @Override
148 protected byte[] getDigestValue() throws SignatureException {
149 if (offset > RAW_ECDSA_MAX) {
150 throw new SignatureException("Message digest is too long");
151
152 }
153 byte[] result = new byte[offset];
154 System.arraycopy(precomputedDigest, 0, result, 0, offset);
155 offset = 0;
156
157 return result;
158 }
159 }
160
161 // Nested class for SHA1withECDSA signatures
162 public static final class SHA1 extends ECDSASignature {
163 public SHA1() {
164 super("SHA1");
165 }
166 }
167
168 // Nested class for SHA256withECDSA signatures
169 public static final class SHA256 extends ECDSASignature {
170 public SHA256() {
171 super("SHA-256");
172 }
173 }
174
175 // Nested class for SHA384withECDSA signatures
176 public static final class SHA384 extends ECDSASignature {
177 public SHA384() {
178 super("SHA-384");
179 }
180 }
181
182 // Nested class for SHA512withECDSA signatures
183 public static final class SHA512 extends ECDSASignature {
184 public SHA512() {
185 super("SHA-512");
186 }
187 }
188
189 // initialize for verification. See JCA doc
190 @Override
191 protected void engineInitVerify(PublicKey publicKey)
192 throws InvalidKeyException {
193 this.publicKey = (ECPublicKey) ECKeyFactory.toECKey(publicKey);
194
195 // Should check that the supplied key is appropriate for signature
196 // algorithm (e.g. P-256 for SHA256withECDSA)
197 this.privateKey = null;
198 resetDigest();
199 }
200
201 // initialize for signing. See JCA doc
202 @Override
203 protected void engineInitSign(PrivateKey privateKey)
204 throws InvalidKeyException {
205 engineInitSign(privateKey, null);
206 }
207
208 // initialize for signing. See JCA doc
209 @Override
210 protected void engineInitSign(PrivateKey privateKey, SecureRandom random)
211 throws InvalidKeyException {
212 this.privateKey = (ECPrivateKey) ECKeyFactory.toECKey(privateKey);
213
214 // Should check that the supplied key is appropriate for signature
215 // algorithm (e.g. P-256 for SHA256withECDSA)
216 this.publicKey = null;
217 this.random = random;
218 resetDigest();
219 }
220
221 /**
222 * Resets the message digest if needed.
223 */
224 protected void resetDigest() {
225 if (needsReset) {
226 if (messageDigest != null) {
227 messageDigest.reset();
228 }
229 needsReset = false;
230 }
231 }
232
233 /**
234 * Returns the message digest value.
235 */
236 protected byte[] getDigestValue() throws SignatureException {
237 needsReset = false;
238 return messageDigest.digest();
239 }
240
241 // update the signature with the plaintext data. See JCA doc
242 @Override
243 protected void engineUpdate(byte b) throws SignatureException {
244 messageDigest.update(b);
245 needsReset = true;
246 }
247
248 // update the signature with the plaintext data. See JCA doc
249 @Override
250 protected void engineUpdate(byte[] b, int off, int len)
251 throws SignatureException {
252 messageDigest.update(b, off, len);
253 needsReset = true;
254 }
255
256 // update the signature with the plaintext data. See JCA doc
257 @Override
258 protected void engineUpdate(ByteBuffer byteBuffer) {
259 int len = byteBuffer.remaining();
260 if (len <= 0) {
261 return;
262 }
263
264 messageDigest.update(byteBuffer);
265 needsReset = true;
266 }
267
268 // sign the data and return the signature. See JCA doc
269 @Override
270 protected byte[] engineSign() throws SignatureException {
271 byte[] s = privateKey.getS().toByteArray();
272 ECParameterSpec params = privateKey.getParams();
273 byte[] encodedParams = ECParameters.encodeParameters(params); // DER OID
274 int keySize = params.getCurve().getField().getFieldSize();
275
276 // seed is twice the key size (in bytes) plus 1
277 byte[] seed = new byte[(((keySize + 7) >> 3) + 1) * 2];
278 if (random == null) {
279 random = JCAUtil.getSecureRandom();
280 }
281 random.nextBytes(seed);
282
283 try {
284
285 return encodeSignature(
286 signDigest(getDigestValue(), s, encodedParams, seed));
287
288 } catch (GeneralSecurityException e) {
289 throw new SignatureException("Could not sign data", e);
290 }
291 }
292
293 // verify the data and return the result. See JCA doc
294 @Override
295 protected boolean engineVerify(byte[] signature) throws SignatureException {
296
297 byte[] w;
298 ECParameterSpec params = publicKey.getParams();
299 byte[] encodedParams = ECParameters.encodeParameters(params); // DER OID
300
301 if (publicKey instanceof ECPublicKeyImpl) {
302 w = ((ECPublicKeyImpl)publicKey).getEncodedPublicValue();
303 } else { // instanceof ECPublicKey
304 w = ECParameters.encodePoint(publicKey.getW(), params.getCurve());
305 }
306
307 try {
308
309 return verifySignedDigest(
310 decodeSignature(signature), getDigestValue(), w, encodedParams);
311
312 } catch (GeneralSecurityException e) {
313 throw new SignatureException("Could not verify signature", e);
314 }
315 }
316
317 // set parameter, not supported. See JCA doc
318 @Override
319 protected void engineSetParameter(String param, Object value)
320 throws InvalidParameterException {
321 throw new UnsupportedOperationException("setParameter() not supported");
322 }
323
324 // get parameter, not supported. See JCA doc
325 @Override
326 protected Object engineGetParameter(String param)
327 throws InvalidParameterException {
328 throw new UnsupportedOperationException("getParameter() not supported");
329 }
330
331 // Convert the concatenation of R and S into their DER encoding
332 private byte[] encodeSignature(byte[] signature) throws SignatureException {
333
334 try {
335
336 int n = signature.length >> 1;
337 byte[] bytes = new byte[n];
338 System.arraycopy(signature, 0, bytes, 0, n);
339 BigInteger r = new BigInteger(1, bytes);
340 System.arraycopy(signature, n, bytes, 0, n);
341 BigInteger s = new BigInteger(1, bytes);
342
343 DerOutputStream out = new DerOutputStream(signature.length + 10);
344 out.putInteger(r);
345 out.putInteger(s);
346 DerValue result =
347 new DerValue(DerValue.tag_Sequence, out.toByteArray());
348
349 return result.toByteArray();
350
351 } catch (Exception e) {
352 throw new SignatureException("Could not encode signature", e);
353 }
354 }
355
356 // Convert the DER encoding of R and S into a concatenation of R and S
357 private byte[] decodeSignature(byte[] signature) throws SignatureException {
358
359 try {
360 DerInputStream in = new DerInputStream(signature);
361 DerValue[] values = in.getSequence(2);
362 BigInteger r = values[0].getPositiveBigInteger();
363 BigInteger s = values[1].getPositiveBigInteger();
364 // trim leading zeroes
365 byte[] rBytes = trimZeroes(r.toByteArray());
366 byte[] sBytes = trimZeroes(s.toByteArray());
367 int k = Math.max(rBytes.length, sBytes.length);
368 // r and s each occupy half the array
369 byte[] result = new byte[k << 1];
370 System.arraycopy(rBytes, 0, result, k - rBytes.length,
371 rBytes.length);
372 System.arraycopy(sBytes, 0, result, result.length - sBytes.length,
373 sBytes.length);
374 return result;
375
376 } catch (Exception e) {
377 throw new SignatureException("Could not decode signature", e);
378 }
379 }
380
381 // trim leading (most significant) zeroes from the result
382 private static byte[] trimZeroes(byte[] b) {
383 int i = 0;
384 while ((i < b.length - 1) && (b[i] == 0)) {
385 i++;
386 }
387 if (i == 0) {
388 return b;
389 }
390 byte[] t = new byte[b.length - i];
391 System.arraycopy(b, i, t, 0, t.length);
392 return t;
393 }
394
395 /**
396 * Signs the digest using the private key.
397 *
398 * @param digest the digest to be signed.
399 * @param s the private key's S value.
400 * @param encodedParams the curve's DER encoded object identifier.
401 * @param seed the random seed.
402 *
403 * @return byte[] the signature.
404 */
405 private static native byte[] signDigest(byte[] digest, byte[] s,
406 byte[] encodedParams, byte[] seed) throws GeneralSecurityException;
407
408 /**
409 * Verifies the signed digest using the public key.
410 *
411 * @param signedDigest the signature to be verified. It is encoded
412 * as a concatenation of the key's R and S values.
413 * @param digest the digest to be used.
414 * @param w the public key's W point (in uncompressed form).
415 * @param encodedParams the curve's DER encoded object identifier.
416 *
417 * @return boolean true if the signature is successfully verified.
418 */
419 private static native boolean verifySignedDigest(byte[] signature,
420 byte[] digest, byte[] w, byte[] encodedParams)
421 throws GeneralSecurityException;
422}

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t