Exemplo n.º 1
0
        public void TestEd448Consistency()
        {
            byte[] sk   = new byte[Ed448.SecretKeySize];
            byte[] pk   = new byte[Ed448.PublicKeySize];
            byte[] ctx  = new byte[Random.NextInt() & 7];
            byte[] m    = new byte[255];
            byte[] sig1 = new byte[Ed448.SignatureSize];
            byte[] sig2 = new byte[Ed448.SignatureSize];

            Random.NextBytes(ctx);
            Random.NextBytes(m);

            for (int i = 0; i < 10; ++i)
            {
                Random.NextBytes(sk);
                Ed448.GeneratePublicKey(sk, 0, pk, 0);

                int mLen = Random.NextInt() & 255;

                Ed448.Sign(sk, 0, ctx, m, 0, mLen, sig1, 0);
                Ed448.Sign(sk, 0, pk, 0, ctx, m, 0, mLen, sig2, 0);

                Assert.IsTrue(Arrays.AreEqual(sig1, sig2), "Ed448 consistent signatures #" + i);

                bool shouldVerify = Ed448.Verify(sig1, 0, pk, 0, ctx, m, 0, mLen);

                Assert.IsTrue(shouldVerify, "Ed448 consistent sign/verify #" + i);

                sig1[Ed448.PublicKeySize - 1] ^= 0x80;
                bool shouldNotVerify = Ed448.Verify(sig1, 0, pk, 0, ctx, m, 0, mLen);

                Assert.IsFalse(shouldNotVerify, "Ed448 consistent verification failure #" + i);
            }
        }
Exemplo n.º 2
0
        public Association(DatagramTransport transport, AssociationListener al, bool client)
        {
            //Log.setLevel(Log.ALL);
            Logger.Debug("Created an Associaction of type: " + this.GetType().Name);
            _al         = al;
            _random     = new SecureRandom();
            _myVerTag   = _random.NextInt();
            _transp     = transport;
            _streams    = new Dictionary <int, SCTPStream>();
            _outbound   = new Dictionary <long, DataChunk>();
            _holdingPen = new Dictionary <uint, DataChunk>();
            var IInt = new FastBit.Int(_random.NextInt());

            _nearTSN = new FastBit.Uint(IInt.b0, IInt.b1, IInt.b2, IInt.b3).Auint;
            _state   = State.CLOSED;
            if (_transp != null)
            {
                startRcv();
            }
            else
            {
                Logger.Error("Created an Associaction with a null transport somehow...");
            }
            __assocNo++;

            /*
             * the method used to determine which
             * side uses odd or even is based on the underlying DTLS connection
             * role: the side acting as the DTLS client MUST use Streams with even
             * Stream Identifiers, the side acting as the DTLS server MUST use
             * Streams with odd Stream Identifiers. */
            _even = client;
        }
Exemplo n.º 3
0
 public override void PerformTest()
 {
     for (int i = 0; i < 10; ++i)
     {
         byte[] context = RandomContext(Random.NextInt() & 255);
         DoTestConsistency(Ed448.Algorithm.Ed448, context);
         DoTestConsistency(Ed448.Algorithm.Ed448ph, context);
     }
 }
Exemplo n.º 4
0
        private ECFieldElement GenerateMultiplyInputA_OpenSSLBug()
        {
            uint[] x = Nat256.Create();
            x[0] = (uint)Random.NextInt() >> 1;
            x[4] = 3;
            x[7] = 0xFFFFFFFF;

            return(FE(Nat256.ToBigInteger(x)));
        }
Exemplo n.º 5
0
        public override void PerformTest()
        {
            for (int i = 0; i < 10; ++i)
            {
                DoTestConsistency(Ed25519.Algorithm.Ed25519, null);

                byte[] context = RandomContext(Random.NextInt() & 255);
                DoTestConsistency(Ed25519.Algorithm.Ed25519ctx, context);
                DoTestConsistency(Ed25519.Algorithm.Ed25519ph, context);
            }
        }
