/** * Create a System.Random object from this RandomNumberGenerator */ public SecureRandom(RandomNumberGenerator rng) { _rng = rng; _sample_buffer = new byte[4]; _state = new Sample(); _state.Val = 0; _state.Max = 1; }
public override byte[] CreateKeyExchange(byte[] rgbData) { if (this._rsaKey == null) { throw new CryptographicUnexpectedOperationException(Environment.GetResourceString("Cryptography_MissingKey")); } if (this._rsaKey is RSACryptoServiceProvider) { return ((RSACryptoServiceProvider) this._rsaKey).Encrypt(rgbData, false); } int num = this._rsaKey.KeySize / 8; if ((rgbData.Length + 11) > num) { throw new CryptographicException(Environment.GetResourceString("Cryptography_Padding_EncDataTooBig", new object[] { num - 11 })); } byte[] data = new byte[num]; if (this.RngValue == null) { this.RngValue = RandomNumberGenerator.Create(); } this.Rng.GetNonZeroBytes(data); data[0] = 0; data[1] = 2; data[(num - rgbData.Length) - 1] = 0; Buffer.InternalBlockCopy(rgbData, 0, data, num - rgbData.Length, rgbData.Length); return this._rsaKey.EncryptValue(data); }
private void SetUp(long length) { this.transmission = new Transmission(TransmissionType.DOWNLOAD_NEW_FILE, "testfile"); this.transmission.AddDefaultConstraints(); if (this.localFileStream != null) { this.localFileStream.Dispose(); } this.localFileStream = new MemoryStream(); if (this.hashAlg != null) { this.hashAlg.Dispose(); } this.hashAlg = new SHA1Managed(); this.remoteLength = length; this.remoteContent = new byte[this.remoteLength]; if (this.random != null) { this.random.Dispose(); } this.random = RandomNumberGenerator.Create(); this.random.GetBytes(this.remoteContent); this.mockedMemStream = new Mock<MemoryStream>(this.remoteContent) { CallBase = true }; this.mockedStream = new Mock<IContentStream>(); this.mockedStream.Setup(stream => stream.Length).Returns(this.remoteLength); this.mockedStream.Setup(stream => stream.Stream).Returns(this.mockedMemStream.Object); this.mockedDocument = new Mock<IDocument>(); this.mockedDocument.Setup(doc => doc.ContentStreamLength).Returns(this.remoteLength); this.mockedDocument.Setup(doc => doc.GetContentStream()).Returns(this.mockedStream.Object); }
private byte[] HashPasswordV3(string password, RandomNumberGenerator rng) { return HashPasswordV3(password, rng, prf: KeyDerivationPrf.HMACSHA256, iterCount: _iterCount, saltSize: 128 / 8, numBytesRequested: 256 / 8); }
private PasswordHasher() { _iterCount = 10000; if (_iterCount < 1) { throw new InvalidOperationException("InvalidPasswordHasherIterationCount"); } _rng = RandomNumberGenerator.Create(); }
public static int GetRandom(int aFrom, int aTo) { System.Security.Cryptography.RandomNumberGenerator mRandom = System.Security.Cryptography.RandomNumberGenerator.Create(); byte[] mByte = new byte[1]; mRandom.GetNonZeroBytes(mByte); return((mByte[0] % ((aTo - aFrom) + 1)) + aFrom); }
private static int GenerateRandomInt32Value(RandomNumberGenerator randomNumberGenerator) { var fourRandomBytes = new byte[4]; // 4 bytes = 32 bits = Int32 randomNumberGenerator.GetBytes(fourRandomBytes); var randomInt32Value = BitConverter.ToInt32(fourRandomBytes, 0); return randomInt32Value; }
public static string CreateHash(string password) { // Generate a random salt byte[] salt = new byte[SALT_BYTES]; try { using (System.Security.Cryptography.RandomNumberGenerator csprng = System.Security.Cryptography.RandomNumberGenerator.Create()) { csprng.GetBytes(salt); } } catch (CryptographicException ex) { throw new CannotPerformOperationException( "Random number generator not available.", ex ); } catch (ArgumentNullException ex) { throw new CannotPerformOperationException( "Invalid argument given to random number generator.", ex ); } byte[] hash = PBKDF2(password, salt, PBKDF2_ITERATIONS, HASH_BYTES); // format: algorithm:iterations:hashSize:salt:hash String parts = "sha1:" + PBKDF2_ITERATIONS + ":" + hash.Length + ":" + Convert.ToBase64String(salt) + ":" + Convert.ToBase64String(hash); return(parts); }
public CumulativeRandom(int maxTimes) { rnd = RNGCryptoServiceProvider.Create(); //rnd = new Random(); basis = 1.0/maxTimes; buff = 0.0; }
/// <summary> /// Generate a random IV. /// </summary> /// <returns></returns> private static byte[] IV() { byte[] data = new byte[IV_SIZE]; System.Security.Cryptography.RandomNumberGenerator rnd = System.Security.Cryptography.RandomNumberGenerator.Create(); rnd.GetBytes(data); return(data); }
/// <summary> /// Initializes a new instance of the RandomNumberGeneratorWrapper class, wrapping a given <see cref="System.Security.Cryptography.RandomNumberGenerator"/> instance. /// </summary> /// <param name="rand">The instance of <see cref="System.Security.Cryptography.RandomNumberGenerator"/> to wrap.</param> /// <exception cref="System.ArgumentNullException"><paramref name="rand"/> is null.</exception> public RandomNumberGeneratorWrapper(RandomNumberGenerator rand) { if (rand == null) { throw new ArgumentNullException("rand"); } this.rand = rand; }
/** * Return a random AHAddress initialized from the given rng */ public AHAddress(RandomNumberGenerator rng) { byte[] buffer = new byte[MemSize]; rng.GetBytes(buffer); SetClass(buffer, this.Class); _buffer = MemBlock.Reference(buffer, 0, MemSize); _prefix = (uint)NumberSerializer.ReadInt(_buffer, 0); }
public RNGCryptoServiceProvider(CspParameters cspParams) { if (cspParams != null) throw new PlatformNotSupportedException(); // This class wraps RandomNumberGenerator.Create() from Algorithms assembly _impl = Create(); }
/// <summary> /// Construct a new random number generator with random seed. /// </summary> /// <param name="rng">The <see cref="RandomNumberGenerator"/> to use.</param> /// <param name="threadSafe">if set to <c>true</c> , the class is thread safe.</param> public SystemCryptoRandomNumberGenerator(RandomNumberGenerator rng, bool threadSafe) : base(threadSafe) { if (rng == null) { throw new ArgumentNullException("rng"); } mRandom = rng; }
public static void GetBytes(byte[] dest) { if (Generator == null) { Generator = RNGCryptoServiceProvider.Create(); } Generator.GetBytes(dest); }
public CryptoApiEntropySourceProvider(RandomNumberGenerator rng, bool isPredictionResistant) { if (rng == null) throw new ArgumentNullException("rng"); mRng = rng; mPredictionResistant = isPredictionResistant; }
protected virtual void Dispose(bool disposing) { if (disposing) { _generator.Dispose(); _generator = null; } }
public PatchworkTransformService( RandomNumberGenerator randomNumberGenerator, byte delta = 4, int iterationNumber = 20000) { this._randomNumberGenerator = randomNumberGenerator; this._delta = delta; this._iterationNumber = iterationNumber; }
public string CreateSalt() { using (_generator = _generatorInitializer()) { var byteArr = new byte[32]; _generator.GetBytes(byteArr); return Convert.ToBase64String(byteArr); } }
public static RandomNumberGenerator GetRandom() { if (_random == null) { _random = new RNGCryptoServiceProvider(); } return _random; }
static public byte[] IV (int size) { if (rng == null) rng = RandomNumberGenerator.Create (); byte[] iv = new byte [size]; rng.GetBytes (iv); return iv; }
static public byte[] Key (int size) { if (rng == null) rng = RandomNumberGenerator.Create (); byte[] key = new byte [size]; rng.GetBytes (key); return key; }
internal static string Create(ref RandomNumberGenerator randgen) { if (randgen == null) { randgen = new RNGCryptoServiceProvider(); } byte[] data = new byte[15]; randgen.GetBytes(data); return Encode(data); }
public TokenManager() { sha1 = SHA1.Create(); random = RandomNumberGenerator.Create(); LastSecretGeneration = DateTime.MinValue; //in order to force the update secret = new byte[10]; previousSecret = new byte[10]; random.GetNonZeroBytes(secret); random.GetNonZeroBytes(previousSecret); }
protected Spritz() { #if !DOTNET5_4 LegalBlockSizesValue = s_legalBlockSizes; LegalKeySizesValue = s_legalKeySizes; #endif this.BlockSize = 256; this.KeySize = 128; this.rng = RandomNumberGenerator.Create(); }
public TokenManager() { sha1 = HashAlgoFactory.Create<SHA1>(); random = new RNGCryptoServiceProvider (); LastSecretGeneration = DateTime.MinValue; //in order to force the update secret = new byte[10]; previousSecret = new byte[10]; random.GetNonZeroBytes(secret); random.GetNonZeroBytes(previousSecret); }
/// <summary> /// Initializes a new instance of the <see cref="PBKDF2CryptoProvider" /> class. /// </summary> /// <param name="saltByteSize">The salt size. Defaults to 24.</param> /// <param name="hashByteSize">The hash size. Defaults to 24.</param> /// <param name="iterations">The number of iterations used by the algorithm. Defaults to 10000.</param> /// <param name="delimiter">The hash components delimiter. Defaults to ':'.</param> public PBKDF2CryptoProvider(int saltByteSize = 128, int hashByteSize = 128, int iterations = 10000, char[] delimiter = null) { this.saltByteSize = saltByteSize; this.hashByteSize = hashByteSize; this.iterations = iterations; this.delimiter = delimiter ?? new[] { ':' }; this.rng = new RNGCryptoServiceProvider(); this.log = LogManager.GetLogger("Sentinel.OAuth.PBKDF2CryptoProvider"); }
protected SRPParameters(SRPVersion version, bool caseSensitive) { AlgorithmVersion = version; CaseSensitive = caseSensitive; SetupParameters(); RandomGenerator = new RNGCryptoServiceProvider(); Multiplier = version == SRPVersion.SRP6 ? (BigInteger)3 : Hash.FinalizeHash(Modulus, Generator); }
protected Salsa20() { #if NET451 LegalBlockSizesValue = s_legalBlockSizes; LegalKeySizesValue = s_legalKeySizes; #endif this.BlockSize = 64; this.KeySize = 256; this.Rounds = Salsa20Rounds.Twenty; this.rng = RandomNumberGenerator.Create(); }
public string GenerateSalt() { byte[] saltBytes = new byte[128 / 8]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(saltBytes); } string salt = Convert.ToBase64String(saltBytes); return(salt); }
/// <summary> /// Generate cryptographically random key of given bit size. /// </summary> /// <param name="size">The size.</param> /// <returns> the key </returns> private static string GenerateRandomKey(int size) { byte[] key = new byte[(int)size / 8]; #if FullNetFx RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider(); #else System.Security.Cryptography.RandomNumberGenerator crypto = System.Security.Cryptography.RandomNumberGenerator.Create(); #endif crypto.GetBytes(key); return(Convert.ToBase64String(key)); }
protected virtual void Dispose(bool disposing) { if (!this.isDisposed) { if (disposing) { this.randomNumberGenerator.Dispose(); this.randomNumberGenerator = null; } this.isDisposed = true; } }
private void btnselnumberchars_Click(object sender, EventArgs e) { R randgen = R.Create(); byte[] rand = new byte[10]; randgen.GetBytes(rand); // Random Number between 0 - 255 --- we need between 0 - chars2generate int startselection = (int)Math.Floor(rand[2] * (rtbseedgen.TextLength - cbbNumChars.SelectedIndex + 1) / 255.0); if (startselection < 0) { startselection = 0; } rtbseedgen.Select(startselection, cbbNumChars.SelectedIndex + 1); rtbseedgen.Focus(); }
public static string StrRandomNumber(int length) { System.Security.Cryptography.RandomNumberGenerator rng = System.Security.Cryptography.RandomNumberGenerator.Create(); byte[] buffer1 = new byte[length]; rng.GetBytes(buffer1); rng = null; string str = "0123456789"; StringBuilder s = new StringBuilder(); for (int i = 0; i < length; i++) { Random rnd = new Random(buffer1[i]); int w = rnd.Next(0, str.Length); s.Append(str.Substring(w, 1)); } return(s.ToString()); }
/// <summary> /// Produces 'Count' Random Characters from Character List /// </summary> /// <param name="count">Number of Chars to Produce</param> /// <param name="from_list">Char Array that holds possible Chars</param> /// <returns>String with Count Random Characters</returns> private string produce_random(int number = -1) { int count = 0; if (number == -1) { count = cbbNumChars.SelectedIndex + 1; } else { count = number; } char[] from_list = get_char_set().ToCharArray(); if (from_list.Length == 0) { return(""); } R randgen = R.Create(); byte[] rand = new byte[5000]; string ret = ""; while (ret.Length < count) { randgen.GetNonZeroBytes(rand); foreach (byte x in rand) { if (from_list.Contains((char)x)) { ret += (char)x; } if (ret.Length >= count) { return(ret); } } } return(ret); }
/// <summary> /// Function that generates random string. /// </summary> /// <param name="minLen">Minimal length.</param> /// <param name="maxLen">Maximum length.</param> /// <param name="useDigit">Value that indicates if numbers are included.</param> /// <returns>String value.</returns> public static string GetRandStr(int minLen, int maxLen, bool useDigit = false) { string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; if (useDigit) { valid += "1234567890"; } StringBuilder res = new StringBuilder(); int length = R.GetInt32(minLen, maxLen + 1); for (int i = 0; i < length; i++) { res.Append(valid[R.GetInt32(valid.Length)]); } return(res.ToString()); }
internal static BigInteger NextBigInteger(this System.Security.Cryptography.RandomNumberGenerator rng, int sizeInBits) { if (sizeInBits < 0) { throw new ArgumentException("sizeInBits must be non-negative"); } if (sizeInBits == 0) { return(0); } byte[] b = new byte[sizeInBits / 8 + 1]; rng.GetBytes(b); if (sizeInBits % 8 == 0) { b[b.Length - 1] = 0; } else { b[b.Length - 1] &= (byte)((1 << sizeInBits % 8) - 1); } return(new BigInteger(b)); }
void RandomExample() { { Random rng = new Random(); Console.WriteLine(rng.Next().ToString()); Console.WriteLine(rng.Next().ToString()); Console.WriteLine(rng.Next().ToString()); } Console.WriteLine(); for (int i = 0; i < 2; i++) { Random rngSeed = new Random(1); // Pro = reproducablility Console.WriteLine(rngSeed.Next().ToString()); Console.WriteLine(rngSeed.Next().ToString()); Console.WriteLine("-"); } Console.WriteLine(); for (int i = 0; i < 100; i++) { // Approx 10 ms between need Random seeds Console.WriteLine(new Random().Next().ToString()); } Console.WriteLine(); System.Security.Cryptography.RandomNumberGenerator rngPlusPlus = System.Security.Cryptography.RandomNumberGenerator.Create(); byte[] randomData = new byte[4]; Console.WriteLine(randomData[0]); rngPlusPlus.GetBytes(randomData); Console.WriteLine(randomData[0]); }
internal static unsafe bool ExportPkcs8KeyBlob( bool allocate, SafeNCryptKeyHandle keyHandle, ReadOnlySpan <char> password, int kdfCount, Span <byte> destination, out int bytesWritten, out byte[]?allocated) { using (SafeUnicodeStringHandle stringHandle = new SafeUnicodeStringHandle(password)) { ReadOnlySpan <byte> pkcs12TripleDesOidBytes = "1.2.840.113549.1.12.1.3\0" u8; // the Windows APIs for OID strings are ASCII-only fixed(byte *oidPtr = &MemoryMarshal.GetReference(pkcs12TripleDesOidBytes)) { Interop.NCrypt.NCryptBuffer *buffers = stackalloc Interop.NCrypt.NCryptBuffer[3]; Interop.NCrypt.PBE_PARAMS pbeParams = default; Span <byte> salt = new Span <byte>(pbeParams.rgbSalt, Interop.NCrypt.PBE_PARAMS.RgbSaltSize); RandomNumberGenerator.Fill(salt); pbeParams.Params.cbSalt = salt.Length; pbeParams.Params.iIterations = kdfCount; buffers[0] = new Interop.NCrypt.NCryptBuffer { BufferType = Interop.NCrypt.BufferType.PkcsSecret, cbBuffer = checked (2 * (password.Length + 1)), pvBuffer = stringHandle.DangerousGetHandle(), }; if (buffers[0].pvBuffer == IntPtr.Zero) { buffers[0].cbBuffer = 0; } buffers[1] = new Interop.NCrypt.NCryptBuffer { BufferType = Interop.NCrypt.BufferType.PkcsAlgOid, cbBuffer = pkcs12TripleDesOidBytes.Length, pvBuffer = (IntPtr)oidPtr, }; buffers[2] = new Interop.NCrypt.NCryptBuffer { BufferType = Interop.NCrypt.BufferType.PkcsAlgParam, cbBuffer = sizeof(Interop.NCrypt.PBE_PARAMS), pvBuffer = (IntPtr)(&pbeParams), }; Interop.NCrypt.NCryptBufferDesc desc = new Interop.NCrypt.NCryptBufferDesc { cBuffers = 3, pBuffers = (IntPtr)buffers, ulVersion = 0, }; Span <byte> empty = default; ErrorCode errorCode = Interop.NCrypt.NCryptExportKey( keyHandle, IntPtr.Zero, Interop.NCrypt.NCRYPT_PKCS8_PRIVATE_KEY_BLOB, ref desc, ref MemoryMarshal.GetReference(empty), 0, out int numBytesNeeded, 0); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } allocated = null; if (allocate) { allocated = new byte[numBytesNeeded]; destination = allocated; } else if (numBytesNeeded > destination.Length) { bytesWritten = 0; return(false); } errorCode = Interop.NCrypt.NCryptExportKey( keyHandle, IntPtr.Zero, Interop.NCrypt.NCRYPT_PKCS8_PRIVATE_KEY_BLOB, ref desc, ref MemoryMarshal.GetReference(destination), destination.Length, out numBytesNeeded, 0); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } if (allocate && numBytesNeeded != destination.Length) { byte[] trimmed = new byte[numBytesNeeded]; destination.Slice(0, numBytesNeeded).CopyTo(trimmed); Array.Clear(allocated !, 0, numBytesNeeded); allocated = trimmed; } bytesWritten = numBytesNeeded; return(true); } } }
public RandomNumberGenerator(string rngName) { Check.NotNullOrWhiteSpace(nameof(rngName), rngName); this.randomNumberGenerator = System.Security.Cryptography.RandomNumberGenerator.Create(rngName); }
public HMACSHA1() : this(RandomNumberGenerator.GetBytes(BlockSize)) { }
public NerdyRandomNumberGenerator() { this.randomNumberGenerator = System.Security.Cryptography.RandomNumberGenerator.Create(); }
public NerdyRandomNumberGenerator(string rngName) { Check.ArgNotWhiteSpace(rngName, nameof(rngName)); this.randomNumberGenerator = System.Security.Cryptography.RandomNumberGenerator.Create(rngName); }
public static int PadBlock(ReadOnlySpan <byte> block, Span <byte> destination, int paddingSizeInBytes, PaddingMode paddingMode) { int count = block.Length; int paddingRemainder = count % paddingSizeInBytes; int padBytes = paddingSizeInBytes - paddingRemainder; switch (paddingMode) { case PaddingMode.None when(paddingRemainder != 0): throw new CryptographicException(SR.Cryptography_PartialBlock); case PaddingMode.None: if (destination.Length < count) { throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); } block.CopyTo(destination); return(count); // ANSI padding fills the blocks with zeros and adds the total number of padding bytes as // the last pad byte, adding an extra block if the last block is complete. // // xx 00 00 00 00 00 00 07 case PaddingMode.ANSIX923: int ansiSize = count + padBytes; if (destination.Length < ansiSize) { throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); } block.CopyTo(destination); destination.Slice(count, padBytes - 1).Clear(); destination[count + padBytes - 1] = (byte)padBytes; return(ansiSize); // ISO padding fills the blocks up with random bytes and adds the total number of padding // bytes as the last pad byte, adding an extra block if the last block is complete. // // xx rr rr rr rr rr rr 07 case PaddingMode.ISO10126: int isoSize = count + padBytes; if (destination.Length < isoSize) { throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); } block.CopyTo(destination); RandomNumberGenerator.Fill(destination.Slice(count, padBytes - 1)); destination[count + padBytes - 1] = (byte)padBytes; return(isoSize); // PKCS padding fills the blocks up with bytes containing the total number of padding bytes // used, adding an extra block if the last block is complete. // // xx xx 06 06 06 06 06 06 case PaddingMode.PKCS7: int pkcsSize = count + padBytes; if (destination.Length < pkcsSize) { throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); } block.CopyTo(destination); destination.Slice(count, padBytes).Fill((byte)padBytes); return(pkcsSize); // Zeros padding fills the last partial block with zeros, and does not add a new block to // the end if the last block is already complete. // // xx 00 00 00 00 00 00 00 case PaddingMode.Zeros: if (padBytes == paddingSizeInBytes) { padBytes = 0; } int zeroSize = count + padBytes; if (destination.Length < zeroSize) { throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); } block.CopyTo(destination); destination.Slice(count, padBytes).Clear(); return(zeroSize); default: throw new CryptographicException(SR.Cryptography_UnknownPaddingMode); } }
public BoxMullerCrypto() { rand = System.Security.Cryptography.RandomNumberGenerator.Create(); random = new byte[4]; }
public override void GenerateIV() { IV = RandomNumberGenerator.GetBytes(BlockSize / BitsPerByte); }
public Random() { rng = SSC.RandomNumberGenerator.Create(); }
public sealed override void GenerateKey() { Key = RandomNumberGenerator.GetBytes(KeySize / BitsPerByte); }
/** * Return a random AHAddress initialized from the given rng */ public AHAddress(RandomNumberGenerator rng) { byte[] buffer = new byte[MemSize]; rng.GetBytes(buffer); SetClass(buffer, this.Class); _buffer = MemBlock.Reference(buffer, 0, MemSize); }
void IDisposable.Dispose() { lock(_disposeGuard) { _randomNumberGenerator = null; } }
public void Dispose() { lock(this) // Just in case two threads try to dispose me at the same time? Whatev. ;-) { if (RNG != null) { try { RNG.Dispose(); } catch { } RNG = null; } if (HashWrappers != null) { try { foreach(HashAlgorithmWrapper hashWrapper in HashWrappers) { try { hashWrapper.Dispose(); } catch { } } } catch { } HashWrappers = null; } } }
/// <summary> /// Initializes a new instance of the <see cref="SHA2CryptoProvider" /> class. /// </summary> /// <param name="saltByteSize">The salt size. Defaults to 64.</param> public SHA2CryptoProvider(int saltByteSize = 64) { this.saltByteSize = saltByteSize; this.rng = new RNGCryptoServiceProvider(); this.log = LogManager.GetLogger("Sentinel.OAuth.SHA2CryptoProvider"); }