1 use rand::Rng;
2 use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
3
4 use crate::errors::{Error, Result};
5 use crate::hash::Hash;
6 use crate::key::{self, PrivateKey, PublicKey};
7
8 // Encrypts the given message with RSA and the padding
9 // scheme from PKCS#1 v1.5. The message must be no longer than the
10 // length of the public modulus minus 11 bytes.
11 #[inline]
encrypt<R: Rng, PK: PublicKey>(rng: &mut R, pub_key: &PK, msg: &[u8]) -> Result<Vec<u8>>12 pub fn encrypt<R: Rng, PK: PublicKey>(rng: &mut R, pub_key: &PK, msg: &[u8]) -> Result<Vec<u8>> {
13 key::check_public(pub_key)?;
14
15 let k = pub_key.size();
16 if msg.len() > k - 11 {
17 return Err(Error::MessageTooLong);
18 }
19
20 // EM = 0x00 || 0x02 || PS || 0x00 || M
21 let mut em = vec![0u8; k];
22 em[1] = 2;
23 non_zero_random_bytes(rng, &mut em[2..k - msg.len() - 1]);
24 em[k - msg.len() - 1] = 0;
25 em[k - msg.len()..].copy_from_slice(msg);
26
27 pub_key.raw_encryption_primitive(&em, pub_key.size())
28 }
29
30 /// Decrypts a plaintext using RSA and the padding scheme from PKCS#1 v1.5.
31 // If an `rng` is passed, it uses RSA blinding to avoid timing side-channel attacks.
32 //
33 // Note that whether this function returns an error or not discloses secret
34 // information. If an attacker can cause this function to run repeatedly and
35 // learn whether each instance returned an error then they can decrypt and
36 // forge signatures as if they had the private key. See
37 // `decrypt_session_key` for a way of solving this problem.
38 #[inline]
decrypt<R: Rng, SK: PrivateKey>( rng: Option<&mut R>, priv_key: &SK, ciphertext: &[u8], ) -> Result<Vec<u8>>39 pub fn decrypt<R: Rng, SK: PrivateKey>(
40 rng: Option<&mut R>,
41 priv_key: &SK,
42 ciphertext: &[u8],
43 ) -> Result<Vec<u8>> {
44 key::check_public(priv_key)?;
45
46 let (valid, out, index) = decrypt_inner(rng, priv_key, ciphertext)?;
47 if valid == 0 {
48 return Err(Error::Decryption);
49 }
50
51 Ok(out[index as usize..].to_vec())
52 }
53
54 // Calculates the signature of hashed using
55 // RSASSA-PKCS1-V1_5-SIGN from RSA PKCS#1 v1.5. Note that `hashed` must
56 // be the result of hashing the input message using the given hash
57 // function. If hash is `None`, hashed is signed directly. This isn't
58 // advisable except for interoperability.
59 //
60 // If `rng` is not `None` then RSA blinding will be used to avoid timing
61 // side-channel attacks.
62 //
63 // This function is deterministic. Thus, if the set of possible
64 // messages is small, an attacker may be able to build a map from
65 // messages to signatures and identify the signed messages. As ever,
66 // signatures provide authenticity, not confidentiality.
67 #[inline]
sign<R: Rng, SK: PrivateKey>( rng: Option<&mut R>, priv_key: &SK, hash: Option<&Hash>, hashed: &[u8], ) -> Result<Vec<u8>>68 pub fn sign<R: Rng, SK: PrivateKey>(
69 rng: Option<&mut R>,
70 priv_key: &SK,
71 hash: Option<&Hash>,
72 hashed: &[u8],
73 ) -> Result<Vec<u8>> {
74 let (hash_len, prefix) = hash_info(hash, hashed.len())?;
75
76 let t_len = prefix.len() + hash_len;
77 let k = priv_key.size();
78 if k < t_len + 11 {
79 return Err(Error::MessageTooLong);
80 }
81
82 // EM = 0x00 || 0x01 || PS || 0x00 || T
83 let mut em = vec![0xff; k];
84 em[0] = 0;
85 em[1] = 1;
86 em[k - t_len - 1] = 0;
87 em[k - t_len..k - hash_len].copy_from_slice(&prefix);
88 em[k - hash_len..k].copy_from_slice(hashed);
89
90 priv_key.raw_decryption_primitive(rng, &em, priv_key.size())
91 }
92
93 /// Verifies an RSA PKCS#1 v1.5 signature.
94 #[inline]
verify<PK: PublicKey>( pub_key: &PK, hash: Option<&Hash>, hashed: &[u8], sig: &[u8], ) -> Result<()>95 pub fn verify<PK: PublicKey>(
96 pub_key: &PK,
97 hash: Option<&Hash>,
98 hashed: &[u8],
99 sig: &[u8],
100 ) -> Result<()> {
101 let (hash_len, prefix) = hash_info(hash, hashed.len())?;
102
103 let t_len = prefix.len() + hash_len;
104 let k = pub_key.size();
105 if k < t_len + 11 {
106 return Err(Error::Verification);
107 }
108
109 let em = pub_key.raw_encryption_primitive(sig, pub_key.size())?;
110
111 // EM = 0x00 || 0x01 || PS || 0x00 || T
112 let mut ok = em[0].ct_eq(&0u8);
113 ok &= em[1].ct_eq(&1u8);
114 ok &= em[k - hash_len..k].ct_eq(hashed);
115 ok &= em[k - t_len..k - hash_len].ct_eq(&prefix);
116 ok &= em[k - t_len - 1].ct_eq(&0u8);
117
118 for el in em.iter().skip(2).take(k - t_len - 3) {
119 ok &= el.ct_eq(&0xff)
120 }
121
122 if ok.unwrap_u8() != 1 {
123 return Err(Error::Verification);
124 }
125
126 Ok(())
127 }
128
129 #[inline]
hash_info(hash: Option<&Hash>, digest_len: usize) -> Result<(usize, &'static [u8])>130 fn hash_info(hash: Option<&Hash>, digest_len: usize) -> Result<(usize, &'static [u8])> {
131 match hash {
132 Some(hash) => {
133 let hash_len = hash.size();
134 if digest_len != hash_len {
135 return Err(Error::InputNotHashed);
136 }
137
138 Ok((hash_len, hash.asn1_prefix()))
139 }
140 // this means the data is signed directly
141 None => Ok((digest_len, &[])),
142 }
143 }
144
145 /// Decrypts ciphertext using `priv_key` and blinds the operation if
146 /// `rng` is given. It returns one or zero in valid that indicates whether the
147 /// plaintext was correctly structured. In either case, the plaintext is
148 /// returned in em so that it may be read independently of whether it was valid
149 /// in order to maintain constant memory access patterns. If the plaintext was
150 /// valid then index contains the index of the original message in em.
151 #[inline]
decrypt_inner<R: Rng, SK: PrivateKey>( rng: Option<&mut R>, priv_key: &SK, ciphertext: &[u8], ) -> Result<(u8, Vec<u8>, u32)>152 fn decrypt_inner<R: Rng, SK: PrivateKey>(
153 rng: Option<&mut R>,
154 priv_key: &SK,
155 ciphertext: &[u8],
156 ) -> Result<(u8, Vec<u8>, u32)> {
157 let k = priv_key.size();
158 if k < 11 {
159 return Err(Error::Decryption);
160 }
161
162 let em = priv_key.raw_decryption_primitive(rng, ciphertext, priv_key.size())?;
163
164 let first_byte_is_zero = em[0].ct_eq(&0u8);
165 let second_byte_is_two = em[1].ct_eq(&2u8);
166
167 // The remainder of the plaintext must be a string of non-zero random
168 // octets, followed by a 0, followed by the message.
169 // looking_for_index: 1 iff we are still looking for the zero.
170 // index: the offset of the first zero byte.
171 let mut looking_for_index = 1u8;
172 let mut index = 0u32;
173
174 for (i, el) in em.iter().enumerate().skip(2) {
175 let equals0 = el.ct_eq(&0u8);
176 index.conditional_assign(&(i as u32), Choice::from(looking_for_index) & equals0);
177 looking_for_index.conditional_assign(&0u8, equals0);
178 }
179
180 // The PS padding must be at least 8 bytes long, and it starts two
181 // bytes into em.
182 // TODO: WARNING: THIS MUST BE CONSTANT TIME CHECK:
183 // Ref: https://github.com/dalek-cryptography/subtle/issues/20
184 // This is currently copy & paste from the constant time impl in
185 // go, but very likely not sufficient.
186 let valid_ps = Choice::from((((2i32 + 8i32 - index as i32 - 1i32) >> 31) & 1) as u8);
187 let valid =
188 first_byte_is_zero & second_byte_is_two & Choice::from(!looking_for_index & 1) & valid_ps;
189 index = u32::conditional_select(&0, &(index + 1), valid);
190
191 Ok((valid.unwrap_u8(), em, index))
192 }
193
194 /// Fills the provided slice with random values, which are guranteed
195 /// to not be zero.
196 #[inline]
non_zero_random_bytes<R: Rng>(rng: &mut R, data: &mut [u8])197 fn non_zero_random_bytes<R: Rng>(rng: &mut R, data: &mut [u8]) {
198 rng.fill(data);
199
200 for el in data {
201 if *el == 0u8 {
202 // TODO: break after a certain amount of time
203 while *el == 0u8 {
204 *el = rng.gen();
205 }
206 }
207 }
208 }
209
210 #[cfg(test)]
211 mod tests {
212 use super::*;
213 use base64;
214 use hex;
215 use num_bigint::BigUint;
216 use num_traits::FromPrimitive;
217 use num_traits::Num;
218 use rand::thread_rng;
219 use sha1::{Digest, Sha1};
220
221 use crate::{Hash, PaddingScheme, PublicKey, PublicKeyParts, RSAPrivateKey, RSAPublicKey};
222
223 #[test]
test_non_zero_bytes()224 fn test_non_zero_bytes() {
225 for _ in 0..10 {
226 let mut rng = thread_rng();
227 let mut b = vec![0u8; 512];
228 non_zero_random_bytes(&mut rng, &mut b);
229 for el in &b {
230 assert_ne!(*el, 0u8);
231 }
232 }
233 }
234
get_private_key() -> RSAPrivateKey235 fn get_private_key() -> RSAPrivateKey {
236 // In order to generate new test vectors you'll need the PEM form of this key:
237 // -----BEGIN RSA PRIVATE KEY-----
238 // MIIBOgIBAAJBALKZD0nEffqM1ACuak0bijtqE2QrI/KLADv7l3kK3ppMyCuLKoF0
239 // fd7Ai2KW5ToIwzFofvJcS/STa6HA5gQenRUCAwEAAQJBAIq9amn00aS0h/CrjXqu
240 // /ThglAXJmZhOMPVn4eiu7/ROixi9sex436MaVeMqSNf7Ex9a8fRNfWss7Sqd9eWu
241 // RTUCIQDasvGASLqmjeffBNLTXV2A5g4t+kLVCpsEIZAycV5GswIhANEPLmax0ME/
242 // EO+ZJ79TJKN5yiGBRsv5yvx5UiHxajEXAiAhAol5N4EUyq6I9w1rYdhPMGpLfk7A
243 // IU2snfRJ6Nq2CQIgFrPsWRCkV+gOYcajD17rEqmuLrdIRexpg8N1DOSXoJ8CIGlS
244 // tAboUGBxTDq3ZroNism3DaMIbKPyYrAqhKov1h5V
245 // -----END RSA PRIVATE KEY-----
246
247 RSAPrivateKey::from_components(
248 BigUint::from_str_radix("9353930466774385905609975137998169297361893554149986716853295022578535724979677252958524466350471210367835187480748268864277464700638583474144061408845077", 10).unwrap(),
249 BigUint::from_u64(65537).unwrap(),
250 BigUint::from_str_radix("7266398431328116344057699379749222532279343923819063639497049039389899328538543087657733766554155839834519529439851673014800261285757759040931985506583861", 10).unwrap(),
251 vec![
252 BigUint::from_str_radix("98920366548084643601728869055592650835572950932266967461790948584315647051443",10).unwrap(),
253 BigUint::from_str_radix("94560208308847015747498523884063394671606671904944666360068158221458669711639", 10).unwrap()
254 ],
255 )
256 }
257
258 #[test]
test_decrypt_pkcs1v15()259 fn test_decrypt_pkcs1v15() {
260 let priv_key = get_private_key();
261
262 let tests = [[
263 "gIcUIoVkD6ATMBk/u/nlCZCCWRKdkfjCgFdo35VpRXLduiKXhNz1XupLLzTXAybEq15juc+EgY5o0DHv/nt3yg==",
264 "x",
265 ], [
266 "Y7TOCSqofGhkRb+jaVRLzK8xw2cSo1IVES19utzv6hwvx+M8kFsoWQm5DzBeJCZTCVDPkTpavUuEbgp8hnUGDw==",
267 "testing.",
268 ], [
269 "arReP9DJtEVyV2Dg3dDp4c/PSk1O6lxkoJ8HcFupoRorBZG+7+1fDAwT1olNddFnQMjmkb8vxwmNMoTAT/BFjQ==",
270 "testing.\n",
271 ], [
272 "WtaBXIoGC54+vH0NH0CHHE+dRDOsMc/6BrfFu2lEqcKL9+uDuWaf+Xj9mrbQCjjZcpQuX733zyok/jsnqe/Ftw==",
273 "01234567890123456789012345678901234567890123456789012",
274 ]];
275
276 for test in &tests {
277 let out = priv_key
278 .decrypt(
279 PaddingScheme::new_pkcs1v15_encrypt(),
280 &base64::decode(test[0]).unwrap(),
281 )
282 .unwrap();
283 assert_eq!(out, test[1].as_bytes());
284 }
285 }
286
287 #[test]
test_encrypt_decrypt_pkcs1v15()288 fn test_encrypt_decrypt_pkcs1v15() {
289 let mut rng = thread_rng();
290 let priv_key = get_private_key();
291 let k = priv_key.size();
292
293 for i in 1..100 {
294 let mut input: Vec<u8> = (0..i * 8).map(|_| rng.gen()).collect();
295 if input.len() > k - 11 {
296 input = input[0..k - 11].to_vec();
297 }
298
299 let pub_key: RSAPublicKey = priv_key.clone().into();
300 let ciphertext = encrypt(&mut rng, &pub_key, &input).unwrap();
301 assert_ne!(input, ciphertext);
302 let blind: bool = rng.gen();
303 let blinder = if blind { Some(&mut rng) } else { None };
304 let plaintext = decrypt(blinder, &priv_key, &ciphertext).unwrap();
305 assert_eq!(input, plaintext);
306 }
307 }
308
309 #[test]
test_sign_pkcs1v15()310 fn test_sign_pkcs1v15() {
311 let priv_key = get_private_key();
312
313 let tests = [[
314 "Test.\n", "a4f3fa6ea93bcdd0c57be020c1193ecbfd6f200a3d95c409769b029578fa0e336ad9a347600e40d3ae823b8c7e6bad88cc07c1d54c3a1523cbbb6d58efc362ae"
315 ]];
316
317 for test in &tests {
318 let digest = Sha1::digest(test[0].as_bytes()).to_vec();
319 let expected = hex::decode(test[1]).unwrap();
320
321 let out = priv_key
322 .sign(PaddingScheme::new_pkcs1v15_sign(Some(Hash::SHA1)), &digest)
323 .unwrap();
324 assert_ne!(out, digest);
325 assert_eq!(out, expected);
326
327 let mut rng = thread_rng();
328 let out2 = priv_key
329 .sign_blinded(
330 &mut rng,
331 PaddingScheme::new_pkcs1v15_sign(Some(Hash::SHA1)),
332 &digest,
333 )
334 .unwrap();
335 assert_eq!(out2, expected);
336 }
337 }
338
339 #[test]
test_verify_pkcs1v15()340 fn test_verify_pkcs1v15() {
341 let priv_key = get_private_key();
342
343 let tests = [[
344 "Test.\n", "a4f3fa6ea93bcdd0c57be020c1193ecbfd6f200a3d95c409769b029578fa0e336ad9a347600e40d3ae823b8c7e6bad88cc07c1d54c3a1523cbbb6d58efc362ae"
345 ]];
346 let pub_key: RSAPublicKey = priv_key.into();
347
348 for test in &tests {
349 let digest = Sha1::digest(test[0].as_bytes()).to_vec();
350 let sig = hex::decode(test[1]).unwrap();
351
352 pub_key
353 .verify(
354 PaddingScheme::new_pkcs1v15_sign(Some(Hash::SHA1)),
355 &digest,
356 &sig,
357 )
358 .expect("failed to verify");
359 }
360 }
361
362 #[test]
test_unpadded_signature()363 fn test_unpadded_signature() {
364 let msg = b"Thu Dec 19 18:06:16 EST 2013\n";
365 let expected_sig = base64::decode("pX4DR8azytjdQ1rtUiC040FjkepuQut5q2ZFX1pTjBrOVKNjgsCDyiJDGZTCNoh9qpXYbhl7iEym30BWWwuiZg==").unwrap();
366 let priv_key = get_private_key();
367
368 let sig = priv_key
369 .sign(PaddingScheme::new_pkcs1v15_sign(None), msg)
370 .unwrap();
371 assert_eq!(expected_sig, sig);
372
373 let pub_key: RSAPublicKey = priv_key.into();
374 pub_key
375 .verify(PaddingScheme::new_pkcs1v15_sign(None), msg, &sig)
376 .expect("failed to verify");
377 }
378 }
379