Exemplo n.º 6
0
 private byte[] EncodeBlock(byte[] input, int inOff, int inLen)
 {
     //IL_0013: Unknown result type (might be due to invalid IL or missing references)
     if (inLen > GetInputBlockSize())
     {
         throw new ArgumentException("input data too large", "inLen");
     }
     byte[] array = new byte[engine.GetInputBlockSize()];
     if (forPrivateKey)
     {
         array[0] = 1;
         for (int i = 1; i != array.Length - inLen - 1; i++)
         {
             array[i] = 255;
         }
     }
     else
     {
         ((Random)random).NextBytes(array);
         array[0] = 2;
         for (int j = 1; j != array.Length - inLen - 1; j++)
         {
             while (array[j] == 0)
             {
                 array[j] = (byte)random.NextInt();
             }
         }
     }
     array[array.Length - inLen - 1] = 0;
     global::System.Array.Copy((global::System.Array)input, inOff, (global::System.Array)array, array.Length - inLen, inLen);
     return(engine.ProcessBlock(array, 0, array.Length));
 }
Exemplo n.º 7
0
        // * //



        // Generate a strong encryption key, optionally protect with user password //
        public static string GenerateKey(int length)
        {
            string masterKey = null;

            try
            {
                // We want a random number of non-alphanumeric characters to be included
                int nonAlphaCharCnt = Math.Abs(Random.NextInt() % (length + 1));

                // Generate password
                masterKey = Membership.GeneratePassword(length, nonAlphaCharCnt);

                // Ensure we got good stuff back
                if (masterKey == null)
                {
                    throw new Exception("Failed to obtain a master key or header!");
                }
            }
            catch (Exception)
            {
                return(null);
            }

            return(masterKey);
        }
Exemplo n.º 8
0
        protected virtual int ChooseExtraPadBlocks(SecureRandom r, int max)
        {
            int x   = r.NextInt();
            int val = this.LowestBitSet(x);

            return(Math.Min(val, max));
        }
Exemplo n.º 9
0
        public void testMult()
        {
            IntegerPolynomial i1 = new IntegerPolynomial(new int[] { 1368, 2047, 672, 871, 1662, 1352, 1099, 1608 });
            IntegerPolynomial i2 = new IntegerPolynomial(new int[] { 1729, 1924, 806, 179, 1530, 1381, 1695, 60 });
            LongPolynomial2   a  = new LongPolynomial2(i1);
            LongPolynomial2   b  = new LongPolynomial2(i2);
            IntegerPolynomial c1 = i1.Multiply(i2, 2048);
            IntegerPolynomial c2 = a.Multiply(b).ToIntegerPolynomial();

            Assert.True(c1.coeffs.SequenceEqual(c2.coeffs));

            SecureRandom rng = new SecureRandom();

            for (int i = 0; i < 10; i++)
            {
                int N = 2 + rng.NextInt(2000);
                i1 = PolynomialGenerator.GenerateRandom(N, 2048);
                i2 = PolynomialGenerator.GenerateRandom(N, 2048);
                a  = new LongPolynomial2(i1);
                b  = new LongPolynomial2(i2);
                c1 = i1.Multiply(i2);
                c1.ModPositive(2048);
                c2 = a.Multiply(b).ToIntegerPolynomial();
                Assert.True(c1.coeffs.SequenceEqual(c2.coeffs));
            }
        }
