summary refs log tree commit diff
path: root/crypto/src/pqc/math/linearalgebra/RandUtils.cs
blob: f7b7b858889ddbd305a78c56442440a9949597ed (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using Org.BouncyCastle.Security;

namespace Org.BouncyCastle.Pqc.Math.LinearAlgebra
{
    public class RandUtils
    {
        public static int NextInt(SecureRandom rand, int n)
        {

            if ((n & -n) == n)  // i.e., n is a power of 2
            {
                return (int)((n * (long)(Utils.UnsignedRightBitShiftInt(rand.NextInt(), 1))) >> 31);
            }

            int bits, value;
            do
            {
                bits = Utils.UnsignedRightBitShiftInt(rand.NextInt() ,1);
                value = bits % n;
            }
            while (bits - value + (n - 1) < 0);

            return value;
        }
    }

}