From d7d1dcb5399c61cf2916ccc45aa25b0209c88712 Mon Sep 17 00:00:00 2001
From: zzz <zzz@mail.i2p>
Date: Tue, 12 Mar 2019 12:55:58 +0000
Subject: [PATCH] Crypto: Ed25519 check for S < L as in RFC 8032

Origin: https://github.com/i2p/i2p.i2p/commit/d7d1dcb5399c61cf2916ccc45aa25b0209c88712

---
 src/net/i2p/crypto/eddsa/EdDSAEngine.java | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/src/net/i2p/crypto/eddsa/EdDSAEngine.java b/src/net/i2p/crypto/eddsa/EdDSAEngine.java
index 1f0ba6d..9c55104 100644
--- a/src/net/i2p/crypto/eddsa/EdDSAEngine.java
+++ b/src/net/i2p/crypto/eddsa/EdDSAEngine.java
@@ -12,6 +12,7 @@
 package net.i2p.crypto.eddsa;
 
 import java.io.ByteArrayOutputStream;
+import java.math.BigInteger;
 import java.nio.ByteBuffer;
 import java.security.InvalidAlgorithmParameterException;
 import java.security.InvalidKeyException;
@@ -30,6 +31,7 @@ import net.i2p.crypto.eddsa.math.Curve;
 import net.i2p.crypto.eddsa.math.GroupElement;
 import net.i2p.crypto.eddsa.math.ScalarOps;
 import sun.security.x509.X509Key;
+import net.i2p.crypto.eddsa.math.bigint.BigIntegerLittleEndianEncoding;
 
 /**
  * Signing and verification for EdDSA.
@@ -69,6 +71,8 @@ import sun.security.x509.X509Key;
 public final class EdDSAEngine extends Signature {
     public static final String SIGNATURE_ALGORITHM = "NONEwithEdDSA";
 
+    private static final BigInteger ORDER = new BigInteger("2").pow(252).add(new BigInteger("27742317777372353535851937790883648493"));
+
     private MessageDigest digest;
     private ByteArrayOutputStream baos;
     private EdDSAKey key;
@@ -306,6 +310,11 @@ public final class EdDSAEngine extends Signature {
         h = key.getParams().getScalarOps().reduce(h);
 
         byte[] Sbyte = Arrays.copyOfRange(sigBytes, b/8, b/4);
+        // RFC 8032
+        BigInteger Sbigint = (new BigIntegerLittleEndianEncoding()).toBigInteger(Sbyte);
+        if (Sbigint.compareTo(ORDER) >= 0)
+            return false;
+
         // R = SB - H(Rbar,Abar,M)A
         GroupElement R = key.getParams().getB().doubleScalarMultiplyVariableTime(
                 ((EdDSAPublicKey) key).getNegativeA(), h, Sbyte);
-- 
2.33.0