Exemplo n.º 10
0
        public void CanValidateSignature()
        {
            Ed25519KeyPairGenerator kpg = new Ed25519KeyPairGenerator();

            kpg.Init(new Ed25519KeyGenerationParameters(Random));

            AsymmetricCipherKeyPair     kp         = kpg.GenerateKeyPair();
            Ed25519PrivateKeyParameters privateKey = (Ed25519PrivateKeyParameters)kp.Private;
            Ed25519PublicKeyParameters  publicKey  = (Ed25519PublicKeyParameters)kp.Public;
            var pubKeyBase64 = Convert.ToBase64String(publicKey.GetEncoded());

            // create signature for item
            byte[] msg = new byte[Random.NextInt() & 255];
            Random.NextBytes(msg);
            var signer = new Ed25519Signer();

            signer.Init(true, privateKey);
            signer.BlockUpdate(msg, 0, msg.Length);
            byte[] signature           = signer.GenerateSignature();
            var    signatureForAppCast = Convert.ToBase64String(signature);

            // verify signature
            var checker = new Ed25519Checker(NetSparkleUpdater.Enums.SecurityMode.Strict, pubKeyBase64);

            Assert.True(checker.VerifySignature(signatureForAppCast, msg) == NetSparkleUpdater.Enums.ValidationResult.Valid);
        }
 private Color GetRandomColor() 
 {
     SecureRandom rgen = new SecureRandom();
     return Color.HSVToColor(150, new float[]{
         rgen.NextInt(359), 1, 1
     });
 }
Exemplo n.º 12
0
 private byte[] EncodeBlock(byte[] input, int inOff, int inLen)
 {
     if (inLen > GetInputBlockSize())
     {
         throw new ArgumentException("input data too large", "inLen");
     }
     byte[] array = new byte[engine.GetInputBlockSize()];
     if (forPrivateKey)
     {
         array[0] = 1;
         for (int i = 1; i != array.Length - inLen - 1; i++)
         {
             array[i] = byte.MaxValue;
         }
     }
     else
     {
         random.NextBytes(array);
         array[0] = 2;
         for (int j = 1; j != array.Length - inLen - 1; j++)
         {
             while (array[j] == 0)
             {
                 array[j] = (byte)random.NextInt();
             }
         }
     }
     array[array.Length - inLen - 1] = 0;
     Array.Copy(input, inOff, array, array.Length - inLen, inLen);
     return(engine.ProcessBlock(array, 0, array.Length));
 }
Exemplo n.º 13
0
        private Color GetRandomColor()
        {
            SecureRandom rgen = new SecureRandom();

            return(Color.HSVToColor(150, new float[] {
                rgen.NextInt(359), 1, 1
            }));
        }
Exemplo n.º 14
0
        private static int NextInt(SecureRandom rand, int n)
        {
            if ((n & -n) == n)  // i.e., n is a power of 2
            {
                return((int)(((uint)n * (ulong)((uint)rand.NextInt() >> 1)) >> 31));
            }

            int bits, value;

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

            return(value);
        }
Exemplo n.º 15
0
        private int ChooseExtraPadBlocks(SecureRandom r, int max)
        {
//			return r.NextInt(max + 1);

            uint x = (uint)r.NextInt();
            int  n = LowestBitSet(x);

            return(System.Math.Min(n, max));
        }
Exemplo n.º 16
0
        protected virtual int ChooseExtraPadBlocks(SecureRandom r, int max)
        {
            // return r.NextInt(max + 1);

            int x = r.NextInt();
            int n = LowestBitSet(x);

            return(System.Math.Min(n, max));
        }
        /**
         * Generates a polynomial with coefficients randomly selected from <code>{-1, 0, 1}</code>.
         *
         * @param N number of coefficients
         */
        public static DenseTernaryPolynomial GenerateRandom(int N, SecureRandom random)
        {
            DenseTernaryPolynomial poly = new DenseTernaryPolynomial(N);

            for (int i = 0; i < N; i++)
            {
                poly.coeffs[i] = random.NextInt(3) - 1;
            }
            return(poly);
        }
Exemplo n.º 18
0
        private ECFieldElement GenerateSquareInput_CarryBug()
        {
            uint[] x = Nat.Create(12);
            x[0]  = (uint)Random.NextInt() >> 1;
            x[6]  = 2;
            x[10] = 0xFFFF0000;
            x[11] = 0xFFFFFFFF;

            return(FE(Nat.ToBigInteger(12, x)));
        }
