Skip to main content

heika_core/
key.rs

1//! 鍵。
2
3use alloc::borrow::ToOwned;
4use alloc::string::String;
5use core::fmt;
6use core::str::FromStr;
7
8use rand_core::CryptoRng;
9use zeroize::Zeroizing;
10
11use crate::ed25519;
12use crate::hex::{self, ParseHexError};
13use crate::signature::Signature;
14
15/// Ed25519 の公開鍵。catapult の `Key` と同じく、曲線上の点かどうかは確かめず32バイトとして扱う。
16/// 文字列にするときは、Symbol の慣習に合わせて大文字の16進にする。
17#[derive(Clone, Copy, PartialEq, Eq, Hash)]
18pub struct PublicKey(pub [u8; 32]);
19
20impl PublicKey {
21    /// 秘密鍵から導出する。catapult の `crypto/KeyPair.cpp` と同じく、RFC 8032 の Ed25519(SHA-512)。
22    pub fn from_private_key(private_key: &PrivateKey) -> Self {
23        Self(ed25519::public_key(&private_key.0))
24    }
25
26    /// 署名を検証する。catapult の `crypto::Verify` と同じものだけを受け付ける。
27    ///
28    /// catapult と同じく、メッセージはいくつかに分けたまま渡せる。
29    pub fn verify(&self, message: &[&[u8]], signature: &Signature) -> bool {
30        ed25519::verify(&self.0, message, &signature.0)
31    }
32}
33
34impl fmt::Display for PublicKey {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        f.write_str(&hex::encode(&self.0))
37    }
38}
39
40impl fmt::Debug for PublicKey {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        write!(f, "PublicKey({self})")
43    }
44}
45
46impl FromStr for PublicKey {
47    type Err = ParseHexError;
48
49    fn from_str(text: &str) -> Result<Self, Self::Err> {
50        hex::decode(text).map(Self)
51    }
52}
53
54/// Ed25519 の秘密鍵(RFC 8032 のシード)。使い終わるとメモリを0で上書きする。
55/// 中身が表示されたり、読むのにかかる時間から漏れたりしないように、
56/// `Display` は持たず、16進との変換は定数時間で行う。
57pub struct PrivateKey(Zeroizing<[u8; 32]>);
58
59impl PrivateKey {
60    /// 32バイトのシードから作る。渡した側の配列は呼び出し側で消す。
61    pub fn from_bytes(bytes: &[u8; 32]) -> Self {
62        Self(Zeroizing::new(*bytes))
63    }
64
65    /// 渡された暗号用の乱数で作る。
66    pub fn generate_with_rng<R: CryptoRng + ?Sized>(rng: &mut R) -> Self {
67        let mut bytes = Zeroizing::new([0; 32]);
68        rng.fill_bytes(&mut *bytes);
69        Self(bytes)
70    }
71
72    /// OS の乱数で作る。
73    #[cfg(feature = "getrandom")]
74    pub fn generate() -> Result<Self, getrandom::Error> {
75        let mut bytes = Zeroizing::new([0; 32]);
76        getrandom::fill(&mut *bytes)?;
77        Ok(Self(bytes))
78    }
79
80    /// 32バイトのシードとして見る。PEM などに書き出すつもりで呼ぶときだけ使う。
81    pub fn as_bytes(&self) -> &[u8; 32] {
82        &self.0
83    }
84
85    /// 大文字の16進にする。表示するつもりで呼ぶときだけ使う。
86    pub fn to_hex(&self) -> Zeroizing<String> {
87        let mut buffer = Zeroizing::new([0; 64]);
88        let text = base16ct::upper::encode_str(&*self.0, &mut *buffer)
89            .expect("64 bytes hold 32 bytes of hex");
90        Zeroizing::new(text.to_owned())
91    }
92
93    /// RFC 8032 の Ed25519 で署名する。catapult の `crypto::Sign` と同じ。
94    ///
95    /// catapult と同じく、メッセージはいくつかに分けたまま渡せる。
96    pub fn sign(&self, message: &[&[u8]]) -> Signature {
97        Signature(ed25519::sign(&self.0, message))
98    }
99}
100
101impl fmt::Debug for PrivateKey {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        f.write_str("PrivateKey(..)")
104    }
105}
106
107impl FromStr for PrivateKey {
108    type Err = ParsePrivateKeyError;
109
110    /// 大文字も小文字も受け付ける。
111    fn from_str(text: &str) -> Result<Self, Self::Err> {
112        // base16ct は短い入力でも読めた分だけ返すので、長さは先に確かめる
113        if text.len() != 64 {
114            return Err(ParsePrivateKeyError::InvalidLength);
115        }
116        let mut bytes = Zeroizing::new([0; 32]);
117        base16ct::mixed::decode(text, &mut *bytes)
118            .map_err(|_| ParsePrivateKeyError::InvalidCharacter)?;
119        Ok(Self(bytes))
120    }
121}
122
123/// 秘密鍵が読めなかった理由。秘密鍵の一部を漏らさないように、どこの何が悪かったかは含めない。
124#[derive(Debug, Clone, PartialEq, Eq)]
125pub enum ParsePrivateKeyError {
126    /// 16進で64文字になっていない
127    InvalidLength,
128    /// 16進の数字ではない文字が含まれている
129    InvalidCharacter,
130}
131
132impl fmt::Display for ParsePrivateKeyError {
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        match self {
135            Self::InvalidLength => f.write_str("秘密鍵は16進で64文字のはずです"),
136            Self::InvalidCharacter => f.write_str("秘密鍵に16進の数字ではない文字が含まれています"),
137        }
138    }
139}
140
141impl core::error::Error for ParsePrivateKeyError {}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    const UPPER: &str = "79AF37ED4A98EF6C79F8C26992EA55ECEF74865827A1BBB602374C8F4F13DA07";
148
149    #[test]
150    fn round_trips_through_upper_case_hex() {
151        let key: PublicKey = UPPER.parse().unwrap();
152        assert_eq!(key.0[..2], [0x79, 0xAF]);
153        assert_eq!(key.to_string(), UPPER);
154    }
155
156    #[test]
157    fn accepts_lower_case_and_displays_upper_case() {
158        let key: PublicKey = UPPER.to_lowercase().parse().unwrap();
159        assert_eq!(key.to_string(), UPPER);
160    }
161
162    #[test]
163    fn debug_shows_hex() {
164        let key: PublicKey = UPPER.parse().unwrap();
165        assert_eq!(format!("{key:?}"), format!("PublicKey({UPPER})"));
166    }
167
168    #[test]
169    fn rejects_a_short_key() {
170        assert_eq!(
171            UPPER[..62].parse::<PublicKey>(),
172            Err(ParseHexError::InvalidLength {
173                expected: 64,
174                actual: 62
175            })
176        );
177    }
178
179    // RFC 8032 の 7.1 節にある Ed25519 のテスト 1
180    const PRIVATE: &str = "9D61B19DEFFD5A60BA844AF492EC2CC44449C5697B326919703BAC031CAE7F60";
181
182    #[test]
183    fn private_key_round_trips_through_upper_case_hex() {
184        let key: PrivateKey = PRIVATE.parse().unwrap();
185        assert_eq!(*key.to_hex(), PRIVATE);
186    }
187
188    #[test]
189    fn private_key_accepts_lower_case_and_writes_upper_case() {
190        let key: PrivateKey = PRIVATE.to_lowercase().parse().unwrap();
191        assert_eq!(*key.to_hex(), PRIVATE);
192    }
193
194    #[test]
195    fn private_key_debug_hides_the_key() {
196        let key: PrivateKey = PRIVATE.parse().unwrap();
197        assert_eq!(format!("{key:?}"), "PrivateKey(..)");
198    }
199
200    #[test]
201    fn private_key_rejects_a_short_key() {
202        assert_eq!(
203            PRIVATE[..62].parse::<PrivateKey>().unwrap_err(),
204            ParsePrivateKeyError::InvalidLength
205        );
206    }
207
208    #[test]
209    fn private_key_error_does_not_reveal_the_key() {
210        let typo = format!("{}G", &PRIVATE[..63]);
211        let error = typo.parse::<PrivateKey>().unwrap_err();
212        assert_eq!(error, ParsePrivateKeyError::InvalidCharacter);
213        assert!(!error.to_string().contains('G'));
214    }
215
216    #[test]
217    fn private_key_rejects_non_ascii_without_panicking() {
218        // 「あ」は3バイトなので、バイト数では64になる
219        let text = format!("{}あ", &PRIVATE[..61]);
220        assert_eq!(
221            text.parse::<PrivateKey>().unwrap_err(),
222            ParsePrivateKeyError::InvalidCharacter
223        );
224    }
225
226    #[test]
227    fn derives_the_public_key_from_the_private_key() {
228        let key: PrivateKey = PRIVATE.parse().unwrap();
229        assert_eq!(
230            PublicKey::from_private_key(&key).to_string(),
231            "D75A980182B10AB7D54BFED3C964073A0EE172F3DAA62325AF021A68F707511A"
232        );
233    }
234
235    #[test]
236    fn private_key_from_bytes_keeps_the_bytes() {
237        let key = PrivateKey::from_bytes(&[0xAB; 32]);
238        assert_eq!(*key.to_hex(), "AB".repeat(32));
239    }
240
241    /// RFC 8032 の 7.1 節にある Ed25519 のテスト 1 から 3。秘密鍵、公開鍵、メッセージ、署名
242    const RFC_8032: [(&str, &str, &str, &str); 3] = [
243        (
244            PRIVATE,
245            "D75A980182B10AB7D54BFED3C964073A0EE172F3DAA62325AF021A68F707511A",
246            "",
247            "E5564300C360AC729086E2CC806E828A84877F1EB8E5D974D873E065224901555FB8821590A33BACC61E39701CF9B46BD25BF5F0595BBE24655141438E7A100B",
248        ),
249        (
250            "4CCD089B28FF96DA9DB6C346EC114E0F5B8A319F35ABA624DA8CF6ED4FB8A6FB",
251            "3D4017C3E843895A92B70AA74D1B7EBC9C982CCF2EC4968CC0CD55F12AF4660C",
252            "72",
253            "92A009A9F0D4CAB8720E820B5F642540A2B27B5416503F8FB3762223EBDB69DA085AC1E43E15996E458F3613D0F11D8C387B2EAEB4302AEEB00D291612BB0C00",
254        ),
255        (
256            "C5AA8DF43F9F837BEDB7442F31DCB7B166D38535076F094B85CE3A2E0B4458F7",
257            "FC51CD8E6218A1A38DA47ED00230F0580816ED13BA3303AC5DEB911548908025",
258            "AF82",
259            "6291D657DEEC24024827E69C3ABE01A30CE548A284743A445E3680D7DB5AC3AC18FF9B538D16F290AE67F760984DC6594A7C15E9716ED28DC027BECEEA1EC40A",
260        ),
261    ];
262
263    fn message(text: &str) -> Vec<u8> {
264        text.as_bytes()
265            .chunks(2)
266            .map(|pair| u8::from_str_radix(str::from_utf8(pair).unwrap(), 16).unwrap())
267            .collect()
268    }
269
270    #[test]
271    fn signs_like_rfc_8032() {
272        for (private_key, _, text, signature) in RFC_8032 {
273            let key: PrivateKey = private_key.parse().unwrap();
274            assert_eq!(key.sign(&[&message(text)]).to_string(), signature);
275        }
276    }
277
278    #[test]
279    fn verifies_rfc_8032_signatures() {
280        for (_, public_key, text, signature) in RFC_8032 {
281            let key: PublicKey = public_key.parse().unwrap();
282            let signature: Signature = signature.parse().unwrap();
283            assert!(key.verify(&[&message(text)], &signature));
284            assert!(!key.verify(&[&message(text), b"!"], &signature));
285        }
286    }
287
288    /// 決まったバイト列を返すだけの乱数。テストで鍵を固定するのに使う。
289    struct Replay<'a>(&'a [u8]);
290
291    impl rand_core::TryRng for Replay<'_> {
292        type Error = core::convert::Infallible;
293
294        fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
295            unimplemented!("only fill_bytes is used")
296        }
297
298        fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
299            unimplemented!("only fill_bytes is used")
300        }
301
302        fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
303            let (head, rest) = self.0.split_at(dst.len());
304            dst.copy_from_slice(head);
305            self.0 = rest;
306            Ok(())
307        }
308    }
309
310    impl rand_core::TryCryptoRng for Replay<'_> {}
311
312    #[test]
313    fn generates_from_the_given_rng() {
314        let bytes = crate::hex::decode::<32>(PRIVATE).unwrap();
315        let key = PrivateKey::generate_with_rng(&mut Replay(&bytes));
316        assert_eq!(*key.to_hex(), PRIVATE);
317    }
318
319    #[cfg(feature = "getrandom")]
320    #[test]
321    fn generates_different_keys_from_the_os() {
322        let first = PrivateKey::generate().unwrap();
323        let second = PrivateKey::generate().unwrap();
324        assert_ne!(*first.to_hex(), *second.to_hex());
325    }
326}