public String GeneratePassword(int length, bool upperCase, bool lowerCase, bool digits, bool minus, bool underline, bool space, bool specials, bool brackets) { if (length <= 0) throw new ArgumentException(_cxt.GetString(Resource.String.error_wrong_length)); if (!upperCase && !lowerCase && !digits && !minus && !underline && !space && !specials && !brackets) throw new ArgumentException(_cxt.GetString(Resource.String.error_pass_gen_type)); String characterSet = GetCharacterSet(upperCase, lowerCase, digits, minus, underline, space, specials, brackets); int size = characterSet.Length; StringBuilder buffer = new StringBuilder(); Random random = new SecureRandom(); if (size > 0) { for (int i = 0; i < length; i++) { char c = characterSet[random.Next(size)]; buffer.Append(c); } } return buffer.ToString(); }
private Color GetRandomColor() { SecureRandom rgen = new SecureRandom(); return Color.HSVToColor(150, new float[]{ rgen.NextInt(359), 1, 1 }); }
public void TestVmpcPrng() { var random = new SecureRandom(new VmpcRandomGenerator()); random.SetSeed(SecureRandom.GetSeed(32)); CheckSecureRandom(random); }
private static void checkSecureRandom( SecureRandom random) { // Note: This will periodically (< 1e-6 probability) give a false alarm. // That's randomness for you! Assert.IsTrue(runChiSquaredTests(random), "Chi2 test detected possible non-randomness"); }
public void TestThreadedSeed() { SecureRandom random = new SecureRandom( new ThreadedSeedGenerator().GenerateSeed(20, false)); checkSecureRandom(random); }
public void CreateGeneratorWithDefaultProvider() { using (var random = new SecureRandom()) { Assert.IsNotNull(random.Generator, "The generator is null."); } }
public void CreateBigIntegerWithZeroLength() { using(var random = new SecureRandom()) { random.GetBigInteger(0); } }
public void TestCryptoApi() { SecureRandom random = new SecureRandom( new CryptoApiRandomGenerator()); CheckSecureRandom(random); }
private void doTestCreateKeyParameter( string algorithm, DerObjectIdentifier oid, int keyBits, Type expectedType, SecureRandom random) { int keyLength = keyBits / 8; byte[] bytes = new byte[keyLength]; random.NextBytes(bytes); KeyParameter key; key = ParameterUtilities.CreateKeyParameter(algorithm, bytes); checkKeyParameter(key, expectedType, bytes); key = ParameterUtilities.CreateKeyParameter(oid, bytes); checkKeyParameter(key, expectedType, bytes); bytes = new byte[keyLength * 2]; random.NextBytes(bytes); int offset = random.Next(1, keyLength); byte[] expected = new byte[keyLength]; Array.Copy(bytes, offset, expected, 0, keyLength); key = ParameterUtilities.CreateKeyParameter(algorithm, bytes, offset, keyLength); checkKeyParameter(key, expectedType, expected); key = ParameterUtilities.CreateKeyParameter(oid, bytes, offset, keyLength); checkKeyParameter(key, expectedType, expected); }
private static double measureChiSquared( SecureRandom random, int rounds) { int[] counts = new int[256]; byte[] bs = new byte[256]; for (int i = 0; i < rounds; ++i) { random.NextBytes(bs); for (int b = 0; b < 256; ++b) { ++counts[bs[b]]; } } byte mask = SecureRandom.GetSeed(1)[0]; for (int i = 0; i < rounds; ++i) { random.NextBytes(bs); for (int b = 0; b < 256; ++b) { ++counts[bs[b] ^ mask]; } ++mask; } byte shift = SecureRandom.GetSeed(1)[0]; for (int i = 0; i < rounds; ++i) { random.NextBytes(bs); for (int b = 0; b < 256; ++b) { ++counts[(byte)(bs[b] + shift)]; } ++shift; } int total = 3 * rounds; double chi2 = 0; for (int k = 0; k < counts.Length; ++k) { double diff = ((double) counts[k]) - total; double diff2 = diff * diff; chi2 += diff2; } chi2 /= total; return chi2; }
public static AsymmetricCipherKeyPair genKeyPair() { SecureRandom rnd = new SecureRandom(); RSAKeyGenerationParameters par = new RSAKeyGenerationParameters(BigInteger.valueOf(65537), rnd, 1024, 10); RSAKeyPairGenerator gen = new RSAKeyPairGenerator(); gen.init(par); AsymmetricCipherKeyPair keys = gen.generateKeyPair(); return keys; }
public void CreateBigIntegerWithLengthOf9() { const int length = 9; using(var random = new SecureRandom()) { var value = random.GetBigInteger(length); Assert.AreEqual(length, value.ToString().Length); } }
public void TestSha1PrngBackward() { byte[] seed = Encoding.ASCII.GetBytes("backward compatible"); SecureRandom sx = new SecureRandom(seed); SecureRandom sy = SecureRandom.GetInstance("SHA1PRNG", false); sy.SetSeed(seed); byte[] bx = new byte[128]; sx.NextBytes(bx); byte[] by = new byte[128]; sy.NextBytes(by); Assert.IsTrue(Arrays.AreEqual(bx, by)); }
public void TestCreateKeyParameter() { SecureRandom random = new SecureRandom(); doTestCreateKeyParameter("AES", NistObjectIdentifiers.IdAes128Cbc, 128, typeof(KeyParameter), random); doTestCreateKeyParameter("DES", OiwObjectIdentifiers.DesCbc, 64, typeof(DesParameters), random); doTestCreateKeyParameter("DESEDE", PkcsObjectIdentifiers.DesEde3Cbc, 192, typeof(DesEdeParameters), random); doTestCreateKeyParameter("RC2", PkcsObjectIdentifiers.RC2Cbc, 128, typeof(RC2Parameters), random); }
private static bool runChiSquaredTests( SecureRandom random) { int passes = 0; for (int tries = 0; tries < 100; ++tries) { double chi2 = measureChiSquared(random, 1000); if (chi2 < 285.0) // 255 degrees of freedom in test => Q ~ 10.0% for 285 ++passes; } return passes > 75; }
public void GetDoubleValues() { using (var random = new SecureRandom()) { var elements = random.GetDoubleValues(8); for (var i = 0; i < elements.Length; i++) { var element = elements[i]; Assert.IsTrue(element >= double.MinValue); Assert.IsTrue(element < double.MaxValue); } } }
public void GetInt32ValuesDuplicatesAllowed() { var generator = new MockRandomNumberGeneratorForGetInt32Values(ValueGeneration.DuplicatesAllowed); using (var random = new SecureRandom(generator)) { var elements = random.GetInt32Values(8, ValueGeneration.DuplicatesAllowed); Assert.AreEqual(8, elements.Length); for (var i = 0; i < elements.Length; i++) { var element = elements[i]; Assert.IsTrue(element >= int.MinValue); Assert.IsTrue(element < int.MaxValue); } Assert.AreEqual(8, generator.MethodCallCount); } }
public void GenerateIntegerWithNegativeUpperBound() { using (var random = new SecureRandom()) { random.Next(-2); } }
public void GetByteValuesDuplicatesAllowedAndElementNumberExceedsByteMaximum() { using (var random = new SecureRandom()) { var elements = random.GetByteValues(2560, ValueGeneration.DuplicatesAllowed); Assert.AreEqual(2560, elements.Length); for (var i = 0; i < elements.Length; i++) { var element = elements[i]; Assert.IsTrue(element >= byte.MinValue); Assert.IsTrue(element <= byte.MaxValue); } Assert.AreNotEqual(elements.Length, new HashSet<byte>(elements).Count); } }
public void TestGeneration() { ISigner s = SignerUtilities.GetSigner("DSA"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; SecureRandom rand = new SecureRandom(); // KeyPairGenerator g = KeyPairGenerator.GetInstance("DSA"); IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA"); // test exception // doTestBadStrength(513); doTestBadStrength(510); doTestBadStrength(1025); //g.initialize(512, rand); { DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(512, 80, rand); g.Init(new DsaKeyGenerationParameters(rand, pGen.GenerateParameters())); } AsymmetricCipherKeyPair p = g.GenerateKeyPair(); AsymmetricKeyParameter sKey = p.Private; AsymmetricKeyParameter vKey = p.Public; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); byte[] sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("DSA"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("DSA verification failed"); } // // ECDSA Fp generation test // s = SignerUtilities.GetSigner("ECDSA"); ECCurve curve = new FpCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters ecSpec = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n g = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); g.Init(new ECKeyGenerationParameters(ecSpec, rand)); p = g.GenerateKeyPair(); sKey = p.Private; vKey = p.Public; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("ECDSA"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("ECDSA verification failed"); } // // ECDSA F2m generation test // s = SignerUtilities.GetSigner("ECDSA"); curve = new F2mCurve( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ecSpec = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.ValueOf(4)); // h g = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); g.Init(new ECKeyGenerationParameters(ecSpec, rand)); p = g.GenerateKeyPair(); sKey = p.Private; vKey = p.Public; s.Init(true, sKey); s.BlockUpdate(data, 0, data.Length); sigBytes = s.GenerateSignature(); s = SignerUtilities.GetSigner("ECDSA"); s.Init(false, vKey); s.BlockUpdate(data, 0, data.Length); if (!s.VerifySignature(sigBytes)) { Fail("ECDSA verification failed"); } }
// Note: Much of this code comes from https://stackoverflow.com/a/22247129 private static X509Certificate2 GenerateSelfSignedCertificate(string subject) { const int keyStrength = 2048; // Generating Random Numbers var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); // The Certificate Generator var certificateGenerator = new X509V3CertificateGenerator(); // Serial Number certificateGenerator.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random)); // Subject Public Key var keyPairGenerator = new RsaKeyPairGenerator(); var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength); keyPairGenerator.Init(keyGenerationParameters); var subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); // Subject DN certificateGenerator.SetSubjectDN(new X509Name("CN=" + subject)); // Subject Alternative Name var subjectAlternativeNames = new List <Asn1Encodable>() { new GeneralName(GeneralName.DnsName, Environment.MachineName), new GeneralName(GeneralName.DnsName, "localhost"), new GeneralName(GeneralName.IPAddress, "127.0.0.1"), }; if (subject != "localhost" && subject != Environment.MachineName) { subjectAlternativeNames.Add(new GeneralName(GeneralName.DnsName, subject)); } certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName.Id, false, new DerSequence(subjectAlternativeNames.ToArray())); // Issuer certificateGenerator.SetIssuerDN(new X509Name("CN=" + subject)); certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public))); // Valid For var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddYears(2); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); // Add basic constraint certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false)); certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth)); // Signature Algorithm const string signatureAlgorithm = "SHA256WithRSA"; var signatureFactory = new Asn1SignatureFactory(signatureAlgorithm, subjectKeyPair.Private); // selfsign certificate var certificate = certificateGenerator.Generate(signatureFactory); // correcponding private key var info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); // merge into X509Certificate2 var x509 = new X509Certificate2(certificate.GetEncoded()); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded()); if (seq.Count != 9) { // throw new PemException("malformed sequence in RSA private key"); } var rsa = RsaPrivateKeyStructure.GetInstance(seq); var rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); try { x509.PrivateKey = ToDotNetKey(rsaparams); // x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams); } catch (CryptographicException e) { throw new Exception($"Exception on cert generation!\nSubject {subject}\nHostname {Environment.MachineName}\nSequenceCount {seq.Count} (should be 9?)", e); } return(x509); }
protected virtual void engineInit( KeyGenerationParameters parameters) { this.random = parameters.Random; this.strength = (parameters.Strength + 7) / 8; }
public void CreateGeneratorWithGivenProvider() { using (var random = new SecureRandom(new RNGCryptoServiceProvider())) { Assert.IsNotNull(random.Generator, "The generator is null."); } }
/// <summary>Constructor allowing specific source of randomness</summary> /// <param name="rand">Instance of <c>SecureRandom</c> to use.</param> public CmsSignedDataStreamGenerator( SecureRandom rand) : base(rand) { }
/** * Construct without a usage index, this will do a random construction of G. * * @param L desired length of prime P in bits (the effective key size). * @param N desired length of prime Q in bits. * @param certainty certainty level for prime number generation. * @param random the source of randomness to use. */ public DsaParameterGenerationParameters(int L, int N, int certainty, SecureRandom random) : this(L, N, certainty, random, -1) { }
// TODO Refactor around ServerECDHParams before making this public internal static ECPrivateKeyParameters GenerateEphemeralServerKeyExchange(SecureRandom random, int[] namedCurves, byte[] ecPointFormats, Stream output) { /* First we try to find a supported named curve from the client's list. */ int namedCurve = -1; if (namedCurves == null) { // TODO Let the peer choose the default named curve namedCurve = NamedCurve.secp256r1; } else { for (int i = 0; i < namedCurves.Length; ++i) { int entry = namedCurves[i]; if (NamedCurve.IsValid(entry) && IsSupportedNamedCurve(entry)) { namedCurve = entry; break; } } } ECDomainParameters ecParams = null; if (namedCurve >= 0) { ecParams = GetParametersForNamedCurve(namedCurve); } else { /* If no named curves are suitable, check if the client supports explicit curves. */ if (Arrays.Contains(namedCurves, NamedCurve.arbitrary_explicit_prime_curves)) { ecParams = GetParametersForNamedCurve(NamedCurve.secp256r1); } else if (Arrays.Contains(namedCurves, NamedCurve.arbitrary_explicit_char2_curves)) { ecParams = GetParametersForNamedCurve(NamedCurve.sect283r1); } } if (ecParams == null) { /* * NOTE: We shouldn't have negotiated ECDHE key exchange since we apparently can't find * a suitable curve. */ throw new TlsFatalAlert(AlertDescription.internal_error); } if (namedCurve < 0) { WriteExplicitECParameters(ecPointFormats, ecParams, output); } else { WriteNamedECParameters(namedCurve, output); } return(GenerateEphemeralClientKeyExchange(random, ecPointFormats, ecParams, output)); }
protected virtual SecureRandom InitSecureRandom(bool needed, SecureRandom provided) { return(!needed ? null : (provided != null) ? provided : new SecureRandom()); }
public Ed448PrivateKeyParameters(SecureRandom random) : base(true) { Ed448.GeneratePrivateKey(random, data); }
public abstract void AddSessionInfo(byte[] si, SecureRandom random);
/* * Finds a pair of prime BigInteger's {p, q: p = 2q + 1} * * (see: Handbook of Applied Cryptography 4.86) */ internal static BigInteger[] GenerateSafePrimes(int size, int certainty, SecureRandom random) { BigInteger p, q; int qLength = size - 1; int minWeight = size >> 2; if (size <= 32) { for (;;) { q = new BigInteger(qLength, 2, random); p = q.ShiftLeft(1).Add(BigInteger.One); if (!p.IsProbablePrime(certainty, true)) { continue; } if (certainty > 2 && !q.IsProbablePrime(certainty, true)) { continue; } break; } } else { // Note: Modified from Java version for speed for (;;) { q = new BigInteger(qLength, 0, random); retry: for (int i = 0; i < primeLists.Length; ++i) { int test = q.Remainder(BigPrimeProducts[i]).IntValue; if (i == 0) { int rem3 = test % 3; if (rem3 != 2) { int diff = 2 * rem3 + 2; q = q.Add(BigInteger.ValueOf(diff)); test = (test + diff) % primeProducts[i]; } } int[] primeList = primeLists[i]; for (int j = 0; j < primeList.Length; ++j) { int prime = primeList[j]; int qRem = test % prime; if (qRem == 0 || qRem == (prime >> 1)) { q = q.Add(Six); goto retry; } } } if (q.BitLength != qLength) { continue; } if (!q.RabinMillerTest(2, random, true)) { continue; } p = q.ShiftLeft(1).Add(BigInteger.One); if (!p.RabinMillerTest(certainty, random, true)) { continue; } if (certainty > 2 && !q.RabinMillerTest(certainty - 2, random, true)) { continue; } /* * Require a minimum weight of the NAF representation, since low-weight primes may be * weak against a version of the number-field-sieve for the discrete-logarithm-problem. * * See "The number field sieve for integers of low weight", Oliver Schirokauer. */ if (WNafUtilities.GetNafWeight(p) < minWeight) { continue; } break; } } return(new BigInteger[] { p, q }); }
public PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag encAlgorithm) { this.defAlgorithm = encAlgorithm; this.rand = new SecureRandom(); }
public X509Certificate Generate( AsymmetricKeyParameter privateKey, SecureRandom random) { return(Generate(new Asn1SignatureFactory(signatureAlgorithm, privateKey, random))); }
public KeyParameter(SecureRandom random, int unknown) : base(random, unknown) { }
public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random) { byte[] keyBytes = contentEncryptionKey.GetKey(); AsymmetricKeyParameter senderPublicKey = senderKeyPair.Public; ICipherParameters senderPrivateParams = senderKeyPair.Private; OriginatorIdentifierOrKey originator; try { originator = new OriginatorIdentifierOrKey( CreateOriginatorPublicKey(senderPublicKey)); } catch (IOException e) { throw new InvalidKeyException("cannot extract originator public key: " + e); } Asn1OctetString ukm = null; if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf)) { try { IAsymmetricCipherKeyPairGenerator ephemKPG = GeneratorUtilities.GetKeyPairGenerator(keyAgreementOID); ephemKPG.Init( ((ECPublicKeyParameters)senderPublicKey).CreateKeyGenerationParameters(random)); AsymmetricCipherKeyPair ephemKP = ephemKPG.GenerateKeyPair(); ukm = new DerOctetString( new MQVuserKeyingMaterial( CreateOriginatorPublicKey(ephemKP.Public), null)); senderPrivateParams = new MqvPrivateParameters( (ECPrivateKeyParameters)senderPrivateParams, (ECPrivateKeyParameters)ephemKP.Private, (ECPublicKeyParameters)ephemKP.Public); } catch (IOException e) { throw new InvalidKeyException("cannot extract MQV ephemeral public key: " + e); } catch (SecurityUtilityException e) { throw new InvalidKeyException("cannot determine MQV ephemeral key pair parameters from public key: " + e); } } DerSequence paramSeq = new DerSequence( keyEncryptionOID, DerNull.Instance); AlgorithmIdentifier keyEncAlg = new AlgorithmIdentifier(keyAgreementOID, paramSeq); Asn1EncodableVector recipientEncryptedKeys = new Asn1EncodableVector(); foreach (X509Certificate recipientCert in recipientCerts) { TbsCertificateStructure tbsCert; try { tbsCert = TbsCertificateStructure.GetInstance( Asn1Object.FromByteArray(recipientCert.GetTbsCertificate())); } catch (Exception) { throw new ArgumentException("can't extract TBS structure from certificate"); } // TODO Should there be a SubjectKeyIdentifier-based alternative? IssuerAndSerialNumber issuerSerial = new IssuerAndSerialNumber( tbsCert.Issuer, tbsCert.SerialNumber.Value); KeyAgreeRecipientIdentifier karid = new KeyAgreeRecipientIdentifier(issuerSerial); ICipherParameters recipientPublicParams = recipientCert.GetPublicKey(); if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf)) { recipientPublicParams = new MqvPublicParameters( (ECPublicKeyParameters)recipientPublicParams, (ECPublicKeyParameters)recipientPublicParams); } // Use key agreement to choose a wrap key for this recipient IBasicAgreement keyAgreement = AgreementUtilities.GetBasicAgreementWithKdf( keyAgreementOID, keyEncryptionOID.Id); keyAgreement.Init(new ParametersWithRandom(senderPrivateParams, random)); BigInteger agreedValue = keyAgreement.CalculateAgreement(recipientPublicParams); int keyEncryptionKeySize = GeneratorUtilities.GetDefaultKeySize(keyEncryptionOID) / 8; byte[] keyEncryptionKeyBytes = X9IntegerConverter.IntegerToBytes(agreedValue, keyEncryptionKeySize); KeyParameter keyEncryptionKey = ParameterUtilities.CreateKeyParameter( keyEncryptionOID, keyEncryptionKeyBytes); // Wrap the content encryption key with the agreement key IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionOID.Id); keyWrapper.Init(true, new ParametersWithRandom(keyEncryptionKey, random)); byte[] encryptedKeyBytes = keyWrapper.Wrap(keyBytes, 0, keyBytes.Length); Asn1OctetString encryptedKey = new DerOctetString(encryptedKeyBytes); recipientEncryptedKeys.Add(new RecipientEncryptedKey(karid, encryptedKey)); } return(new RecipientInfo(new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg, new DerSequence(recipientEncryptedKeys)))); }
public void TestECDsa239BitBinary() { BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552"); BigInteger s = new BigInteger("197030374000731686738334997654997227052849804072198819102649413465737174"); byte[] kData = BigIntegers.AsUnsignedByteArray( new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = FixedSecureRandom.From(kData); ECCurve curve = new F2mCurve( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECDomainParameters parameters = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.ValueOf(4)); // h ECPrivateKeyParameters sKey = new ECPrivateKeyParameters( "ECDSA", new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d parameters); ECPublicKeyParameters vKey = new ECPublicKeyParameters( "ECDSA", curve.DecodePoint(Hex.Decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q parameters); ISigner sgr = SignerUtilities.GetSigner("ECDSA"); byte[] message = Encoding.ASCII.GetBytes("abc"); sgr.Init(true, new ParametersWithRandom(sKey, k)); sgr.BlockUpdate(message, 0, message.Length); byte[] sigBytes = sgr.GenerateSignature(); sgr.Init(false, vKey); sgr.BlockUpdate(message, 0, message.Length); if (!sgr.VerifySignature(sigBytes)) { Fail("239 Bit EC verification failed"); } BigInteger[] sig = DerDecode(sigBytes); if (!r.Equals(sig[0])) { Fail("r component wrong." + SimpleTest.NewLine + " expecting: " + r + SimpleTest.NewLine + " got : " + sig[0]); } if (!s.Equals(sig[1])) { Fail("s component wrong." + SimpleTest.NewLine + " expecting: " + s + SimpleTest.NewLine + " got : " + sig[1]); } }
/// <summary> Initialise the padder.</summary> /// <param name="random">- a SecureRandom if available. /// </param> public virtual void Init(SecureRandom random) { // nothing to do. }
public void GenerateIntegersWithSameMaxAndMinLimits() { using (var random = new SecureRandom()) { const int Max = 25; const int Min = 25; for (var i = 0; i < 100000; i++) { Assert.IsTrue(random.Next(Min, Max) == Min); } } }
public DtlsServerProtocol(SecureRandom secureRandom) : base(secureRandom) { }
public void GenerateIntegerWithUpperRangeAfterDisposing() { SecureRandom random = null; using (random = new SecureRandom()) { } random.Next(2); }
/// <summary> /// Constructor for a new JPakeParticipant. /// /// After construction, the State state will be STATE_INITIALIZED. /// /// Throws NullReferenceException if any argument is null. Throws /// ArgumentException if password is empty. /// </summary> /// <param name="participantId">Unique identifier of this participant. /// The two participants in the exchange must NOT share the same id.</param> /// <param name="password">Shared secret. /// A defensive copy of this array is made (and cleared once CalculateKeyingMaterial() is called). /// Caller should clear the input password as soon as possible.</param> /// <param name="group">Prime order group. See JPakePrimeOrderGroups for standard groups.</param> /// <param name="digest">Digest to use during zero knowledge proofs and key confirmation /// (SHA-256 or stronger preferred).</param> /// <param name="random">Source of secure random data for x1 and x2, and for the zero knowledge proofs.</param> public JPakeParticipant(string participantId, char[] password, JPakePrimeOrderGroup group, IDigest digest, SecureRandom random) { JPakeUtilities.ValidateNotNull(participantId, "participantId"); JPakeUtilities.ValidateNotNull(password, "password"); JPakeUtilities.ValidateNotNull(group, "p"); JPakeUtilities.ValidateNotNull(digest, "digest"); JPakeUtilities.ValidateNotNull(random, "random"); if (password.Length == 0) { throw new ArgumentException("Password must not be empty."); } this.participantId = participantId; // Create a defensive copy so as to fully encapsulate the password. // // This array will contain the password for the lifetime of this // participant BEFORE CalculateKeyingMaterial() is called. // // i.e. When CalculateKeyingMaterial() is called, the array will be cleared // in order to remove the password from memory. // // The caller is responsible for clearing the original password array // given as input to this constructor. this.password = new char[password.Length]; Array.Copy(password, this.password, password.Length); this.p = group.P; this.q = group.Q; this.g = group.G; this.digest = digest; this.random = random; this.state = STATE_INITIALIZED; }
public void GetByteValuesUniqueValuesOnlyButElementNumberIsTooBig() { using (var random = new SecureRandom()) { random.GetByteValues(2560, ValueGeneration.UniqueValuesOnly); } }
/** * Initialises the server to accept a new client authentication attempt * @param N The safe prime associated with the client's verifier * @param g The group parameter associated with the client's verifier * @param v The client's verifier * @param digest The digest algorithm associated with the client's verifier * @param random For key generation */ public virtual void Init(BigInteger N, BigInteger g, BigInteger v, IDigest digest, SecureRandom random) { this.N = N; this.g = g; this.v = v; this.random = random; this.digest = digest; }
public void GetInt32ValuesAfterDisposing() { SecureRandom random = null; using (random = new SecureRandom()) { } random.GetInt32Values(1, ValueGeneration.DuplicatesAllowed); }
public void TestDefault() { var random = new SecureRandom(); CheckSecureRandom(random); }
public void GetInt32ValuesUniqueValuesOnly() { var generator = new MockRandomNumberGeneratorForGetInt32Values(ValueGeneration.UniqueValuesOnly); using (var random = new SecureRandom(generator)) { var elements = random.GetInt32Values( 8, ValueGeneration.UniqueValuesOnly); Assert.AreEqual(8, elements.Length); for (var i = 0; i < elements.Length; i++) { var element = elements[i]; Assert.IsTrue(element >= int.MinValue); Assert.IsTrue(element <= int.MaxValue); } Assert.AreEqual(elements.Length, new HashSet<int>(elements).Count); Assert.AreEqual(9, generator.MethodCallCount); } }
public void TestECDsa239BitPrime() { BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176"); BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783"); byte[] kData = BigIntegers.AsUnsignedByteArray( new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = FixedSecureRandom.From(kData); ECCurve curve = new FpCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters spec = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( "ECDSA", new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d spec); ECPublicKeyParameters pubKey = new ECPublicKeyParameters( "ECDSA", curve.DecodePoint(Hex.Decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q spec); ISigner sgr = SignerUtilities.GetSigner("ECDSA"); // KeyFactory f = KeyFactory.GetInstance("ECDSA"); // PrivateKey sKey = f.generatePrivate(priKey); // PublicKey vKey = f.generatePublic(pubKey); AsymmetricKeyParameter sKey = priKey; AsymmetricKeyParameter vKey = pubKey; sgr.Init(true, new ParametersWithRandom(sKey, k)); byte[] message = Encoding.ASCII.GetBytes("abc"); sgr.BlockUpdate(message, 0, message.Length); byte[] sigBytes = sgr.GenerateSignature(); sgr.Init(false, vKey); sgr.BlockUpdate(message, 0, message.Length); if (!sgr.VerifySignature(sigBytes)) { Fail("239 Bit EC verification failed"); } BigInteger[] sig = DerDecode(sigBytes); if (!r.Equals(sig[0])) { Fail("r component wrong." + SimpleTest.NewLine + " expecting: " + r + SimpleTest.NewLine + " got : " + sig[0]); } if (!s.Equals(sig[1])) { Fail("s component wrong." + SimpleTest.NewLine + " expecting: " + s + SimpleTest.NewLine + " got : " + sig[1]); } }
public void GetInt32ValuesUniqueValuesOnlyButElementNumberIsTooBig() { using (var random = new SecureRandom()) { random.GetInt32Values((uint)int.MaxValue + 10u, ValueGeneration.UniqueValuesOnly); } }
private OcspReq GenerateRequest( DerObjectIdentifier signingAlgorithm, AsymmetricKeyParameter privateKey, X509Certificate[] chain, SecureRandom random) { Asn1EncodableVector requests = new Asn1EncodableVector(); foreach (RequestObject reqObj in list) { try { requests.Add(reqObj.ToRequest()); } catch (Exception e) { throw new OcspException("exception creating Request", e); } } TbsRequest tbsReq = new TbsRequest(requestorName, new DerSequence(requests), requestExtensions); ISigner sig = null; Signature signature = null; if (signingAlgorithm != null) { if (requestorName == null) { throw new OcspException("requestorName must be specified if request is signed."); } try { sig = SignerUtilities.GetSigner(signingAlgorithm.Id); if (random != null) { sig.Init(true, new ParametersWithRandom(privateKey, random)); } else { sig.Init(true, privateKey); } } catch (Exception e) { throw new OcspException("exception creating signature: " + e, e); } DerBitString bitSig = null; try { byte[] encoded = tbsReq.GetEncoded(); sig.BlockUpdate(encoded, 0, encoded.Length); bitSig = new DerBitString(sig.GenerateSignature()); } catch (Exception e) { throw new OcspException("exception processing TBSRequest: " + e, e); } AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(signingAlgorithm, DerNull.Instance); if (chain != null && chain.Length > 0) { Asn1EncodableVector v = new Asn1EncodableVector(); try { for (int i = 0; i != chain.Length; i++) { v.Add( X509CertificateStructure.GetInstance( Asn1Object.FromByteArray(chain[i].GetEncoded()))); } } catch (IOException e) { throw new OcspException("error processing certs", e); } catch (CertificateEncodingException e) { throw new OcspException("error encoding certs", e); } signature = new Signature(sigAlgId, bitSig, new DerSequence(v)); } else { signature = new Signature(sigAlgId, bitSig); } } return(new OcspReq(new OcspRequest(tbsReq, signature))); }
/// <remarks>Both streams can be the same object</remarks> public TlsProtocolHandler(Stream input, Stream output, SecureRandom secureRandom) : base(input, output, secureRandom) { }
internal static byte[] GenerateIV(int length, SecureRandom random) { byte[] array = new byte[length]; ((Random)random).NextBytes(array); return(array); }
public void CreateGeneratorWithNullProvider() { using (var random = new SecureRandom(null)) { } }
/// <summary> /// Encryption constructor to create a new random key from an intermediate /// </summary> public Bip38KeyPair(Bip38Intermediate intermediate, bool retainPrivateKeyWhenPossible = false) { // generate seedb byte[] seedb = new byte[24]; SecureRandom sr = new SecureRandom(); sr.NextBytes(seedb); // get factorb as sha256(sha256(seedb)) Sha256Digest sha256 = new Sha256Digest(); sha256.BlockUpdate(seedb, 0, 24); factorb = new byte[32]; sha256.DoFinal(factorb, 0); sha256.BlockUpdate(factorb, 0, 32); sha256.DoFinal(factorb, 0); // get ECPoint from passpoint PublicKey pk = new PublicKey(intermediate.passpoint); ECPoint generatedpoint = pk.GetECPoint().Multiply(new BigInteger(1, factorb)); byte[] generatedpointbytes = generatedpoint.GetEncoded(); PublicKey generatedaddress = new PublicKey(generatedpointbytes); // get addresshash UTF8Encoding utf8 = new UTF8Encoding(false); byte[] generatedaddressbytes = utf8.GetBytes(generatedaddress.AddressBase58); sha256.BlockUpdate(generatedaddressbytes, 0, generatedaddressbytes.Length); byte[] addresshashfull = new byte[32]; sha256.DoFinal(addresshashfull, 0); sha256.BlockUpdate(addresshashfull, 0, 32); sha256.DoFinal(addresshashfull, 0); byte[] addresshashplusownerentropy = new byte[12]; Array.Copy(addresshashfull, 0, addresshashplusownerentropy, 0, 4); Array.Copy(intermediate.ownerentropy, 0, addresshashplusownerentropy, 4, 8); // derive encryption key material derived = new byte[64]; SCrypt.ComputeKey(intermediate.passpoint, addresshashplusownerentropy, 1024, 1, 1, 1, derived); byte[] derivedhalf2 = new byte[32]; Array.Copy(derived, 32, derivedhalf2, 0, 32); byte[] unencryptedpart1 = new byte[16]; for (int i = 0; i < 16; i++) { unencryptedpart1[i] = (byte)(seedb[i] ^ derived[i]); } byte[] encryptedpart1 = new byte[16]; // encrypt it var aes = Aes.Create(); aes.KeySize = 256; aes.Mode = CipherMode.ECB; aes.Key = derivedhalf2; ICryptoTransform encryptor = aes.CreateEncryptor(); encryptor.TransformBlock(unencryptedpart1, 0, 16, encryptedpart1, 0); encryptor.TransformBlock(unencryptedpart1, 0, 16, encryptedpart1, 0); byte[] unencryptedpart2 = new byte[16]; for (int i = 0; i < 8; i++) { unencryptedpart2[i] = (byte)(encryptedpart1[i + 8] ^ derived[i + 16]); } for (int i = 0; i < 8; i++) { unencryptedpart2[i + 8] = (byte)(seedb[i + 16] ^ derived[i + 24]); } byte[] encryptedpart2 = new byte[16]; encryptor.TransformBlock(unencryptedpart2, 0, 16, encryptedpart2, 0); encryptor.TransformBlock(unencryptedpart2, 0, 16, encryptedpart2, 0); byte[] result = new byte[39]; result[0] = 0x01; result[1] = 0x43; result[2] = generatedaddress.IsCompressedPoint ? (byte)0x20 : (byte)0x00; if (intermediate.LotSequencePresent) { result[2] |= 0x04; } Array.Copy(addresshashfull, 0, result, 3, 4); Array.Copy(intermediate.ownerentropy, 0, result, 7, 8); Array.Copy(encryptedpart1, 0, result, 15, 8); Array.Copy(encryptedpart2, 0, result, 23, 16); _encryptedKey = Util.ByteArrayToBase58Check(result); _pubKey = generatedaddress.PublicKeyBytes; _hash160 = generatedaddress.Hash160; var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1"); if (retainPrivateKeyWhenPossible && intermediate.passfactor != null) { BigInteger privatekey = new BigInteger(1, intermediate.passfactor).Multiply(new BigInteger(1, factorb)).Mod(ps.N); _privKey = new KeyPair(privatekey).PrivateKeyBytes; } // create the confirmation code confirmationCodeInfo = new byte[51]; // constant provides for prefix "cfrm38" confirmationCodeInfo[0] = 0x64; confirmationCodeInfo[1] = 0x3B; confirmationCodeInfo[2] = 0xF6; confirmationCodeInfo[3] = 0xA8; confirmationCodeInfo[4] = 0x9A; // fields for flagbyte, addresshash, and ownerentropy all copy verbatim Array.Copy(result, 2, confirmationCodeInfo, 5, 1 + 4 + 8); }
public TlsProtocolHandler(Stream stream, SecureRandom secureRandom) : base(stream, stream, secureRandom) { }
public static (Certificate crtificate, AsymmetricKeyParameter privateKey) CreateSelfSignedTlsCert( string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivateKey) { const int keyStrength = DEFAULT_KEY_SIZE; if (issuerPrivateKey == null) { issuerPrivateKey = CreatePrivateKeyResource(issuerName); } // Generating Random Numbers var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", issuerPrivateKey, random); // The Certificate Generator var certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName[] { new GeneralName(GeneralName.DnsName, "localhost"), new GeneralName(GeneralName.DnsName, "127.0.0.1") })); certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(new List <DerObjectIdentifier>() { new DerObjectIdentifier("1.3.6.1.5.5.7.3.1") })); // Serial Number var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); // Issuer and Subject Name var subjectDn = new X509Name(subjectName); var issuerDn = new X509Name(issuerName); certificateGenerator.SetIssuerDN(issuerDn); certificateGenerator.SetSubjectDN(subjectDn); // Valid For var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddYears(70); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); // Subject Public Key var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); var subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); // self sign certificate var certificate = certificateGenerator.Generate(signatureFactory); var chain = new X509CertificateStructure[] { X509CertificateStructure.GetInstance(certificate.GetEncoded()) }; var tlsCertificate = new Certificate(chain); return(tlsCertificate, subjectKeyPair.Private); }
public ParametersWithIV(SecureRandom random, int unknown) : base(random, unknown) { }
public static X509Certificate2 CreateSelfSignedCert(string subjectName, string issuerName, AsymmetricKeyParameter privateKey) { const int keyStrength = DEFAULT_KEY_SIZE; if (privateKey == null) { privateKey = CreatePrivateKeyResource(issuerName); } var issuerPrivKey = privateKey; // Generating Random Numbers var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", issuerPrivKey, random); // The Certificate Generator var certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName[] { new GeneralName(GeneralName.DnsName, "localhost"), new GeneralName(GeneralName.DnsName, "127.0.0.1") })); certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(new List <DerObjectIdentifier>() { new DerObjectIdentifier("1.3.6.1.5.5.7.3.1") })); // Serial Number var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random); certificateGenerator.SetSerialNumber(serialNumber); // Issuer and Subject Name var subjectDn = new X509Name(subjectName); var issuerDn = new X509Name(issuerName); certificateGenerator.SetIssuerDN(issuerDn); certificateGenerator.SetSubjectDN(subjectDn); // Valid For var notBefore = DateTime.UtcNow.Date; var notAfter = notBefore.AddYears(70); certificateGenerator.SetNotBefore(notBefore); certificateGenerator.SetNotAfter(notAfter); // Subject Public Key var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength); var keyPairGenerator = new RsaKeyPairGenerator(); keyPairGenerator.Init(keyGenerationParameters); var subjectKeyPair = keyPairGenerator.GenerateKeyPair(); certificateGenerator.SetPublicKey(subjectKeyPair.Public); // self sign certificate var certificate = certificateGenerator.Generate(signatureFactory); // Originally pre-processor defines were used to try and pick the supported way to get from a Bouncy Castle // certificate and private key to a .NET certificate. The problem is that setting the private key on a .NET // X509 certificate is possible in .NET Framework but NOT in .NET Core. To complicate matters even further // the workaround in the CovertBouncyCert method of saving a cert + pvt key to a .pfx stream and then // reloading does not work on macOS or Unity (and possibly elsewhere) due to .pfx serialisation not being // compatible. This is the exception from Unity: // // Mono.Security.ASN1..ctor (System.Byte[] data) (at <6a66fe237d4242c9924192d3c28dd540>:0) // Mono.Security.X509.X509Certificate.Parse(System.Byte[] data)(at < 6a66fe237d4242c9924192d3c28dd540 >:0) // // Summary: // .NET Framework (including Mono on Linux, macOS and WSL) // - Set x509.PrivateKey works. // .NET Standard: // - Set x509.PrivateKey for a .NET Framework application. // - Set x509.PrivateKey for a .NET Core application FAILS. // .NET Core: // - Set x509.PrivateKey for a .NET Core application FAILS. // - PFX serialisation works on Windows. // - PFX serialisation works on WSL and Linux. // - PFX serialisation FAILS on macOS. // // For same issue see https://github.com/dotnet/runtime/issues/23635. // For fix in net5 see https://github.com/dotnet/corefx/pull/42226. try { // corresponding private key var info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); // merge into X509Certificate2 var x509 = new X509Certificate2(certificate.GetEncoded()); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded()); if (seq.Count != 9) { throw new PemException("malformed sequence in RSA private key"); } var rsa = RsaPrivateKeyStructure.GetInstance(seq); //new RsaPrivateKeyStructure(seq); var rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); x509.PrivateKey = ToRSA(rsaparams); return(x509); } catch { return(ConvertBouncyCert(certificate, subjectKeyPair)); } }
private static BigInteger CalculateGenerator_FIPS186_3_Unverifiable(BigInteger p, BigInteger q, SecureRandom r) { return(CalculateGenerator_FIPS186_2(p, q, r)); }
internal static S2k GenerateS2k(HashAlgorithmTag hashAlgorithm, int s2kCount, SecureRandom random) { byte[] iv = GenerateIV(8, random); return(new S2k(hashAlgorithm, iv, s2kCount)); }
private static BigInteger CalculateGenerator_FIPS186_2(BigInteger p, BigInteger q, SecureRandom r) { BigInteger e = p.Subtract(BigInteger.One).Divide(q); BigInteger pSub2 = p.Subtract(BigInteger.Two); for (;;) { BigInteger h = BigIntegers.CreateRandomInRange(BigInteger.Two, pSub2, r); BigInteger g = h.ModPow(e, p); if (g.BitLength > 1) { return(g); } } }
public void Init(SecureRandom random) { this.random = ((random == null) ? new SecureRandom() : random); }