Exemplo n.º 19
0
        /**
         * Creates a random polynomial with <code>N</code> coefficients
         * between <code>0</code> and <code>q-1</code>.
         *
         * @param N length of the polynomial
         * @param q coefficients will all be below this number
         * @return a random polynomial
         */
        public static IntegerPolynomial GenerateRandom(int N, int q)
        {
            SecureRandom rng = new SecureRandom();

            int[] coeffs = new int[N];
            for (int i = 0; i < N; i++)
            {
                coeffs[i] = rng.NextInt(q);
            }
            return(new IntegerPolynomial(coeffs));
        }
Exemplo n.º 20
0
        public int AddPadding(byte[] input, int inOff)
        {
            byte b = (byte)(input.Length - inOff);

            while (inOff < input.Length - 1)
            {
                input[inOff] = (byte)random.NextInt();
                inOff++;
            }
            input[inOff] = b;
            return(b);
        }
Exemplo n.º 21
0
        /*
         * calculate a random mess-with-their-heads value.
         */
        private BigInteger calculateR(
            BigInteger m)
        {
            int        max    = m.BitLength - 1;   // must be less than m.BitLength
            int        min    = max / 2;
            int        length = ((random.NextInt() & 0xff) * ((max - min) / 0xff)) + min;
            BigInteger factor = new BigInteger(length, random);

            while (factor.SignValue == 0)
            {
                factor = new BigInteger(length, random);
            }

            return(factor);
        }
Exemplo n.º 22
0
        /**
         * add the pad bytes to the passed in block, returning the
         * number of bytes added.
         */
        public int AddPadding(
            byte[]      input,
            int inOff)
        {
            byte code = (byte)(input.Length - inOff);

            while (inOff < (input.Length - 1))
            {
                input[inOff] = (byte)random.NextInt();
                inOff++;
            }

            input[inOff] = code;

            return(code);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Create a new random MiniKey.
        /// Entropy is taken from .NET's SecureRandom, the system clock,
        /// and any optionally provided salt.
        /// </summary>
        public static MiniKeyPair CreateRandom(string usersalt)
        {
            if (usersalt == null)
            {
                usersalt = "ok, whatever";
            }
            usersalt += DateTime.UtcNow.Ticks.ToString();
            SecureRandom sr = new SecureRandom();

            char[] chars = new char[64];
            for (int i = 0; i < 64; i++)
            {
                chars[i] = (char)(32 + (sr.NextInt() % 64));
            }
            return(CreateDeterministic(usersalt + new String(chars)));
        }
Exemplo n.º 24
0
        private byte[] EncodeBlock(
            byte[]  input,
            int inOff,
            int inLen)
        {
            if (inLen > GetInputBlockSize())
            {
                throw new ArgumentException("input data too large", "inLen");
            }

            byte[] block = new byte[engine.GetInputBlockSize()];

            if (forPrivateKey)
            {
                block[0] = 0x01;                                        // type code 1

                for (int i = 1; i != block.Length - inLen - 1; i++)
                {
                    block[i] = (byte)0xFF;
                }
            }
            else
            {
                random.NextBytes(block);                                // random fill

                block[0] = 0x02;                                        // type code 2

                //
                // a zero byte marks the end of the padding, so all
                // the pad bytes must be non-zero.
                //
                for (int i = 1; i != block.Length - inLen - 1; i++)
                {
                    while (block[i] == 0)
                    {
                        block[i] = (byte)random.NextInt();
                    }
                }
            }

            block[block.Length - inLen - 1] = 0x00;                   // mark the end of the padding
            Array.Copy(input, inOff, block, block.Length - inLen, inLen);

            return(engine.ProcessBlock(block, 0, block.Length));
        }
Exemplo n.º 25
0
        public static X509Certificate GenerateCertificate(X509Name issuer, X509Name subject, AsymmetricKeyParameter issuerPrivate, AsymmetricKeyParameter subjectPublic, DateTime?notBefore = null, DateTime?notAfter = null)
        {
            ISignatureFactory signatureFactory = new Asn1SignatureFactory(
                PkcsObjectIdentifiers.Sha256WithRsaEncryption.ToString(),
                issuerPrivate);

            X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();

            certGenerator.SetIssuerDN(issuer);
            certGenerator.SetSubjectDN(subject);
            certGenerator.SetSerialNumber(BigInteger.ValueOf(Math.Abs(secureRandom.NextInt())));
            certGenerator.SetNotAfter(notAfter ?? DateTime.UtcNow.AddHours(1));
            certGenerator.SetNotBefore(notBefore ?? DateTime.UtcNow);
            certGenerator.SetPublicKey(subjectPublic);
            certGenerator.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyCertSign | KeyUsage.CrlSign));
            certGenerator.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeID.IdKPTimeStamping));
            return(certGenerator.Generate(signatureFactory));
        }
