Skip to main content

heika_core/
hazmat.rs

1//! 使い方を誤ると鍵が漏れる、Ed25519 の中の部品(feature `hazmat`)。
2//!
3//! heika の署名と検証が使っているものを、そのまま出す。アダプター署名のような、RFC 8032 の決まりどおりでない署名を
4//! 組むときに使う。ここのものを組み合わせて作った署名でも、検証は [`crate::key::PublicKey::verify`](catapult と
5//! 同じ検証)で確かめること。
6//!
7//! 気をつけること:
8//! - 同じ秘密鍵で、違うメッセージに同じノンスを使うと、2つの署名から秘密鍵が求まる。ノンスは、メッセージと、
9//!   署名に仕込むものすべてから決めるか、乱数で作る
10//! - [`ExpandedKey::scalar`] は秘密鍵そのものと同じ。外に出さない
11//! - 受け取った点は [`decode_point`] で確かめる。小さい位数の成分が混ざった点を使うと、catapult の検証を通らない
12
13pub use curve25519_dalek;
14use curve25519_dalek::edwards::{CompressedEdwardsY, EdwardsPoint};
15use curve25519_dalek::scalar::Scalar;
16use curve25519_dalek::traits::IsIdentity;
17use zeroize::Zeroizing;
18
19use crate::ed25519;
20use crate::key::PrivateKey;
21
22/// 秘密鍵(RFC 8032 のシード)を SHA-512 で広げたもの
23pub struct ExpandedKey(ed25519::ExpandedKey);
24
25impl ExpandedKey {
26    pub fn new(key: &PrivateKey) -> Self {
27        Self(ed25519::ExpandedKey::new(key.as_bytes()))
28    }
29
30    /// 前半をクランプしたスカラー。署名の `s = r + h·a` の `a`
31    pub fn scalar(&self) -> &Scalar {
32        &self.0.scalar
33    }
34
35    /// 後半。RFC 8032 では、ノンスを `H(prefix ‖ M)` で決めるのに使う
36    pub fn prefix(&self) -> &[u8; 32] {
37        &self.0.prefix
38    }
39
40    /// 公開鍵の点。[`crate::key::PublicKey::from_private_key`] と同じもの
41    pub fn public_point(&self) -> EdwardsPoint {
42        EdwardsPoint::mul_base(&self.0.scalar)
43    }
44}
45
46/// 検証と同じハッシュ `h = H(R ‖ A ‖ M)`。`encoded_r` と `public_key` は圧縮した点のバイト列
47pub fn challenge(encoded_r: &[u8; 32], public_key: &[u8; 32], message: &[&[u8]]) -> Scalar {
48    ed25519::challenge(encoded_r, public_key, message)
49}
50
51/// 点に戻す。catapult が公開鍵に求めるのと同じく、正規形で、曲線上にあり、素数位数の部分群に入っている点だけを
52/// 受け付ける。単位元は弾かないので、要るなら呼ぶ側で弾く
53pub fn decode_point(bytes: &[u8; 32]) -> Option<EdwardsPoint> {
54    ed25519::decode(bytes)
55}
56
57/// 小さい位数の点(位数が 8 の約数の点)8 個を、圧縮したバイト列と位数の組で返す。
58///
59/// 並びは位数の小さい順で、同じ位数の中ではバイト列の小さい順。8 個は位数 8 の巡回群をなし、単位元
60/// `01 00…00` も含む。番号の振り方には決まったものがないので、点はバイト列で扱う。
61pub fn small_order_points() -> [([u8; 32], u8); 8] {
62    let mut points = curve25519_dalek::constants::EIGHT_TORSION.map(|point| {
63        let order = [1u8, 2, 4, 8]
64            .into_iter()
65            .find(|&order| (point * Scalar::from(order)).is_identity())
66            .expect("eight-torsion points have order dividing 8");
67        (point.compress().to_bytes(), order)
68    });
69    points.sort_by_key(|&(bytes, order)| (order, bytes));
70    points
71}
72
73/// 2 つの点を足す。どちらも正規形で曲線上にあればよく、素数位数の部分群に入っているかは問わない。
74/// 結果は正規形の圧縮したバイト列。どちらかが点に戻せなければ `None`。
75///
76/// 公開鍵に小さい位数の点(単位元を除く)を足すと、catapult の検証が部分群の外の公開鍵を弾くので、
77/// 誰も署名できない鍵になる。ただし、これは今の検証の決まりの下での話で、位数 8 を掛けてから比べる検証
78/// (ZIP-215 など)では、元の鍵の持ち主が署名できる。小さい位数の点そのものなら、誰でも署名できる。
79pub fn add_points(a: &[u8; 32], b: &[u8; 32]) -> Option<[u8; 32]> {
80    Some(
81        (decode_any_point(a)? + decode_any_point(b)?)
82            .compress()
83            .to_bytes(),
84    )
85}
86
87/// 点に戻す。[`decode_point`] と違い、素数位数の部分群に入っているかは問わず、正規形で曲線上にあれば受け付ける。
88/// 部分群の外の点を署名や鍵の交換に使うと、catapult とは違う結果になる
89pub fn decode_any_point(bytes: &[u8; 32]) -> Option<EdwardsPoint> {
90    if !ed25519::is_canonical(bytes) {
91        return None;
92    }
93    CompressedEdwardsY(*bytes).decompress()
94}
95
96/// SHA-512。部分を順に続けたもの
97pub fn sha512<'a>(parts: impl IntoIterator<Item = &'a [u8]>) -> Zeroizing<[u8; 64]> {
98    ed25519::sha512(parts)
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    use crate::key::PublicKey;
105
106    #[test]
107    fn rebuilds_the_rfc_8032_signature() {
108        // ここの部品で RFC 8032 のとおりに組むと、heika の署名と同じものになる
109        let key = PrivateKey::from_bytes(&[7; 32]);
110        let message: &[u8] = b"message";
111        let expanded = ExpandedKey::new(&key);
112        let public_key = PublicKey::from_private_key(&key);
113        assert_eq!(expanded.public_point().compress().to_bytes(), public_key.0);
114        let r = Scalar::from_bytes_mod_order_wide(&sha512([&expanded.prefix()[..], message]));
115        let encoded_r = EdwardsPoint::mul_base(&r).compress().to_bytes();
116        let s = r + challenge(&encoded_r, &public_key.0, &[message]) * expanded.scalar();
117        let mut signature = [0; 64];
118        signature[..32].copy_from_slice(&encoded_r);
119        signature[32..].copy_from_slice(s.as_bytes());
120        assert_eq!(signature, key.sign(&[message]).0);
121        assert!(decode_point(&public_key.0).is_some());
122    }
123
124    const IDENTITY: [u8; 32] = {
125        let mut bytes = [0; 32];
126        bytes[0] = 1;
127        bytes
128    };
129
130    #[test]
131    fn lists_the_eight_small_order_points() {
132        let points = small_order_points();
133        assert_eq!(points.map(|(_, order)| order), [1, 2, 4, 4, 8, 8, 8, 8]);
134        assert_eq!(points[0].0, IDENTITY);
135        // y = -1 が位数 2、y = 0 が位数 4
136        let mut minus_one = [0xFF; 32];
137        minus_one[0] = 0xEC;
138        minus_one[31] = 0x7F;
139        assert_eq!(points[1].0, minus_one);
140        assert_eq!(points[2].0, [0; 32]);
141        let mut zero_negative_x = [0; 32];
142        zero_negative_x[31] = 0x80;
143        assert_eq!(points[3].0, zero_negative_x);
144        // 足しても 8 個の中に閉じている
145        for (a, _) in points {
146            for (b, _) in points {
147                let sum = add_points(&a, &b).unwrap();
148                assert!(points.iter().any(|&(point, _)| point == sum));
149            }
150        }
151    }
152
153    #[test]
154    fn a_public_key_plus_a_small_order_point_cannot_sign() {
155        let key = PrivateKey::from_bytes(&[7; 32]);
156        let public_key = PublicKey::from_private_key(&key);
157        let message: &[u8] = b"message";
158        let signature = key.sign(&[message]);
159        for (point, order) in small_order_points() {
160            let shifted = add_points(&public_key.0, &point).unwrap();
161            if order == 1 {
162                assert_eq!(shifted, public_key.0);
163                continue;
164            }
165            assert!(decode_point(&shifted).is_none());
166            assert!(!PublicKey(shifted).verify(&[message], &signature));
167            // 元に戻せる
168            let back = add_points(
169                &shifted,
170                &(-CompressedEdwardsY(point).decompress().unwrap())
171                    .compress()
172                    .to_bytes(),
173            );
174            assert_eq!(back, Some(public_key.0));
175        }
176    }
177
178    #[test]
179    fn the_identity_plus_a_small_order_point_is_that_point() {
180        for (point, _) in small_order_points() {
181            assert_eq!(add_points(&IDENTITY, &point), Some(point));
182        }
183    }
184
185    #[test]
186    fn rejects_a_non_canonical_point() {
187        // y = p は正規形でない(y = 0 と同じ点になる)
188        let mut p = [0xFF; 32];
189        p[0] = 0xED;
190        p[31] = 0x7F;
191        assert_eq!(add_points(&p, &IDENTITY), None);
192        assert_eq!(add_points(&IDENTITY, &p), None);
193    }
194}