Exemplo n.º 1
0
        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));
        }
Exemplo n.º 2
0
        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;
            }
        }
Exemplo n.º 3
0
        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);
        }
Exemplo n.º 4
0
        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));
        }
Exemplo n.º 5
0
        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);
            }
Exemplo n.º 7
0
        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;
            }
        }
Exemplo n.º 8
0
 private async Task RunRefreshAsync()
 {
     if (_logger.IsTrace)
     {
         _logger.Trace("Running refresh process.");
     }
     var randomId = _cryptoRandom.GenerateRandomBytes(64);
     await _nodesLocator.LocateNodesAsync(randomId);
 }
Exemplo n.º 9
0
 private async Task RunRefreshAsync(CancellationToken cancellationToken)
 {
     if (_logger.IsTrace)
     {
         _logger.Trace("Running refresh process.");
     }
     byte[] randomId = _cryptoRandom.GenerateRandomBytes(64);
     await _nodesLocator.LocateNodesAsync(randomId, cancellationToken);
 }
Exemplo n.º 10
0
        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));
        }
Exemplo n.º 11
0
 public PrivateKey Generate()
 {
     do
     {
         var bytes = _cryptoRandom.GenerateRandomBytes(32);
         if (Proxy.VerifyPrivateKey(bytes))
         {
             return(new PrivateKey(bytes));
         }
     } while (true);
 }
Exemplo n.º 12
0
 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));
     }
 }
Exemplo n.º 13
0
        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);
        }
Exemplo n.º 14
0
        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;
        }
Exemplo n.º 15
0
        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);
        }
Exemplo n.º 16
0
        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;
        }
Exemplo n.º 17
0
#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;
        }
Exemplo n.º 18
0
 public PrivateKeyProvider(ICryptoRandom cryptoRandom)
 {
     PrivateKey = new PrivateKey(cryptoRandom.GenerateRandomBytes(32));
 }
Exemplo n.º 19
0
        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);
        }
Exemplo n.º 20
0
 public PrivateKeyBuilder()
 {
     byte[] bytes = CryptoRandom.GenerateRandomBytes(32);
     TestObject = new PrivateKey(bytes);
 }
Exemplo n.º 21
0
 public AddressBuilder()
 {
     byte[] bytes = CryptoRandom.GenerateRandomBytes(20);
     TestObjectInternal = new Address(bytes);
 }
Exemplo n.º 22
0
 public byte[] Pad(byte[] message)
 {
     byte[] padding = _cryptoRandom.GenerateRandomBytes(100 + _cryptoRandom.NextInt(201));
     return(Bytes.Concat(message, padding));
 }
Exemplo n.º 23
0
        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);
        }