cfxkey/password.rs
1// Copyright 2015-2019 Parity Technologies (UK) Ltd.
2// This file is part of Parity Ethereum.
3
4// Parity Ethereum is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Parity Ethereum is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
16
17use serde::{Deserialize, Serialize};
18use std::{fmt, ptr};
19
20#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
21pub struct Password(String);
22
23impl fmt::Debug for Password {
24 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
25 write!(f, "Password(******)")
26 }
27}
28
29impl Password {
30 pub fn as_bytes(&self) -> &[u8] { self.0.as_bytes() }
31
32 pub fn as_str(&self) -> &str { self.0.as_str() }
33}
34
35// Custom drop impl to zero out memory.
36impl Drop for Password {
37 fn drop(&mut self) {
38 unsafe {
39 for byte_ref in self.0.as_mut_vec() {
40 ptr::write_volatile(byte_ref, 0)
41 }
42 }
43 }
44}
45
46impl From<String> for Password {
47 fn from(s: String) -> Password { Password(s) }
48}
49
50impl<'a> From<&'a str> for Password {
51 fn from(s: &'a str) -> Password { Password::from(String::from(s)) }
52}