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