How do I assign a number to BouncyCastle.BigInteger & # 8596; System.Numerics.BigInteger

The slowest part of my code is that I use the Bouncy Castle method "BigInteger.Multiply ()". To try to speed things up, I'm trying to paste the code below to find out if there are any improvements.

I know that I am not doing something right, because I get a lot of errors and exceptions, when Bouncy Castle sees BigInteger, I send it:

         if (this.sign != 1 || val.sign != 1)
        {
            //todo: test encoding, twos compliment
        }
        var tempThis = this.ToByteArrayUnsigned();
        Array.Reverse(tempThis);
        System.Numerics.BigInteger aThis = new System.Numerics.BigInteger(tempThis);

        var tempThat = val.ToByteArrayUnsigned();
        Array.Reverse(tempThat);
        System.Numerics.BigInteger bThat = new System.Numerics.BigInteger(tempThat);
        var msResult = System.Numerics.BigInteger.Multiply(aThis, bThat);

        var tmpRet = msResult.ToByteArray();
        Array.Reverse(tmpRet);
        var ret = new BigInteger(tmpRet);
        return ret;

This is the original BC feature.

    public BigInteger Multiply(     BigInteger val)
    {

       // THEORY: If I use the native System.Numerics here, then I might get better performance

        if (val == this)
            return Square();

        if ((sign & val.sign) == 0)
            return Zero;

        if (val.QuickPow2Check()) // val is power of two
        {
            BigInteger result = this.ShiftLeft(val.Abs().BitLength - 1);
            return val.sign > 0 ? result : result.Negate();
        }

        if (this.QuickPow2Check()) // this is power of two
        {
            BigInteger result = val.ShiftLeft(this.Abs().BitLength - 1);
            return this.sign > 0 ? result : result.Negate();
        }

        int resLength = magnitude.Length + val.magnitude.Length;
        int[] res = new int[resLength];

        Multiply(res, this.magnitude, val.magnitude);

        int resSign = sign ^ val.sign ^ 1;
        return new BigInteger(resSign, res, true);
    }
+4
source share

Source: https://habr.com/ru/post/1526746/


All Articles