public (PrivateKey PrivateKey, Result Result) GenerateKey(SecureString password) { var privateKey = new PrivateKey(_cryptoRandom.GenerateRandomBytes(32)); var result = StoreKey(privateKey, password); return(result.ResultType == ResultType.Success ? (privateKey, result) : (null, result)); }
public byte[] Encrypt(PublicKey recipientPublicKey, byte[] plaintext, byte[] macData) { byte[] iv = _cryptoRandom.GenerateRandomBytes(KeySize / 8); PrivateKey ephemeralPrivateKey = new PrivateKey(_cryptoRandom.GenerateRandomBytes(32)); ECPublicKeyParameters publicKeyParameters = BouncyCrypto.WrapPublicKey(recipientPublicKey); ECPrivateKeyParameters ephemeralPrivateKeyParameters = BouncyCrypto.WrapPrivateKey(ephemeralPrivateKey); EthereumIesEngine iesEngine = MakeIesEngine(true, publicKeyParameters, ephemeralPrivateKeyParameters, iv); try { byte[] cipher = iesEngine.ProcessBlock(plaintext, 0, plaintext.Length, macData); MemoryStream memoryStream = new MemoryStream(); memoryStream.Write(ephemeralPrivateKey.PublicKey.PrefixedBytes, 0, ephemeralPrivateKey.PublicKey.PrefixedBytes.Length); memoryStream.Write(iv, 0, iv.Length); memoryStream.Write(cipher, 0, cipher.Length); return(memoryStream.ToArray()); } catch (InvalidCipherTextException) { throw; } catch (IOException) { throw; } }
public Packet Auth(PublicKey remoteNodeId, EncryptionHandshake handshake) { handshake.RemoteNodeId = remoteNodeId; handshake.InitiatorNonce = _cryptoRandom.GenerateRandomBytes(32); handshake.EphemeralPrivateKey = _ephemeralGenerator.Generate(); byte[] staticSharedSecret = Proxy.EcdhSerialized(remoteNodeId.Bytes, _privateKey.KeyBytes); byte[] forSigning = staticSharedSecret.Xor(handshake.InitiatorNonce); AuthEip8Message authMessage = new AuthEip8Message(); authMessage.Nonce = handshake.InitiatorNonce; authMessage.PublicKey = _privateKey.PublicKey; authMessage.Signature = _ecdsa.Sign(handshake.EphemeralPrivateKey, new Keccak(forSigning)); byte[] authData = _messageSerializationService.Serialize(authMessage); int size = authData.Length + 32 + 16 + 65; // data + MAC + IV + pub byte[] sizeBytes = size.ToBigEndianByteArray().Slice(2, 2); byte[] packetData = _eciesCipher.Encrypt( remoteNodeId, authData, sizeBytes); handshake.AuthPacket = new Packet(Bytes.Concat(sizeBytes, packetData)); return(handshake.AuthPacket); }
public Result StoreKey(PrivateKey key, SecureString password) { var salt = _cryptoRandom.GenerateRandomBytes(32); var passBytes = password.ToByteArray(_keyStoreEncoding); var derivedKey = SCrypt.ComputeDerivedKey(passBytes, salt, _config.KdfparamsN, _config.KdfparamsR, _config.KdfparamsP, null, _config.KdfparamsDklen); var encryptKey = Keccak.Compute(derivedKey.Take(16).ToArray()).Bytes.Take(16).ToArray(); var encryptContent = key.KeyBytes; var iv = _cryptoRandom.GenerateRandomBytes(_config.IVSize); var cipher = _symmetricEncrypter.Encrypt(encryptContent, encryptKey, iv, _config.Cipher); if (cipher == null) { return(Result.Fail("Error during encryption")); } var mac = Keccak.Compute(derivedKey.Skip(_config.KdfparamsDklen - 16).Take(16).Concat(cipher).ToArray()).Bytes; var address = key.Address.ToString(); var keyStoreItem = new KeyStoreItem { Address = address, Crypto = new Crypto { Cipher = _config.Cipher, CipherText = cipher.ToHexString(true), CipherParams = new CipherParams { IV = iv.ToHexString(true) }, KDF = _config.Kdf, KDFParams = new KdfParams { DkLen = _config.KdfparamsDklen, N = _config.KdfparamsN, P = _config.KdfparamsP, R = _config.KdfparamsR, Salt = salt.ToHexString(true) }, MAC = mac.ToHexString(true), Version = CryptoVersion }, Id = address, Version = Version }; var serializedKey = _jsonSerializer.Serialize(keyStoreItem); if (serializedKey == null) { return(Result.Fail("Error during key serialization")); } return(PersistKey(address, serializedKey)); }
public Result StoreKey(PrivateKey key, SecureString password) { if (!password.IsReadOnly()) { throw new InvalidOperationException("Cannot work with password that is not readonly"); } var salt = _cryptoRandom.GenerateRandomBytes(32); var passBytes = password.ToByteArray(_keyStoreEncoding); var derivedKey = SCrypt.ComputeDerivedKey(passBytes, salt, _config.KdfparamsN, _config.KdfparamsR, _config.KdfparamsP, null, _config.KdfparamsDklen); var encryptKey = Keccak.Compute(derivedKey.Take(16).ToArray()).Bytes.Take(16).ToArray(); var encryptContent = key.KeyBytes; var iv = _cryptoRandom.GenerateRandomBytes(_config.IVSize); var cipher = _symmetricEncrypter.Encrypt(encryptContent, encryptKey, iv, _config.Cipher); if (cipher == null) { return(Result.Fail("Error during encryption")); } var mac = Keccak.Compute(derivedKey.Skip(_config.KdfparamsDklen - 16).Take(16).Concat(cipher).ToArray()).Bytes; string addressString = key.Address.ToString(false, false); var keyStoreItem = new KeyStoreItem { Address = addressString, Crypto = new Crypto { Cipher = _config.Cipher, CipherText = cipher.ToHexString(false), CipherParams = new CipherParams { IV = iv.ToHexString(false) }, KDF = _config.Kdf, KDFParams = new KdfParams { DkLen = _config.KdfparamsDklen, N = _config.KdfparamsN, P = _config.KdfparamsP, R = _config.KdfparamsR, Salt = salt.ToHexString(false) }, MAC = mac.ToHexString(false), }, Id = addressString, Version = Version }; return(StoreKey(key.Address, keyStoreItem)); }
public BenchmarkTestRandom(ICryptoRandom trueRandom, int mod) { responses = new byte[6][]; _mod = mod; _i = -1; // WARN: order reflects the internal implementation of the service (tests may fail after any refactoring) responses[0] = NetTestVectors.NonceA; responses[1] = NetTestVectors.EphemeralKeyA.KeyBytes; responses[2] = trueRandom.GenerateRandomBytes(100); responses[3] = NetTestVectors.NonceB; responses[4] = NetTestVectors.EphemeralKeyB.KeyBytes; responses[5] = trueRandom.GenerateRandomBytes(100); }
public byte[] Encrypt(PublicKey recipientPublicKey, byte[] plaintext, byte[] macData) { byte[] iv = _cryptoRandom.GenerateRandomBytes(KeySize / 8); PrivateKey ephemeralPrivateKey = _keyGenerator.Generate(); IIesEngine iesEngine = MakeIesEngine(true, recipientPublicKey, ephemeralPrivateKey, iv); try { byte[] cipher = iesEngine.ProcessBlock(plaintext, 0, plaintext.Length, macData); MemoryStream memoryStream = new MemoryStream(); memoryStream.Write(ephemeralPrivateKey.PublicKey.PrefixedBytes, 0, ephemeralPrivateKey.PublicKey.PrefixedBytes.Length); memoryStream.Write(iv, 0, iv.Length); memoryStream.Write(cipher, 0, cipher.Length); return(memoryStream.ToArray()); } catch (InvalidCipherTextException) { throw; } catch (IOException) { throw; } }
private async Task RunRefreshAsync() { if (_logger.IsTrace) { _logger.Trace("Running refresh process."); } var randomId = _cryptoRandom.GenerateRandomBytes(64); await _nodesLocator.LocateNodesAsync(randomId); }
private async Task RunRefreshAsync(CancellationToken cancellationToken) { if (_logger.IsTrace) { _logger.Trace("Running refresh process."); } byte[] randomId = _cryptoRandom.GenerateRandomBytes(64); await _nodesLocator.LocateNodesAsync(randomId, cancellationToken); }
public void Sign_and_recover() { EthereumSigner ethereumSigner = new EthereumSigner(OlympicSpecProvider.Instance, NullLogManager.Instance); Keccak message = Keccak.Compute("Test message"); PrivateKey privateKey = new PrivateKey(_cryptoRandom.GenerateRandomBytes(32)); Signature signature = ethereumSigner.Sign(privateKey, message); Assert.AreEqual(privateKey.Address, ethereumSigner.RecoverAddress(signature, message)); }
public PrivateKey Generate() { do { var bytes = _cryptoRandom.GenerateRandomBytes(32); if (Proxy.VerifyPrivateKey(bytes)) { return(new PrivateKey(bytes)); } } while (true); }
private void InitializeRandom(bool preEip8Format = false) { // WARN: order reflects the internal implementation of the service (tests may fail after any refactoring) if (preEip8Format) { _testRandom.EnqueueRandomBytes(NetTestVectors.NonceA, NetTestVectors.EphemeralKeyA.KeyBytes, NetTestVectors.NonceB, NetTestVectors.EphemeralKeyB.KeyBytes); } else { _testRandom.EnqueueRandomBytes(NetTestVectors.NonceA, NetTestVectors.EphemeralKeyA.KeyBytes, _trueCryptoRandom.GenerateRandomBytes(100), NetTestVectors.NonceB, NetTestVectors.EphemeralKeyB.KeyBytes, _trueCryptoRandom.GenerateRandomBytes(100)); } }
private SecureString CreateNodeKeyPassword(int size) { char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray(); byte[] data = _cryptoRandom.GenerateRandomBytes(size); SecureString secureString = new SecureString(); for (int i = 0; i < data.Length; i++) { secureString.AppendChar(chars[data[i] % chars.Length]); } secureString.MakeReadOnly(); return(secureString); }
public PrivateKeyProvider(ICryptoRandom cryptoRandom) { PrivateKey privateKey = null; do { var bytes = cryptoRandom.GenerateRandomBytes(32); if (Proxy.VerifyPrivateKey(bytes)) { privateKey = new PrivateKey(bytes); } } while (privateKey == null); PrivateKey = privateKey; }
public PrivateKey Generate() { PrivateKey privateKey = null; do { var bytes = _cryptoRandom.GenerateRandomBytes(32); if (Proxy.VerifyPrivateKey(bytes)) { privateKey = new PrivateKey(bytes); } } while (privateKey == null); return(privateKey); }
public void Initialize() { _configurationProvider = new JsonConfigProvider(); _keyStoreDir = _configurationProvider.GetConfig <KeystoreConfig>().KeyStoreDirectory; if (!Directory.Exists(_keyStoreDir)) { Directory.CreateDirectory(_keyStoreDir); } ILogManager logManager = NullLogManager.Instance; _serializer = new JsonSerializer(logManager); _cryptoRandom = new CryptoRandom(); _store = new FileKeyStore(_configurationProvider, _serializer, new AesEncrypter(_configurationProvider, logManager), _cryptoRandom, logManager); var testsContent = File.ReadAllText("basic_tests.json"); _testsModel = _serializer.Deserialize <KeyStoreTestsModel>(testsContent); _testAddress = new PrivateKey(_cryptoRandom.GenerateRandomBytes(32)).Address; }
#pragma warning disable CA1416 private void Protect(byte[] data) { _entropy = _random.GenerateRandomBytes(_random.NextInt(EntropyMaxLength - EntropyMinLength) + EntropyMinLength); _encryptedData = Protect(data, _entropy, DataProtectionScope.CurrentUser); _timestamp = _timestamper.UtcNow; }
public PrivateKeyProvider(ICryptoRandom cryptoRandom) { PrivateKey = new PrivateKey(cryptoRandom.GenerateRandomBytes(32)); }
public async Task <Keccak?> MakeAsync(Keccak assetId, uint units, UInt256 value, Address address, UInt256?gasPrice = null) { if (!_wallet.IsUnlocked(address)) { if (_logger.IsWarn) { _logger.Warn($"Account: '{address}' is locked, can't make a deposit."); } return(null); } DataAsset?dataAsset = _dataAssetService.GetDiscovered(assetId); if (dataAsset is null) { if (_logger.IsWarn) { _logger.Warn($"Available data asset: '{assetId}' was not found."); } return(null); } if (!_dataAssetService.IsAvailable(dataAsset)) { if (_logger.IsWarn) { _logger.Warn($"Data asset: '{assetId}' is unavailable, state: {dataAsset.State}."); } return(null); } if (dataAsset.KycRequired && !await _kycVerifier.IsVerifiedAsync(assetId, address)) { return(null); } Address providerAddress = dataAsset.Provider.Address; INdmPeer?provider = _providerService.GetPeer(providerAddress); if (provider is null) { if (_logger.IsWarn) { _logger.Warn($"Provider nodes were not found for address: '{providerAddress}'."); } return(null); } if (dataAsset.MinUnits > units || dataAsset.MaxUnits < units) { if (_logger.IsWarn) { _logger.Warn($"Invalid data request units: '{units}', min: '{dataAsset.MinUnits}', max: '{dataAsset.MaxUnits}'."); } return(null); } UInt256 unitsValue = units * dataAsset.UnitPrice; if (units * dataAsset.UnitPrice != value) { if (_logger.IsWarn) { _logger.Warn($"Invalid data request value: '{value}', while it should be: '{unitsValue}'."); } return(null); } uint now = (uint)_timestamper.EpochSeconds; uint expiryTime = now + (uint)dataAsset.Rules.Expiry.Value; expiryTime += dataAsset.UnitType == DataAssetUnitType.Unit ? 0 : units; byte[] pepper = _cryptoRandom.GenerateRandomBytes(16); byte[] abiHash = _abiEncoder.Encode(AbiEncodingStyle.Packed, _depositAbiSig, assetId.Bytes, units, value, expiryTime, pepper, dataAsset.Provider.Address, address); Keccak depositId = Keccak.Compute(abiHash); Deposit deposit = new Deposit(depositId, units, expiryTime, value); DepositDetails depositDetails = new DepositDetails(deposit, dataAsset, address, pepper, now, Enumerable.Empty <TransactionInfo>(), 0, requiredConfirmations: _requiredBlockConfirmations); UInt256 gasPriceValue = gasPrice is null || gasPrice.Value == 0 ? await _gasPriceService.GetCurrentAsync() : gasPrice.Value; await _depositRepository.AddAsync(depositDetails); Keccak?transactionHash = null; if (_logger.IsInfo) { _logger.Info($"Created a deposit with id: '{depositId}', for data asset: '{assetId}', address: '{address}'."); } if (_disableSendingDepositTransaction) { if (_logger.IsWarn) { _logger.Warn("*** NDM sending deposit transaction is disabled ***"); } } else { transactionHash = await _depositService.MakeDepositAsync(address, deposit, gasPriceValue); } if (transactionHash == null) { if (_logger.IsWarn) { _logger.Warn($"Failed to make a deposit with for data asset: '{assetId}', address: '{address}', gas price: {gasPriceValue} wei."); } return(null); } if (_logger.IsInfo) { _logger.Info($"Sent a deposit with id: '{depositId}', transaction hash: '{transactionHash}' for data asset: '{assetId}', address: '{address}', gas price: {gasPriceValue} wei."); } depositDetails.AddTransaction(TransactionInfo.Default(transactionHash, deposit.Value, gasPriceValue, _depositService.GasLimit, now)); await _depositRepository.UpdateAsync(depositDetails); return(depositId); }
public PrivateKeyBuilder() { byte[] bytes = CryptoRandom.GenerateRandomBytes(32); TestObject = new PrivateKey(bytes); }
public AddressBuilder() { byte[] bytes = CryptoRandom.GenerateRandomBytes(20); TestObjectInternal = new Address(bytes); }
public byte[] Pad(byte[] message) { byte[] padding = _cryptoRandom.GenerateRandomBytes(100 + _cryptoRandom.NextInt(201)); return(Bytes.Concat(message, padding)); }
public async Task <Keccak> MakeAsync(Keccak assetId, uint units, UInt256 value, Address address) { if (!_wallet.IsUnlocked(address)) { if (_logger.IsWarn) { _logger.Warn($"Account: '{address}' is locked, can't make a deposit."); } return(null); } var dataAsset = _dataAssetService.GetDiscovered(assetId); if (dataAsset is null) { if (_logger.IsWarn) { _logger.Warn($"Available data asset: '{assetId}' was not found."); } return(null); } if (!_dataAssetService.IsAvailable(dataAsset)) { if (_logger.IsWarn) { _logger.Warn($"Data asset: '{assetId}' is unavailable, state: {dataAsset.State}."); } return(null); } if (dataAsset.KycRequired && !(await _kycVerifier.IsVerifiedAsync(assetId, address))) { return(null); } var providerAddress = dataAsset.Provider.Address; var provider = _providerService.GetPeer(providerAddress); if (provider is null) { if (_logger.IsWarn) { _logger.Warn($"Provider nodes were not found for address: '{providerAddress}'."); } return(null); } if (dataAsset.MinUnits > units || dataAsset.MaxUnits < units) { if (_logger.IsWarn) { _logger.Warn($"Invalid data request units: '{units}', min: '{dataAsset.MinUnits}', max: '{dataAsset.MaxUnits}'."); } return(null); } var unitsValue = units * dataAsset.UnitPrice; if (units * dataAsset.UnitPrice != value) { if (_logger.IsWarn) { _logger.Warn($"Invalid data request value: '{value}', while it should be: '{unitsValue}'."); } return(null); } var now = (uint)_timestamper.EpochSeconds; var expiryTime = now + (uint)dataAsset.Rules.Expiry.Value; expiryTime += dataAsset.UnitType == DataAssetUnitType.Unit ? 0 : units; var pepper = _cryptoRandom.GenerateRandomBytes(16); var abiHash = _abiEncoder.Encode(AbiEncodingStyle.Packed, _depositAbiSig, assetId.Bytes, units, value, expiryTime, pepper, dataAsset.Provider.Address, address); var depositId = Keccak.Compute(abiHash); var deposit = new Deposit(depositId, units, expiryTime, value); var depositDetails = new DepositDetails(deposit, dataAsset, address, pepper, now, null, requiredConfirmations: _requiredBlockConfirmations); await _depositRepository.AddAsync(depositDetails); if (_logger.IsInfo) { _logger.Info($"Created a deposit with id: '{depositId}', for data asset: '{assetId}', address: '{address}'."); } var transactionHash = await _depositService.MakeDepositAsync(address, deposit); if (_logger.IsInfo) { _logger.Info($"Sent a deposit with id: '{depositId}', transaction hash: '{transactionHash}' for data asset: '{assetId}', address: '{address}'."); } depositDetails.SetTransactionHash(transactionHash); await _depositRepository.UpdateAsync(depositDetails); return(depositId); }