encryption/asymmetric/
rsa.rs1use rand_core::OsRng;
27use rsa::pkcs8::{DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey};
28use rsa::traits::PublicKeyParts;
29use rsa::{Oaep, RsaPrivateKey, RsaPublicKey};
30use sha2::Sha256;
31
32use crate::contract::{AsymmetricCipher, Identified};
33use crate::error::{Error, Result};
34use crate::internal::{hex_decode, hex_encode};
35
36use super::KeyPairHex;
37
38const LABEL: &str = "RSA-OAEP-SHA256";
39
40const MIN_KEY_BITS: usize = 2048;
42
43const SHA256_OUTPUT_LEN: usize = 32;
45
46#[derive(Debug, Default, Clone, Copy)]
48pub struct RsaOaepSha256Service;
49
50impl RsaOaepSha256Service {
51 pub fn encrypt(plaintext: &[u8], public_key_hex: &str) -> Result<String> {
53 let public_key = parse_public_key(public_key_hex)?;
54
55 let max_plaintext = public_key
60 .size()
61 .checked_sub(2 * SHA256_OUTPUT_LEN + 2)
62 .ok_or(Error::EncryptionFailed { label: LABEL })?;
63 if plaintext.len() > max_plaintext {
64 return Err(Error::EncryptionFailed { label: LABEL });
65 }
66
67 let ciphertext = public_key
68 .encrypt(&mut OsRng, Oaep::new::<Sha256>(), plaintext)
69 .map_err(|_| Error::EncryptionFailed { label: LABEL })?;
70 Ok(hex_encode(&ciphertext))
71 }
72
73 pub fn decrypt(ciphertext_hex: &str, private_key_hex: &str) -> Result<Vec<u8>> {
75 let private_key = parse_private_key(private_key_hex)?;
76 let ciphertext =
77 hex_decode(ciphertext_hex).map_err(|_| Error::DecryptionFailed { label: LABEL })?;
78
79 private_key
81 .decrypt_blinded(&mut OsRng, Oaep::new::<Sha256>(), &ciphertext)
82 .map_err(|_| Error::DecryptionFailed { label: LABEL })
83 }
84
85 pub fn generate_key_pair_hex(bits: usize) -> Result<KeyPairHex> {
90 if bits < MIN_KEY_BITS {
91 return Err(Error::InvalidKeyLength {
94 label: LABEL,
95 expected: MIN_KEY_BITS,
96 got: bits,
97 });
98 }
99
100 let private_key = RsaPrivateKey::new(&mut OsRng, bits)
101 .map_err(|_| Error::EncryptionFailed { label: LABEL })?;
102 let private_key_der = private_key
103 .to_pkcs8_der()
104 .map_err(|_| Error::EncryptionFailed { label: LABEL })?;
105 let public_key_der = private_key
106 .to_public_key()
107 .to_public_key_der()
108 .map_err(|_| Error::EncryptionFailed { label: LABEL })?;
109
110 Ok(KeyPairHex {
111 private_key_hex: hex_encode(private_key_der.as_bytes()),
112 public_key_hex: hex_encode(public_key_der.as_bytes()),
113 })
114 }
115}
116
117#[derive(Debug, Default, Clone, Copy)]
120pub struct RsaOaepSha256Cipher;
121
122impl RsaOaepSha256Cipher {
123 pub const IDENTIFIER: &'static str = "rsa-oaep-sha256";
124
125 pub fn new() -> Self {
126 Self
127 }
128}
129
130impl Identified for RsaOaepSha256Cipher {
131 fn identifier(&self) -> &str {
132 Self::IDENTIFIER
133 }
134}
135
136impl AsymmetricCipher for RsaOaepSha256Cipher {
137 fn encrypt(&self, plaintext: &[u8], public_key_hex: &str) -> Result<String> {
138 RsaOaepSha256Service::encrypt(plaintext, public_key_hex)
139 }
140
141 fn decrypt(&self, ciphertext_hex: &str, private_key_hex: &str) -> Result<Vec<u8>> {
142 RsaOaepSha256Service::decrypt(ciphertext_hex, private_key_hex)
143 }
144}
145
146fn parse_public_key(public_key_hex: &str) -> Result<RsaPublicKey> {
148 let der = hex_decode(public_key_hex).map_err(|_| Error::InvalidKey { label: LABEL })?;
149 RsaPublicKey::from_public_key_der(&der).map_err(|_| Error::InvalidKey { label: LABEL })
150}
151
152fn parse_private_key(private_key_hex: &str) -> Result<RsaPrivateKey> {
154 let der = hex_decode(private_key_hex).map_err(|_| Error::InvalidKey { label: LABEL })?;
155 RsaPrivateKey::from_pkcs8_der(&der).map_err(|_| Error::InvalidKey { label: LABEL })
156}
157
158#[cfg(test)]
159mod tests {
160 use std::sync::OnceLock;
161
162 use super::*;
163
164 const WYCHEPROOF_PKCS8_HEX: &str = "308204bd020100300d06092a864886f70d0101010500048204a7308204a3020100028201\
171 0100a2b451a07d0aa5f96e455671513550514a8a5b462ebef717094fa1fee82224e637f9\
172 746d3f7cafd31878d80325b6ef5a1700f65903b469429e89d6eac8845097b5ab393189db\
173 92512ed8a7711a1253facd20f79c15e8247f3d3e42e46e48c98e254a2fe9765313a03eff\
174 8f17e1a029397a1fa26a8dce26f490ed81299615d9814c22da610428e09c7d9658594266\
175 f5c021d0fceca08d945a12be82de4d1ece6b4c03145b5d3495d4ed5411eb878daf05fd7a\
176 fc3e09ada0f1126422f590975a1969816f48698bcbba1b4d9cae79d460d8f9f85e797500\
177 5d9bc22c4e5ac0f7c1a45d12569a62807d3b9a02e5a530e773066f453d1f5b4c2e9cf782\
178 0283f742b9d502030100010282010024cdc62317f5d72a6f6ba6cc9632899b01d1ff2886\
179 7d72f61688995bc855a4e420a8405250089bdb13cf8e09543827b748b9d27fbb2b4d9e20\
180 af8c5a6a862796d1a4cc18ad16ea678bc1bd4a83bbbe9c5e57453b5ce7388e41a3ba4ce2\
181 b77b4438a229e954f720dae0353dc088ac8a76b26dc276f8e1b7851ddd6398ad16ff2e78\
182 195123b9b036e945c38c9d12434f6df76fe22359eb3e1ac9c011678fc926fad3ae475a4f\
183 ffff55feb2d147e9c894f4c0e29a599e762462482d968bf42780945fc0d2c31c573c4431\
184 b8f4fe8b8c67bec815abd44f7a86edca1c2308737358d2c2ae5e2e0e2dadf73098026237\
185 7e58b13b7d9992060a0bc870ccfdb4a9319ee102818100dc431050f782e894fb5248247d\
186 98cb7d58b8d1e24f3b55d041c56e4de086b0d5bb028bda42eeb5d234d5681e5809d415e6\
187 a289ad4cfbf78f978f6c35814f50eebff1c5b80a69f788e81e6bab5ddaa78369d659d143\
188 ec6f17e79813a575cfad9c569156b90113e2e9110ad9e7b48a1c9348a6e653321191290e\
189 a36cfb3a5b18f102818100bd1a81e7977f9898122273ae3222b598ea5fb19eb4eabc3830\
190 8a5e32196603b2e500ffb79f5b886816611debc472fac45544070beb057c941378a6868a\
191 f3b7a03d3f9880ec47d5e089b94fbde542aba9ae8d72c57088d7abf5b131f39098f7bc16\
192 0f90536abc9492fd4e06f3ed7299d4b97bb03677207d95669f140cfbc20f2502818100a9\
193 4b528b28f291599121d91952ffd1c7f21d7c1479d99d478885fb161870ee1218bf084726\
194 12dbe5497e8d9c650688e09c786961ae3e2c354dc48ae34514759c4c23c4588488961dc0\
195 6b414e61c0e1e7fbbd2923d31532fe289f96da220711e58c14019808e00414276933bb07\
196 e4efb9b4a9b37656917205209f33f09515d7c10281803af0e72a933aef09ff2503df78ba\
197 fed531c02ff1a2bc437c540cdcbd4ad35435cf511763596543480629b114ca7f780ff7ef\
198 a32ea0cb6e000d6d9ea1f2ef71fd9cf9948422a165557e37e755edfe70d90b920502eb47\
199 8bc98a63f788ce3a0f856d6ede7251a383bfa8fa480a81a925af7b3cc538c4bab8c9f759\
200 7ffb68011d8d0281802640fbfbcfefb163ee7a87b6483a66ee41f956d90fa8a7939bfc04\
201 2ee0924b1b7993d0445f758d51933e85179c0320b0c968b48a91c38b5be923e1097c0c56\
202 2f88d42294b6a2759bafa5428a74f1270874e45f6fcc60f21602de5eccd143cf31241f59\
203 21b5ad3983fb54ef17be3b285367e50c999c67247b552fe4bfce945f7b";
204 const WYCHEPROOF_CT_VALID: &str = "5eab3f0741e63986ed647d53e1cd71df041986900803d0f99c68355d249a15a47dc5b4f7\
206 0a191477654299e5a2731f3b4eec76dea18262fc696ac794e5f66cbfcddac4472c578e24\
207 6c26707598055584540b839836b1404c5611ae558a984cee8fd036cea924e0be2474a940\
208 f61e0acc14fcae95ebdc59942a9ce9af9a9c81999f7f6815f057ffdc2533cb15d6391d1e\
209 2d95f16f9c04209c889a4c359c7d2926d28a66e2b030a416b928d2825627998e5191fb49\
210 83a6e65024262d94fc09187a2d78162122433251d1bfcc8e507d06eba2d229c10031261d\
211 a32ab8ccd15f1c5f9fbf07ed158483d736a110af4b44d6a4da60d6cb519b4454213cf9f0\
212 dc560f2b";
213 const WYCHEPROOF_CT_N_MINUS_1: &str = "a2b451a07d0aa5f96e455671513550514a8a5b462ebef717094fa1fee82224e637f9746d\
215 3f7cafd31878d80325b6ef5a1700f65903b469429e89d6eac8845097b5ab393189db9251\
216 2ed8a7711a1253facd20f79c15e8247f3d3e42e46e48c98e254a2fe9765313a03eff8f17\
217 e1a029397a1fa26a8dce26f490ed81299615d9814c22da610428e09c7d9658594266f5c0\
218 21d0fceca08d945a12be82de4d1ece6b4c03145b5d3495d4ed5411eb878daf05fd7afc3e\
219 09ada0f1126422f590975a1969816f48698bcbba1b4d9cae79d460d8f9f85e7975005d9b\
220 c22c4e5ac0f7c1a45d12569a62807d3b9a02e5a530e773066f453d1f5b4c2e9cf7820283\
221 f742b9d4";
222 const WYCHEPROOF_MSG_VALID_HEX: &str = "54657374"; fn wycheproof_keypair_hex() -> KeyPairHex {
227 let der = hex_decode(WYCHEPROOF_PKCS8_HEX).unwrap();
228 let private_key = RsaPrivateKey::from_pkcs8_der(&der).unwrap();
229 let public_der = private_key.to_public_key().to_public_key_der().unwrap();
230 KeyPairHex {
231 private_key_hex: WYCHEPROOF_PKCS8_HEX.to_string(),
232 public_key_hex: hex_encode(public_der.as_bytes()),
233 }
234 }
235
236 fn generated_keypair() -> &'static KeyPairHex {
238 static PAIR: OnceLock<KeyPairHex> = OnceLock::new();
239 PAIR.get_or_init(|| RsaOaepSha256Service::generate_key_pair_hex(MIN_KEY_BITS).unwrap())
240 }
241
242 #[test]
243 fn wycheproof_fixed_vectors() {
244 let pair = wycheproof_keypair_hex();
245
246 assert_eq!(
248 RsaOaepSha256Service::decrypt(WYCHEPROOF_CT_VALID, &pair.private_key_hex).unwrap(),
249 hex_decode(WYCHEPROOF_MSG_VALID_HEX).unwrap()
250 );
251
252 let ciphertext = RsaOaepSha256Service::encrypt(b"Test", &pair.public_key_hex).unwrap();
254 assert_eq!(
255 RsaOaepSha256Service::decrypt(&ciphertext, &pair.private_key_hex).unwrap(),
256 b"Test"
257 );
258
259 for ciphertext in [WYCHEPROOF_CT_N_MINUS_1, ""] {
261 assert_eq!(
262 RsaOaepSha256Service::decrypt(ciphertext, &pair.private_key_hex).unwrap_err(),
263 Error::DecryptionFailed { label: LABEL }
264 );
265 }
266 }
267
268 #[test]
269 fn keypair_roundtrip_self_parse_and_shapes() {
270 let pair = generated_keypair();
271
272 let ciphertext =
275 RsaOaepSha256Service::encrypt("RSA 数据 🎉".as_bytes(), &pair.public_key_hex).unwrap();
276 assert_eq!(ciphertext.len(), 512);
277 assert_eq!(
278 RsaOaepSha256Service::decrypt(&ciphertext, &pair.private_key_hex).unwrap(),
279 "RSA 数据 🎉".as_bytes()
280 );
281
282 for der_hex in [&pair.private_key_hex, &pair.public_key_hex] {
284 assert!(der_hex.starts_with("30"));
285 assert!(der_hex.len().is_multiple_of(2));
286 }
287 }
288
289 #[test]
290 fn wrong_private_key_or_tampered_ciphertext_fails() {
291 let wycheproof = wycheproof_keypair_hex();
292 let generated = generated_keypair();
293
294 let ciphertext =
296 RsaOaepSha256Service::encrypt(b"secret", &wycheproof.public_key_hex).unwrap();
297 assert_eq!(
298 RsaOaepSha256Service::decrypt(&ciphertext, &generated.private_key_hex).unwrap_err(),
299 Error::DecryptionFailed { label: LABEL }
300 );
301
302 let mut tampered = ciphertext.clone();
304 let last = tampered.len() - 1;
305 let flipped = if tampered.as_bytes()[last] == b'0' {
306 '1'
307 } else {
308 '0'
309 };
310 tampered.replace_range(last.., &flipped.to_string());
311 assert_eq!(
312 RsaOaepSha256Service::decrypt(&tampered, &wycheproof.private_key_hex).unwrap_err(),
313 Error::DecryptionFailed { label: LABEL }
314 );
315 }
316
317 #[test]
318 fn oversized_plaintext_is_rejected() {
319 let pair = wycheproof_keypair_hex();
320 let max_plaintext = [0u8; 190];
322 RsaOaepSha256Service::encrypt(&max_plaintext, &pair.public_key_hex).unwrap();
323
324 let too_long = [0u8; 191];
325 assert_eq!(
326 RsaOaepSha256Service::encrypt(&too_long, &pair.public_key_hex).unwrap_err(),
327 Error::EncryptionFailed { label: LABEL }
328 );
329 }
330
331 #[test]
332 fn malformed_keys_are_rejected() {
333 let pair = wycheproof_keypair_hex();
334
335 assert_eq!(
337 RsaOaepSha256Service::encrypt(b"x", "zz").unwrap_err(),
338 Error::InvalidKey { label: LABEL }
339 );
340 assert_eq!(
341 RsaOaepSha256Service::decrypt("00", "zz").unwrap_err(),
342 Error::InvalidKey { label: LABEL }
343 );
344 assert_eq!(
346 RsaOaepSha256Service::encrypt(b"x", "deadbeef").unwrap_err(),
347 Error::InvalidKey { label: LABEL }
348 );
349 let truncated = &pair.private_key_hex[..pair.private_key_hex.len() - 2];
350 assert_eq!(
351 RsaOaepSha256Service::decrypt("00", truncated).unwrap_err(),
352 Error::InvalidKey { label: LABEL }
353 );
354 assert_eq!(
356 RsaOaepSha256Service::decrypt("00", &pair.public_key_hex).unwrap_err(),
357 Error::InvalidKey { label: LABEL }
358 );
359 }
360
361 #[test]
362 fn key_bits_below_floor_are_rejected() {
363 for bits in [512, 1024, 2047] {
364 assert_eq!(
365 RsaOaepSha256Service::generate_key_pair_hex(bits).unwrap_err(),
366 Error::InvalidKeyLength {
367 label: LABEL,
368 expected: MIN_KEY_BITS,
369 got: bits,
370 }
371 );
372 }
373 }
374
375 #[test]
376 fn cipher_trait_matches_service() {
377 let cipher = RsaOaepSha256Cipher::new();
378 assert_eq!(cipher.identifier(), "rsa-oaep-sha256");
379
380 let pair = wycheproof_keypair_hex();
381 let ciphertext = cipher.encrypt(b"via trait", &pair.public_key_hex).unwrap();
382 assert_eq!(
383 cipher.decrypt(&ciphertext, &pair.private_key_hex).unwrap(),
384 b"via trait"
385 );
386 }
387}