Debian Codegraph @

ext/ed25519_jruby/net/i2p/crypto/eddsa/EdDSAEngine.java

raw symbols SCIP
1 /**
2 * EdDSA-Java by str4d
3 *
4 * To the extent possible under law, the person who associated CC0 with
5 * EdDSA-Java has waived all copyright and related or neighboring rights
6 * to EdDSA-Java.
7 *
8 * You should have received a copy of the CC0 legalcode along with this
9 * work. If not, see <https://creativecommons.org/publicdomain/zero/1.0/>.
10 *
11 */
12 package net.i2p.crypto.eddsa;
13
14 import java.io.ByteArrayOutputStream;
15 import java.nio.ByteBuffer;
16 import java.security.InvalidAlgorithmParameterException;
17 import java.security.InvalidKeyException;
18 import java.security.MessageDigest;
19 import java.security.NoSuchAlgorithmException;
20 import java.security.PrivateKey;
21 import java.security.PublicKey;
22 import java.security.Signature;
23 import java.security.SignatureException;
24 import java.security.spec.AlgorithmParameterSpec;
25 import java.security.spec.InvalidKeySpecException;
26 import java.security.spec.X509EncodedKeySpec;
27 import java.util.Arrays;
28
29 import net.i2p.crypto.eddsa.math.Curve;
30 import net.i2p.crypto.eddsa.math.GroupElement;
31 import net.i2p.crypto.eddsa.math.ScalarOps;
32 import sun.security.x509.X509Key;
33
34 /**
35 * Signing and verification for EdDSA.
36 *<p>
37 * The EdDSA sign and verify algorithms do not interact well with
38 * the Java Signature API, as one or more update() methods must be
39 * called before sign() or verify(). Using the standard API,
40 * this implementation must copy and buffer all data passed in
41 * via update().
42 *</p><p>
43 * This implementation offers two ways to avoid this copying,
44 * but only if all data to be signed or verified is available
45 * in a single byte array.
46 *</p><p>
47 *Option 1:
48 *</p><ol>
49 *<li>Call initSign() or initVerify() as usual.
50 *</li><li>Call setParameter(ONE_SHOT_MODE)
51 *</li><li>Call update(byte[]) or update(byte[], int, int) exactly once
52 *</li><li>Call sign() or verify() as usual.
53 *</li><li>If doing additional one-shot signs or verifies with this object, you must
54 * call setParameter(ONE_SHOT_MODE) each time
55 *</li></ol>
56 *
57 *<p>
58 *Option 2:
59 *</p><ol>
60 *<li>Call initSign() or initVerify() as usual.
61 *</li><li>Call one of the signOneShot() or verifyOneShot() methods.
62 *</li><li>If doing additional one-shot signs or verifies with this object,
63 * just call signOneShot() or verifyOneShot() again.
64 *</li></ol>
65 *
66 * @author str4d
67 *
68 */
69 public final class EdDSAEngine extends Signature {
70 public static final String SIGNATURE_ALGORITHM = "NONEwithEdDSA";
71
72 private MessageDigest digest;
73 private ByteArrayOutputStream baos;
74 private EdDSAKey key;
75 private boolean oneShotMode;
76 private byte[] oneShotBytes;
77 private int oneShotOffset;
78 private int oneShotLength;
79
80 /**
81 * To efficiently sign or verify data in one shot, pass this to setParameters()
82 * after initSign() or initVerify() but BEFORE THE FIRST AND ONLY
83 * update(data) or update(data, off, len). The data reference will be saved
84 * and then used in sign() or verify() without copying the data.
85 * Violate these rules and you will get a SignatureException.
86 */
87 public static final AlgorithmParameterSpec ONE_SHOT_MODE = new OneShotSpec();
88
89 private static class OneShotSpec implements AlgorithmParameterSpec {}
90
91 /**
92 * No specific EdDSA-internal hash requested, allows any EdDSA key.
93 */
94 public EdDSAEngine() {
95 super(SIGNATURE_ALGORITHM);
96 }
97
98 /**
99 * Specific EdDSA-internal hash requested, only matching keys will be allowed.
100 * @param digest the hash algorithm that keys must have to sign or verify.
101 */
102 public EdDSAEngine(MessageDigest digest) {
103 this();
104 this.digest = digest;
105 }
106
107 private void reset() {
108 if (digest != null)
109 digest.reset();
110 if (baos != null)
111 baos.reset();
112 oneShotMode = false;
113 oneShotBytes = null;
114 }
115
116 @Override
117 protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException {
118 reset();
119 if (privateKey instanceof EdDSAPrivateKey) {
120 EdDSAPrivateKey privKey = (EdDSAPrivateKey) privateKey;
121 key = privKey;
122
123 if (digest == null) {
124 // Instantiate the digest from the key parameters
125 try {
126 digest = MessageDigest.getInstance(key.getParams().getHashAlgorithm());
127 } catch (NoSuchAlgorithmException e) {
128 throw new InvalidKeyException("cannot get required digest " + key.getParams().getHashAlgorithm() + " for private key.");
129 }
130 } else if (!key.getParams().getHashAlgorithm().equals(digest.getAlgorithm()))
131 throw new InvalidKeyException("Key hash algorithm does not match chosen digest");
132 digestInitSign(privKey);
133 } else {
134 throw new InvalidKeyException("cannot identify EdDSA private key: " + privateKey.getClass());
135 }
136 }
137
138 private void digestInitSign(EdDSAPrivateKey privKey) {
139 // Preparing for hash
140 // r = H(h_b,...,h_2b-1,M)
141 int b = privKey.getParams().getCurve().getField().getb();
142 digest.update(privKey.getH(), b/8, b/4 - b/8);
143 }
144
145 @Override
146 protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException {
147 reset();
148 if (publicKey instanceof EdDSAPublicKey) {
149 key = (EdDSAPublicKey) publicKey;
150
151 if (digest == null) {
152 // Instantiate the digest from the key parameters
153 try {
154 digest = MessageDigest.getInstance(key.getParams().getHashAlgorithm());
155 } catch (NoSuchAlgorithmException e) {
156 throw new InvalidKeyException("cannot get required digest " + key.getParams().getHashAlgorithm() + " for private key.");
157 }
158 } else if (!key.getParams().getHashAlgorithm().equals(digest.getAlgorithm()))
159 throw new InvalidKeyException("Key hash algorithm does not match chosen digest");
160 } else if (publicKey instanceof X509Key) {
161 // X509Certificate will sometimes contain an X509Key rather than the EdDSAPublicKey itself; the contained
162 // key is valid but needs to be instanced as an EdDSAPublicKey before it can be used.
163 EdDSAPublicKey parsedPublicKey;
164 try {
165 parsedPublicKey = new EdDSAPublicKey(new X509EncodedKeySpec(publicKey.getEncoded()));
166 } catch (InvalidKeySpecException ex) {
167 throw new InvalidKeyException("cannot handle X.509 EdDSA public key: " + publicKey.getAlgorithm());
168 }
169 engineInitVerify(parsedPublicKey);
170 } else {
171 throw new InvalidKeyException("cannot identify EdDSA public key: " + publicKey.getClass());
172 }
173 }
174
175 /**
176 * @throws SignatureException if in one-shot mode
177 */
178 @Override
179 protected void engineUpdate(byte b) throws SignatureException {
180 if (oneShotMode)
181 throw new SignatureException("unsupported in one-shot mode");
182 if (baos == null)
183 baos = new ByteArrayOutputStream(256);
184 baos.write(b);
185 }
186
187 /**
188 * @throws SignatureException if one-shot rules are violated
189 */
190 @Override
191 protected void engineUpdate(byte[] b, int off, int len)
192 throws SignatureException {
193 if (oneShotMode) {
194 if (oneShotBytes != null)
195 throw new SignatureException("update() already called");
196 oneShotBytes = b;
197 oneShotOffset = off;
198 oneShotLength = len;
199 } else {
200 if (baos == null)
201 baos = new ByteArrayOutputStream(256);
202 baos.write(b, off, len);
203 }
204 }
205
206 @Override
207 protected byte[] engineSign() throws SignatureException {
208 try {
209 return x_engineSign();
210 } finally {
211 reset();
212 // must leave the object ready to sign again with
213 // the same key, as required by the API
214 EdDSAPrivateKey privKey = (EdDSAPrivateKey) key;
215 digestInitSign(privKey);
216 }
217 }
218
219 private byte[] x_engineSign() throws SignatureException {
220 Curve curve = key.getParams().getCurve();
221 ScalarOps sc = key.getParams().getScalarOps();
222 byte[] a = ((EdDSAPrivateKey) key).geta();
223
224 byte[] message;
225 int offset, length;
226 if (oneShotMode) {
227 if (oneShotBytes == null)
228 throw new SignatureException("update() not called first");
229 message = oneShotBytes;
230 offset = oneShotOffset;
231 length = oneShotLength;
232 } else {
233 if (baos == null)
234 message = new byte[0];
235 else
236 message = baos.toByteArray();
237 offset = 0;
238 length = message.length;
239 }
240 // r = H(h_b,...,h_2b-1,M)
241 digest.update(message, offset, length);
242 byte[] r = digest.digest();
243
244 // r mod l
245 // Reduces r from 64 bytes to 32 bytes
246 r = sc.reduce(r);
247
248 // R = rB
249 GroupElement R = key.getParams().getB().scalarMultiply(r);
250 byte[] Rbyte = R.toByteArray();
251
252 // S = (r + H(Rbar,Abar,M)*a) mod l
253 digest.update(Rbyte);
254 digest.update(((EdDSAPrivateKey) key).getAbyte());
255 digest.update(message, offset, length);
256 byte[] h = digest.digest();
257 h = sc.reduce(h);
258 byte[] S = sc.multiplyAndAdd(h, a, r);
259
260 // R+S
261 int b = curve.getField().getb();
262 ByteBuffer out = ByteBuffer.allocate(b/4);
263 out.put(Rbyte).put(S);
264 return out.array();
265 }
266
267 @Override
268 protected boolean engineVerify(byte[] sigBytes) throws SignatureException {
269 try {
270 return x_engineVerify(sigBytes);
271 } finally {
272 reset();
273 }
274 }
275
276 private boolean x_engineVerify(byte[] sigBytes) throws SignatureException {
277 Curve curve = key.getParams().getCurve();
278 int b = curve.getField().getb();
279 if (sigBytes.length != b/4)
280 throw new SignatureException("signature length is wrong");
281
282 // R is first b/8 bytes of sigBytes, S is second b/8 bytes
283 digest.update(sigBytes, 0, b/8);
284 digest.update(((EdDSAPublicKey) key).getAbyte());
285 // h = H(Rbar,Abar,M)
286 byte[] message;
287 int offset, length;
288 if (oneShotMode) {
289 if (oneShotBytes == null)
290 throw new SignatureException("update() not called first");
291 message = oneShotBytes;
292 offset = oneShotOffset;
293 length = oneShotLength;
294 } else {
295 if (baos == null)
296 message = new byte[0];
297 else
298 message = baos.toByteArray();
299 offset = 0;
300 length = message.length;
301 }
302 digest.update(message, offset, length);
303 byte[] h = digest.digest();
304
305 // h mod l
306 h = key.getParams().getScalarOps().reduce(h);
307
308 byte[] Sbyte = Arrays.copyOfRange(sigBytes, b/8, b/4);
309 // R = SB - H(Rbar,Abar,M)A
310 GroupElement R = key.getParams().getB().doubleScalarMultiplyVariableTime(
311 ((EdDSAPublicKey) key).getNegativeA(), h, Sbyte);
312
313 // Variable time. This should be okay, because there are no secret
314 // values used anywhere in verification.
315 byte[] Rcalc = R.toByteArray();
316 for (int i = 0; i < Rcalc.length; i++) {
317 if (Rcalc[i] != sigBytes[i])
318 return false;
319 }
320 return true;
321 }
322
323 /**
324 * To efficiently sign all the data in one shot, if it is available,
325 * use this method, which will avoid copying the data.
326 *
327 * Same as:
328 *<pre>
329 * setParameter(ONE_SHOT_MODE)
330 * update(data)
331 * sig = sign()
332 *</pre>
333 *
334 * @param data the message to be signed
335 * @return the signature
336 * @throws SignatureException if update() already called
337 * @see #ONE_SHOT_MODE
338 */
339 public byte[] signOneShot(byte[] data) throws SignatureException {
340 return signOneShot(data, 0, data.length);
341 }
342
343 /**
344 * To efficiently sign all the data in one shot, if it is available,
345 * use this method, which will avoid copying the data.
346 *
347 * Same as:
348 *<pre>
349 * setParameter(ONE_SHOT_MODE)
350 * update(data, off, len)
351 * sig = sign()
352 *</pre>
353 *
354 * @param data byte array containing the message to be signed
355 * @param off the start of the message inside data
356 * @param len the length of the message
357 * @return the signature
358 * @throws SignatureException if update() already called
359 * @see #ONE_SHOT_MODE
360 */
361 public byte[] signOneShot(byte[] data, int off, int len) throws SignatureException {
362 oneShotMode = true;
363 update(data, off, len);
364 return sign();
365 }
366
367 /**
368 * To efficiently verify all the data in one shot, if it is available,
369 * use this method, which will avoid copying the data.
370 *
371 * Same as:
372 *<pre>
373 * setParameter(ONE_SHOT_MODE)
374 * update(data)
375 * ok = verify(signature)
376 *</pre>
377 *
378 * @param data the message that was signed
379 * @param signature of the message
380 * @return true if the signature is valid, false otherwise
381 * @throws SignatureException if update() already called
382 * @see #ONE_SHOT_MODE
383 */
384 public boolean verifyOneShot(byte[] data, byte[] signature) throws SignatureException {
385 return verifyOneShot(data, 0, data.length, signature, 0, signature.length);
386 }
387
388 /**
389 * To efficiently verify all the data in one shot, if it is available,
390 * use this method, which will avoid copying the data.
391 *
392 * Same as:
393 *<pre>
394 * setParameter(ONE_SHOT_MODE)
395 * update(data, off, len)
396 * ok = verify(signature)
397 *</pre>
398 *
399 * @param data byte array containing the message that was signed
400 * @param off the start of the message inside data
401 * @param len the length of the message
402 * @param signature of the message
403 * @return true if the signature is valid, false otherwise
404 * @throws SignatureException if update() already called
405 * @see #ONE_SHOT_MODE
406 */
407 public boolean verifyOneShot(byte[] data, int off, int len, byte[] signature) throws SignatureException {
408 return verifyOneShot(data, off, len, signature, 0, signature.length);
409 }
410
411 /**
412 * To efficiently verify all the data in one shot, if it is available,
413 * use this method, which will avoid copying the data.
414 *
415 * Same as:
416 *<pre>
417 * setParameter(ONE_SHOT_MODE)
418 * update(data)
419 * ok = verify(signature, sigoff, siglen)
420 *</pre>
421 *
422 * @param data the message that was signed
423 * @param signature byte array containing the signature
424 * @param sigoff the start of the signature
425 * @param siglen the length of the signature
426 * @return true if the signature is valid, false otherwise
427 * @throws SignatureException if update() already called
428 * @see #ONE_SHOT_MODE
429 */
430 public boolean verifyOneShot(byte[] data, byte[] signature, int sigoff, int siglen) throws SignatureException {
431 return verifyOneShot(data, 0, data.length, signature, sigoff, siglen);
432 }
433
434 /**
435 * To efficiently verify all the data in one shot, if it is available,
436 * use this method, which will avoid copying the data.
437 *
438 * Same as:
439 *<pre>
440 * setParameter(ONE_SHOT_MODE)
441 * update(data, off, len)
442 * ok = verify(signature, sigoff, siglen)
443 *</pre>
444 *
445 * @param data byte array containing the message that was signed
446 * @param off the start of the message inside data
447 * @param len the length of the message
448 * @param signature byte array containing the signature
449 * @param sigoff the start of the signature
450 * @param siglen the length of the signature
451 * @return true if the signature is valid, false otherwise
452 * @throws SignatureException if update() already called
453 * @see #ONE_SHOT_MODE
454 */
455 public boolean verifyOneShot(byte[] data, int off, int len, byte[] signature, int sigoff, int siglen) throws SignatureException {
456 oneShotMode = true;
457 update(data, off, len);
458 return verify(signature, sigoff, siglen);
459 }
460
461 /**
462 * @throws InvalidAlgorithmParameterException if spec is ONE_SHOT_MODE and update() already called
463 * @see #ONE_SHOT_MODE
464 */
465 @Override
466 protected void engineSetParameter(AlgorithmParameterSpec spec) throws InvalidAlgorithmParameterException {
467 if (spec.equals(ONE_SHOT_MODE)) {
468 if (oneShotBytes != null || (baos != null && baos.size() > 0))
469 throw new InvalidAlgorithmParameterException("update() already called");
470 oneShotMode = true;
471 } else {
472 super.engineSetParameter(spec);
473 }
474 }
475
476 /**
477 * @deprecated
478 */
479 @Override
480 protected void engineSetParameter(String param, Object value) {
481 throw new UnsupportedOperationException("engineSetParameter unsupported");
482 }
483
484 /**
485 * @deprecated
486 */
487 @Override
488 protected Object engineGetParameter(String param) {
489 throw new UnsupportedOperationException("engineSetParameter unsupported");
490 }
491 }