当前位置: 首页>>代码示例>>C#>>正文


C# SecureRandom.NextInt方法代码示例

本文整理汇总了C#中Org.BouncyCastle.Security.SecureRandom.NextInt方法的典型用法代码示例。如果您正苦于以下问题:C# SecureRandom.NextInt方法的具体用法?C# SecureRandom.NextInt怎么用?C# SecureRandom.NextInt使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Org.BouncyCastle.Security.SecureRandom的用法示例。


在下文中一共展示了SecureRandom.NextInt方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: EncryptMessage

 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 };
 }
开发者ID:bucknellu,项目名称:Nyan,代码行数:29,代码来源:Helper.cs

示例2: PerformTest

		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 + ")");
				}
			}
		}
开发者ID:randombit,项目名称:hacrypto,代码行数:66,代码来源:TagTest.cs

示例3: ChooseExtraPadBlocks

		protected virtual 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);
		}
开发者ID:zzilla,项目名称:ONVIF-Device-Manager,代码行数:8,代码来源:TlsBlockCipher.cs

示例4: Prepare

		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 ();

		}
开发者ID:lukedoolittle,项目名称:telehash.net,代码行数:23,代码来源:CipherSet1a.cs

示例5: NextInt

        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;
        }
开发者ID:KimikoMuffin,项目名称:bc-csharp,代码行数:17,代码来源:OCBTest.cs