Exemplo n.º 26
0
Arquivo: Helper.cs Projeto: lr030/ML
        public static EncryptionResult EncryptMessage(byte[] userKey, byte[] userSecret, byte[] data, ushort padding = 0, bool randomisePadding = false)
        {
            var Random = new SecureRandom();
            var Salt   = new byte[16];

            Random.NextBytes(Salt);

            var Curve     = ECNamedCurveTable.GetByName("prime256v1");
            var Spec      = new ECDomainParameters(Curve.Curve, Curve.G, Curve.N, Curve.H, Curve.GetSeed());
            var Generator = new ECKeyPairGenerator();

            Generator.Init(new ECKeyGenerationParameters(Spec, new SecureRandom()));

            var KeyPair            = Generator.GenerateKeyPair();
            var AgreementGenerator = new ECDHBasicAgreement();

            AgreementGenerator.Init(KeyPair.Private);

            var IKM       = AgreementGenerator.CalculateAgreement(new ECPublicKeyParameters(Spec.Curve.DecodePoint(userKey), Spec));
            var PRK       = GenerateHKDF(userSecret, IKM.ToByteArrayUnsigned(), Encoding.UTF8.GetBytes("Content-Encoding: auth\0"), 32);
            var PublicKey = ((ECPublicKeyParameters)KeyPair.Public).Q.GetEncoded(false);
            var CEK       = GenerateHKDF(Salt, PRK, CreateInfoChunk("aesgcm", userKey, PublicKey), 16);
            var Nonce     = GenerateHKDF(Salt, PRK, CreateInfoChunk("nonce", userKey, PublicKey), 12);

            if (randomisePadding && padding > 0)
            {
                padding = Convert.ToUInt16(Math.Abs(Random.NextInt()) % (padding + 1));
            }
            var Input = new byte[padding + 2 + data.Length];

            Buffer.BlockCopy(ConvertInt(padding), 0, Input, 0, 2);
            Buffer.BlockCopy(data, 0, Input, padding + 2, data.Length);
            var Cipher = CipherUtilities.GetCipher("AES/GCM/NoPadding");

            Cipher.Init(true, new AeadParameters(new KeyParameter(CEK), 128, Nonce));
            var Message = new byte[Cipher.GetOutputSize(Input.Length)];

            Cipher.DoFinal(Input, 0, Input.Length, Message, 0);
            return(new EncryptionResult {
                Salt = Salt, Payload = Message, PublicKey = PublicKey
            });
        }
