package org.bouncycastle.crypto.signers;

import java.math.BigInteger;
import java.security.SecureRandom;

import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.DSA;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECKeyParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.math.ec.ECAlgorithms;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECFieldElement;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.util.Arrays;

/**
 * DSTU 4145-2002
 * <p>
 * National Ukrainian standard of digital signature based on elliptic curves (DSTU 4145-2002).
 * </p>
 */
public class DSTU4145Signer
    implements DSA
{
    private static final BigInteger ONE = BigInteger.valueOf(1);

    private ECKeyParameters key;
    private SecureRandom random;

    public void init(boolean forSigning, CipherParameters param)
    {
        if (forSigning)
        {
            if (param instanceof ParametersWithRandom)
            {
                ParametersWithRandom rParam = (ParametersWithRandom)param;

                this.random = rParam.getRandom();
                param = rParam.getParameters();
            }
            else
            {
                this.random = new SecureRandom();
            }

            this.key = (ECPrivateKeyParameters)param;
        }
        else
        {
            this.key = (ECPublicKeyParameters)param;
        }

    }

    public BigInteger[] generateSignature(byte[] message)
    {
        ECDomainParameters parameters = key.getParameters();

        ECCurve curve = parameters.getCurve();

        ECFieldElement h = hash2FieldElement(curve, message);
        if (h.isZero())
        {
            h = curve.fromBigInteger(ONE);
        }

        BigInteger n = parameters.getN();
        BigInteger e, r, s;
        ECFieldElement Fe, y;

        do
        {
            do
            {
                do
                {
                    e = generateRandomInteger(n, random);
                    Fe = parameters.getG().multiply(e).normalize().getAffineXCoord();
                }
                while (Fe.isZero());

                y = h.multiply(Fe);
                r = fieldElement2Integer(n, y);
            }
            while (r.signum() == 0);

            s = r.multiply(((ECPrivateKeyParameters)key).getD()).add(e).mod(n);
        }
        while (s.signum() == 0);

        return new BigInteger[]{r, s};
    }

    public boolean verifySignature(byte[] message, BigInteger r, BigInteger s)
    {
        if (r.signum() <= 0 || s.signum() <= 0)
        {
            return false;
        }

        ECDomainParameters parameters = key.getParameters();

        BigInteger n = parameters.getN();
        if (r.compareTo(n) >= 0 || s.compareTo(n) >= 0)
        {
            return false;
        }

        ECCurve curve = parameters.getCurve();

        ECFieldElement h = hash2FieldElement(curve, message);
        if (h.isZero())
        {
            h = curve.fromBigInteger(ONE);
        }

        ECPoint R = ECAlgorithms.sumOfTwoMultiplies(parameters.getG(), s, ((ECPublicKeyParameters)key).getQ(), r).normalize();

        // components must be bogus.
        if (R.isInfinity())
        {
            return false;
        }

        ECFieldElement y = h.multiply(R.getAffineXCoord());
        return fieldElement2Integer(n, y).compareTo(r) == 0;
    }

    /**
     * Generates random integer such, than its bit length is less than that of n
     */
    private static BigInteger generateRandomInteger(BigInteger n, SecureRandom random)
    {
        return new BigInteger(n.bitLength() - 1, random);
    }
    
    private static void reverseBytes(byte[] bytes)
    {
        byte tmp;
        
        for (int i=0; i<bytes.length/2; i++)
        {
            tmp=bytes[i];
            bytes[i]=bytes[bytes.length-1-i];
            bytes[bytes.length-1-i]=tmp;
        }
    }

    private static ECFieldElement hash2FieldElement(ECCurve curve, byte[] hash)
    {
        byte[] data = Arrays.clone(hash);
        reverseBytes(data);
        BigInteger num = new BigInteger(1, data);
        while (num.bitLength() > curve.getFieldSize())
        {
            num = num.clearBit(num.bitLength() - 1);
        }

        return curve.fromBigInteger(num);
    }

    private static BigInteger fieldElement2Integer(BigInteger n, ECFieldElement fieldElement)
    {
        BigInteger num = fieldElement.toBigInteger();
        while (num.bitLength() >= n.bitLength())
        {
            num = num.clearBit(num.bitLength() - 1);
        }

        return num;
    }
}

@@ -3857,281 +3857,8 @@
    %7D
-%0A    %0A    private static void reverseBytes(byte%5B%5D bytes)%0A    %7B%0A        byte tmp;%0A        %0A        for (int i=0; i%3Cbytes.length/2; i++)%0A        %7B%0A            tmp=bytes%5Bi%5D;%0A            bytes%5Bi%5D=bytes%5Bbytes.length-1-i%5D;%0A            bytes%5Bbytes.length-1-i%5D=tmp;%0A        %7D%0A    %7D
 %0A%0A  
@@ -3974,12 +3974,14 @@
 ays.
-clon
+revers
 e(ha
@@ -3999,244 +3999,89 @@
   re
-verseBytes(data);%0A        BigInteger num = new BigInteger(1, data);%0A        while (num.bitLength() %3E curve.getFieldSize())%0A        %7B%0A            num = num.clearBit(num.bitLength() - 1);%0A        %7D%0A%0A        return curve.fromBigInteger(num
+turn curve.fromBigInteger(truncate(new BigInteger(1, data), curve.getFieldSize())
 );%0A 
@@ -4167,27 +4167,17 @@
 lement f
-ieldElement
+e
 )%0A    %7B%0A
@@ -4188,72 +4188,157 @@
     
-BigInteger num = fieldElement.toBigInteger();
+return truncate(fe.toBigInteger(), n.bitLength() - 1);%0A    %7D%0A%0A    private static BigInteger truncate(BigInteger x, int bitLength)
 %0A    
+%7B%0A
     
-while (num
+    if (x
 .bit
@@ -4351,12 +4351,9 @@
 () %3E
-= n.
+ 
 bitL
@@ -4357,18 +4357,16 @@
 itLength
-()
 )%0A      
@@ -4385,31 +4385,43 @@
     
-num = num.clearBit(num.
+x = x.mod(BigInteger.ONE.shiftLeft(
 bitL
@@ -4421,30 +4421,25 @@
 ft(bitLength
-() - 1
+)
 );%0A        %7D
@@ -4431,33 +4431,32 @@
 th));%0A        %7D%0A
-%0A
         return n
@@ -4454,19 +4454,17 @@
  return 
-num
+x
 ;%0A    %7D%0A

Use utility method to reverse bytes Use more efficient BigInteger truncation