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, Serializer};
18use std::{fmt, ptr};
19
20#[derive(Clone, PartialEq, Eq, Deserialize)]
21pub struct Password(String);
22
23impl Serialize for Password {
24    fn serialize<S: Serializer>(
25        &self, serializer: S,
26    ) -> Result<S::Ok, S::Error> {
27        serializer.serialize_str("******")
28    }
29}
30
31impl fmt::Debug for Password {
32    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
33        write!(f, "Password(******)")
34    }
35}
36
37impl Password {
38    pub fn as_bytes(&self) -> &[u8] { self.0.as_bytes() }
39
40    pub fn as_str(&self) -> &str { self.0.as_str() }
41}
42
43// Custom drop impl to zero out memory.
44impl Drop for Password {
45    fn drop(&mut self) {
46        unsafe {
47            for byte_ref in self.0.as_mut_vec() {
48                ptr::write_volatile(byte_ref, 0)
49            }
50        }
51    }
52}
53
54impl From<String> for Password {
55    fn from(s: String) -> Password { Password(s) }
56}
57
58impl<'a> From<&'a str> for Password {
59    fn from(s: &'a str) -> Password { Password::from(String::from(s)) }
60}