Exemplo n.º 27
0
        public void testMult()
        {
            testMult(new int[] { 2 }, new int[] { -1 });
            testMult(new int[] { 2, 0 }, new int[] { -1, 0 });
            testMult(new int[] { 2, 0, 3 }, new int[] { -1, 0, 1 });
            testMult(new int[] { 2, 0, 3, 1 }, new int[] { -1, 0, 1, 1 });
            testMult(new int[] { 2, 0, 3, 1, 2 }, new int[] { -1, 0, 1, 1, 0 });
            testMult(new int[] { 2, 0, 3, 1, 1, 5 }, new int[] { 1, -1, 1, 1, 0, 1 });
            testMult(new int[] { 2, 0, 3, 1, 1, 5, 1, 4 }, new int[] { 1, 0, 1, 1, -1, 1, 0, -1 });
            testMult(new int[] { 1368, 2047, 672, 871, 1662, 1352, 1099, 1608 }, new int[] { 1, 0, 1, 1, -1, 1, 0, -1 });

            // test random polynomials
            SecureRandom rng = new SecureRandom();

            for (int i = 0; i < 10; i++)
            {
                int[] coeffs1 = new int[rng.NextInt(2000) + 1];
                int[] coeffs2 = DenseTernaryPolynomial.GenerateRandom(coeffs1.Length, rng).coeffs;
                testMult(coeffs1, coeffs2);
            }
        }
Exemplo n.º 28
0
        private static EncryptionResult EncryptMessage(byte[] userKey, byte[] userSecret, byte[] data,
                                                       ushort padding = 0, bool randomisePadding = false)
        {
            SecureRandom random = new SecureRandom();

            byte[] salt = new byte[16];
            random.NextBytes(salt);
            X9ECParameters     curve     = ECNamedCurveTable.GetByName("prime256v1");
            ECDomainParameters spec      = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());
            ECKeyPairGenerator generator = new ECKeyPairGenerator();

            generator.Init(new ECKeyGenerationParameters(spec, new SecureRandom()));
            AsymmetricCipherKeyPair keyPair            = generator.GenerateKeyPair();
            ECDHBasicAgreement      agreementGenerator = new ECDHBasicAgreement();

            agreementGenerator.Init(keyPair.Private);
            BigInteger ikm = agreementGenerator.CalculateAgreement(new ECPublicKeyParameters(spec.Curve.DecodePoint(userKey), spec));

            byte[] prk       = GenerateHkdf(userSecret, ikm.ToByteArrayUnsigned(), Encoding.UTF8.GetBytes("Content-Encoding: auth\0"), 32);
            byte[] publicKey = ((ECPublicKeyParameters)keyPair.Public).Q.GetEncoded(false);
            byte[] cek       = GenerateHkdf(salt, prk, CreateInfoChunk("aesgcm", userKey, publicKey), 16);
            byte[] nonce     = GenerateHkdf(salt, prk, CreateInfoChunk("nonce", userKey, publicKey), 12);
            if (randomisePadding && padding > 0)
            {
                padding = Convert.ToUInt16(Math.Abs(random.NextInt()) % (padding + 1));
            }
            byte[] input = new byte[padding + 2 + data.Length];
            Buffer.BlockCopy(ConvertInt(padding), 0, input, 0, 2);
            Buffer.BlockCopy(data, 0, input, padding + 2, data.Length);
            IBufferedCipher cipher = CipherUtilities.GetCipher("AES/GCM/NoPadding");

            cipher.Init(true, new AeadParameters(new KeyParameter(cek), 128, nonce));
            byte[] message = new byte[cipher.GetOutputSize(input.Length)];
            cipher.DoFinal(input, 0, input.Length, message, 0);
            return(new EncryptionResult()
            {
                Salt = salt, Payload = message, PublicKey = publicKey
            });
        }
Exemplo n.º 29
0
        /**
         * add the pad bytes to the passed in block, returning the
         * number of bytes added.
         */
        public int AddPadding(
            byte[]  input,
            int inOff)
        {
            byte code = (byte)(input.Length - inOff);

            while (inOff < input.Length - 1)
            {
                if (random == null)
                {
                    input[inOff] = 0;
                }
                else
                {
                    input[inOff] = (byte)random.NextInt();
                }
                inOff++;
            }

            input[inOff] = code;

            return(code);
        }