示例6: RandomTest

        private void RandomTest(SecureRandom srng)
        {
            int kLength = 16 + 8 * (System.Math.Abs(srng.NextInt()) % 3);
            byte[] K = new byte[kLength];
            srng.NextBytes(K);

            int pLength = (int)((uint)srng.NextInt() >> 16);
            byte[] P = new byte[pLength];
            srng.NextBytes(P);

            int aLength = (int)((uint)srng.NextInt() >> 24);
            byte[] A = new byte[aLength];
            srng.NextBytes(A);

            int saLength = (int)((uint)srng.NextInt() >> 24);
            byte[] SA = new byte[saLength];
            srng.NextBytes(SA);

            int ivLength = 1 + NextInt(srng, 15);
            byte[] IV = new byte[ivLength];
            srng.NextBytes(IV);

            AeadParameters parameters = new AeadParameters(new KeyParameter(K), 16 * 8, IV, A);
            IAeadBlockCipher cipher = InitOcbCipher(true, parameters);
            byte[] C = new byte[cipher.GetOutputSize(P.Length)];
            int predicted = cipher.GetUpdateOutputSize(P.Length);

            int split = NextInt(srng, SA.Length + 1);
            cipher.ProcessAadBytes(SA, 0, split);
            int len = cipher.ProcessBytes(P, 0, P.Length, C, 0);
            cipher.ProcessAadBytes(SA, split, SA.Length - split);

            if (predicted != len)
            {
                Fail("encryption reported incorrect update length in randomised test");
            }

            len += cipher.DoFinal(C, len);

            if (C.Length != len)
            {
                Fail("encryption reported incorrect length in randomised test");
            }

            byte[] encT = cipher.GetMac();
            byte[] tail = new byte[C.Length - P.Length];
            Array.Copy(C, P.Length, tail, 0, tail.Length);

            if (!AreEqual(encT, tail))
            {
                Fail("stream contained wrong mac in randomised test");
            }

            cipher.Init(false, parameters);
            byte[] decP = new byte[cipher.GetOutputSize(C.Length)];
            predicted = cipher.GetUpdateOutputSize(C.Length);

            split = NextInt(srng, SA.Length + 1);
            cipher.ProcessAadBytes(SA, 0, split);
            len = cipher.ProcessBytes(C, 0, C.Length, decP, 0);
            cipher.ProcessAadBytes(SA, split, SA.Length - split);

            if (predicted != len)
            {
                Fail("decryption reported incorrect update length in randomised test");
            }

            len += cipher.DoFinal(decP, len);

            if (!AreEqual(P, decP))
            {
                Fail("incorrect decrypt in randomised test");
            }

            byte[] decT = cipher.GetMac();
            if (!AreEqual(encT, decT))
            {
                Fail("decryption produced different mac from encryption");
            }

            //
            // key reuse test
            //
            cipher.Init(false, AeadTestUtilities.ReuseKey(parameters));
            decP = new byte[cipher.GetOutputSize(C.Length)];

            split = NextInt(srng, SA.Length + 1);
            cipher.ProcessAadBytes(SA, 0, split);
            len = cipher.ProcessBytes(C, 0, C.Length, decP, 0);
            cipher.ProcessAadBytes(SA, split, SA.Length - split);

            len += cipher.DoFinal(decP, len);

            if (!AreEqual(P, decP))
            {
                Fail("incorrect decrypt in randomised test");
            }

            decT = cipher.GetMac();
            if (!AreEqual(encT, decT))
//.........这里部分代码省略.........
开发者ID:KimikoMuffin,项目名称:bc-csharp,代码行数:101,代码来源:OCBTest.cs

示例7: CreateCertificate

        /// <summary>
        /// Create the actual certificate
        /// </summary>
        public static bool CreateCertificate(ICertificateSettings settings, Action<string> log, out string thumbprint, out string errorMessage)
        {
            errorMessage = string.Empty;
            thumbprint = string.Empty;

            try
            {
                var keyStore = new Pkcs12Store();

                log(Strings.GeneratingKeys);
                var pGen = new RsaKeyPairGenerator();
                var genParam = new
                    RsaKeyGenerationParameters(
                    BigInteger.ValueOf(0x10001),
                    new SecureRandom(),
                    1024,
                    10);
                pGen.Init(genParam);
                var keyPair = pGen.GenerateKeyPair();

                log(Strings.GeneratingCertificate);
                var attrs = new Dictionary<DerObjectIdentifier, string>();
                var oids = new List<DerObjectIdentifier> { X509Name.O, X509Name.L, X509Name.C, X509Name.CN, X509Name.EmailAddress, X509Name.OU, X509Name.ST };
                oids.Reverse();
                if (!string.IsNullOrEmpty(settings.OrgName)) attrs.Add(X509Name.O, settings.OrgName); else oids.Remove(X509Name.O);
                if (!string.IsNullOrEmpty(settings.OrgUnit)) attrs.Add(X509Name.OU, settings.OrgUnit); else oids.Remove(X509Name.OU);
                if (!string.IsNullOrEmpty(settings.City)) attrs.Add(X509Name.L, settings.City); else oids.Remove(X509Name.L);
                if (!string.IsNullOrEmpty(settings.CountryCode)) attrs.Add(X509Name.C, settings.CountryCode); else oids.Remove(X509Name.C);
                if (!string.IsNullOrEmpty(settings.State)) attrs.Add(X509Name.ST, settings.State); else oids.Remove(X509Name.ST);
                if (!string.IsNullOrEmpty(settings.Email)) attrs.Add(X509Name.EmailAddress, settings.Email); else oids.Remove(X509Name.EmailAddress);
                if (!string.IsNullOrEmpty(settings.UserName)) attrs.Add(X509Name.CN, settings.UserName); else oids.Remove(X509Name.CN);

                var certGen = new X509V3CertificateGenerator();
                var random = new SecureRandom();

                certGen.SetSerialNumber(BigInteger.ValueOf(Math.Abs(random.NextInt())));
                certGen.SetIssuerDN(new X509Name(oids, attrs));
                certGen.SetNotBefore(DateTime.Today.Subtract(new TimeSpan(1, 0, 0, 0)));
                var years = Math.Min(settings.MaxYears, 50);
                certGen.SetNotAfter(DateTime.Today.AddYears(years));
                certGen.SetSubjectDN(new X509Name(oids, attrs));
                certGen.SetPublicKey(keyPair.Public);
                certGen.SetSignatureAlgorithm("SHA1WithRSAEncryption");

                var cert = certGen.Generate(keyPair.Private);

                // Save
                log(Strings.SavingCertificate);
                var keyEntry = new AsymmetricKeyEntry(keyPair.Private);
                var certEntry = new X509CertificateEntry(cert);
                const string alias = "alias";
                keyStore.SetKeyEntry(alias, keyEntry, new[] { certEntry });

                var password = settings.Password;
                var memoryStream = new MemoryStream();
                keyStore.Save(memoryStream, password.ToCharArray(), random);
                memoryStream.Position = 0;

                // Save certificate
                var path = settings.Path;
                var folder = Path.GetDirectoryName(path);
                if (!string.IsNullOrEmpty(folder))
                    Directory.CreateDirectory(folder);

                // Set path in finished page.
                using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    memoryStream.WriteTo(fileStream);
                }

                if (settings.ImportInCertificateStore)
                {
                    log("Importing certificate in My Certificates store");
                    var certificate = new X509Certificate2(path, password,
                                                           X509KeyStorageFlags.Exportable |
                                                           X509KeyStorageFlags.PersistKeySet);
                    thumbprint = certificate.Thumbprint;
                    var x509Store2 = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                    try
                    {
                        x509Store2.Open(OpenFlags.ReadWrite);
                        x509Store2.Add(certificate);
                        x509Store2.Close();
                    }
                    catch (Exception ex)
                    {
                        errorMessage = string.Format("Failed to import certificate because: {0}", ex.Message);
                        return false;
                    }
                }

                if (years < 30)
                {
                    log("Certificate is intended for evaluation purposes. It cannot be used to deploy to the market.");
                }
                return true;
            }
//.........这里部分代码省略.........
开发者ID:Xtremrules,项目名称:dot42,代码行数:101,代码来源:CertificateBuilder.cs

示例8: CreateRandom

 /// <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));
 }
开发者ID:salfter,项目名称:Bitcoin-Address-Utility,代码行数:16,代码来源:MiniKeyPair.cs


注:本文中的Org.BouncyCastle.Security.SecureRandom.NextInt方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。