/// <summary> /// Loads a protected private key. /// </summary> /// <param name="address">The address of the protected private key.</param> /// <param name="kdf">A key derivation function to derive a symmetric key to decrypt /// a <see cref="PrivateKey"/>.</param> /// <param name="mac">MAC digest to check if a derived key is correct or not.</param> /// <param name="cipher">A symmetric cipher to decrypt a <see cref="PrivateKey"/>.</param> /// <param name="ciphertext">An encrypted <see cref="PrivateKey"/>.</param> public ProtectedPrivateKey( Address address, IKdf kdf, ImmutableArray <byte> mac, ICipher cipher, ImmutableArray <byte> ciphertext ) { Address = address; Kdf = kdf; Mac = mac; Cipher = cipher; Ciphertext = ciphertext; }
/// <summary> /// Loads a protected private key. /// </summary> /// <param name="address">The address of the protected private key.</param> /// <param name="kdf">A key derivation function to derive a symmetric key to decrypt /// a <see cref="PrivateKey"/>.</param> /// <param name="mac">MAC digest to check if a derived key is correct or not.</param> /// <param name="cipher">A symmetric cipher to decrypt a <see cref="PrivateKey"/>.</param> /// <param name="ciphertext">An encrypted <see cref="PrivateKey"/>.</param> public ProtectedPrivateKey( Address address, IKdf kdf, byte[] mac, ICipher cipher, byte[] ciphertext ) : this( address, kdf, ImmutableArray.Create(mac), cipher, ImmutableArray.Create(ciphertext) ) { }
public static Result <InvalidDataException> Encrypt(Stream input, Stream output, string password, IKdf kdf, ICipher cipher) { var key = kdf.Derive(password.ToUtf8Bytes(), cipher.RequiredKeyLen); try { var iv = Random.Bytes(32); var props = kdf.Properties; props["cipher"] = cipher.CipherName; props["iv"] = iv.ToBase64(); var propsBytes = JsonConvert.SerializeObject(props).ToUtf8Bytes(); var checksum = Sha256(propsBytes); var checksumDict = new Dictionary <string, object> { ["algo"] = "sha256", ["checksum"] = checksum.ToBase64(), }; var checksumBytes = JsonConvert.SerializeObject(checksumDict).ToUtf8Bytes(); output.Write(MagicHeader); output.Write(propsBytes); output.Write(checksumBytes); cipher.Encrypt(input, output, key, iv); } finally { Array.Clear(key, 0, key.Length); } return(Result <InvalidDataException> .Success); }