Exemplo n.º 30
0
        public void Prepare(ICipherSetRemoteInfo info, Packet outer)
        {
            var ri = (CS1ARemoteInfo)info;

            ri.RemoteEphemeralKey = new byte[21];
            Buffer.BlockCopy(outer.Parent.Body, 0, ri.RemoteEphemeralKey, 0, 21);

            var secret    = Helpers.ToByteArray(ECDHAgree(ri.RemoteEphemeralKey, ri.EphemeralKeys.PrivateKey), 20);
            var shaBuffer = new byte[secret.Length + ri.RemoteEphemeralKey.Length + ri.EphemeralKeys.PublicKey.Length];

            Buffer.BlockCopy(secret, 0, shaBuffer, 0, secret.Length);
            Buffer.BlockCopy(ri.RemoteEphemeralKey, 0, shaBuffer, secret.Length, ri.RemoteEphemeralKey.Length);
            Buffer.BlockCopy(ri.EphemeralKeys.PublicKey, 0, shaBuffer, secret.Length + ri.RemoteEphemeralKey.Length, ri.EphemeralKeys.PublicKey.Length);
            ri.DecryptionKey = Helpers.FoldOnce(Helpers.SHA256Hash(shaBuffer));

            Buffer.BlockCopy(ri.EphemeralKeys.PublicKey, 0, shaBuffer, secret.Length, ri.EphemeralKeys.PublicKey.Length);
            Buffer.BlockCopy(ri.RemoteEphemeralKey, 0, shaBuffer, secret.Length + ri.EphemeralKeys.PublicKey.Length, ri.RemoteEphemeralKey.Length);
            ri.EncryptionKey = Helpers.FoldOnce(Helpers.SHA256Hash(shaBuffer));

            var rnd = new SecureRandom();

            ri.IV = (uint)rnd.NextInt();
        }
Exemplo n.º 31
0
        public override void PerformTest()
        {
            DerApplicationSpecific app = (DerApplicationSpecific)
                                         Asn1Object.FromByteArray(longTagged);

            app = (DerApplicationSpecific)Asn1Object.FromByteArray(app.GetContents());

            Asn1InputStream aIn = new Asn1InputStream(app.GetContents());

            Asn1TaggedObject tagged = (Asn1TaggedObject)aIn.ReadObject();

            if (tagged.TagNo != 32)
            {
                Fail("unexpected tag value found - not 32");
            }

            tagged = (Asn1TaggedObject)Asn1Object.FromByteArray(tagged.GetEncoded());

            if (tagged.TagNo != 32)
            {
                Fail("unexpected tag value found on recode - not 32");
            }

            tagged = (Asn1TaggedObject)aIn.ReadObject();

            if (tagged.TagNo != 33)
            {
                Fail("unexpected tag value found - not 33");
            }

            tagged = (Asn1TaggedObject)Asn1Object.FromByteArray(tagged.GetEncoded());

            if (tagged.TagNo != 33)
            {
                Fail("unexpected tag value found on recode - not 33");
            }

            aIn = new Asn1InputStream(longAppSpecificTag);

            app = (DerApplicationSpecific)aIn.ReadObject();

            if (app.ApplicationTag != 97)
            {
                Fail("incorrect tag number read");
            }

            app = (DerApplicationSpecific)Asn1Object.FromByteArray(app.GetEncoded());

            if (app.ApplicationTag != 97)
            {
                Fail("incorrect tag number read on recode");
            }

            SecureRandom sr = new SecureRandom();

            for (int i = 0; i < 100; ++i)
            {
                int testTag = (sr.NextInt() & int.MaxValue) >> sr.Next(26);
                app = new DerApplicationSpecific(testTag, new byte[] { 1 });
                app = (DerApplicationSpecific)Asn1Object.FromByteArray(app.GetEncoded());

                if (app.ApplicationTag != testTag)
                {
                    Fail("incorrect tag number read on recode (random test value: " + testTag + ")");
                }
            }
        }