Struct openssl::rsa::Padding

source ·
pub struct Padding(_);
Expand description

Type of encryption padding to use.

Random length padding is primarily used to prevent attackers from predicting or knowing the exact length of a plaintext message that can possibly lead to breaking encryption.

Implementations§

Creates a Padding from an integer representation.

Examples found in repository?
src/pkey_ctx.rs (line 350)
344
345
346
347
348
349
350
351
    pub fn rsa_padding(&self) -> Result<Padding, ErrorStack> {
        let mut pad = 0;
        unsafe {
            cvt(ffi::EVP_PKEY_CTX_get_rsa_padding(self.as_ptr(), &mut pad))?;
        }

        Ok(Padding::from_raw(pad))
    }
More examples
Hide additional examples
src/encrypt.rs (line 106)
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
    pub fn rsa_padding(&self) -> Result<Padding, ErrorStack> {
        unsafe {
            let mut pad = 0;
            cvt(ffi::EVP_PKEY_CTX_get_rsa_padding(self.pctx, &mut pad))
                .map(|_| Padding::from_raw(pad))
        }
    }

    /// Sets the RSA padding mode.
    ///
    /// This is only useful for RSA keys.
    ///
    /// This corresponds to [`EVP_PKEY_CTX_set_rsa_padding`].
    ///
    /// [`EVP_PKEY_CTX_set_rsa_padding`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_CTX_set_rsa_padding.html
    pub fn set_rsa_padding(&mut self, padding: Padding) -> Result<(), ErrorStack> {
        unsafe {
            cvt(ffi::EVP_PKEY_CTX_set_rsa_padding(
                self.pctx,
                padding.as_raw(),
            ))
            .map(|_| ())
        }
    }

    /// Sets the RSA MGF1 algorithm.
    ///
    /// This is only useful for RSA keys.
    ///
    /// This corresponds to [`EVP_PKEY_CTX_set_rsa_mgf1_md`].
    ///
    /// [`EVP_PKEY_CTX_set_rsa_mgf1_md`]: https://www.openssl.org/docs/manmaster/man7/RSA-PSS.html
    pub fn set_rsa_mgf1_md(&mut self, md: MessageDigest) -> Result<(), ErrorStack> {
        unsafe {
            cvt(ffi::EVP_PKEY_CTX_set_rsa_mgf1_md(
                self.pctx,
                md.as_ptr() as *mut _,
            ))
            .map(|_| ())
        }
    }

    /// Sets the RSA OAEP algorithm.
    ///
    /// This is only useful for RSA keys.
    ///
    /// This corresponds to [`EVP_PKEY_CTX_set_rsa_oaep_md`].
    ///
    /// [`EVP_PKEY_CTX_set_rsa_oaep_md`]: https://www.openssl.org/docs/manmaster/man3/EVP_PKEY_CTX_set_rsa_oaep_md.html
    #[cfg(any(ossl102, libressl310))]
    pub fn set_rsa_oaep_md(&mut self, md: MessageDigest) -> Result<(), ErrorStack> {
        unsafe {
            cvt(ffi::EVP_PKEY_CTX_set_rsa_oaep_md(
                self.pctx,
                md.as_ptr() as *mut _,
            ))
            .map(|_| ())
        }
    }

    /// Sets the RSA OAEP label.
    ///
    /// This is only useful for RSA keys.
    ///
    /// This corresponds to [`EVP_PKEY_CTX_set0_rsa_oaep_label`].
    ///
    /// [`EVP_PKEY_CTX_set0_rsa_oaep_label`]: https://www.openssl.org/docs/manmaster/man3/EVP_PKEY_CTX_set0_rsa_oaep_label.html
    #[cfg(any(ossl102, libressl310))]
    pub fn set_rsa_oaep_label(&mut self, label: &[u8]) -> Result<(), ErrorStack> {
        unsafe {
            let p = cvt_p(ffi::OPENSSL_malloc(label.len() as _))?;
            ptr::copy_nonoverlapping(label.as_ptr(), p as *mut u8, label.len());

            cvt(ffi::EVP_PKEY_CTX_set0_rsa_oaep_label(
                self.pctx,
                p as *mut c_void,
                label.len() as c_int,
            ))
            .map(|_| ())
            .map_err(|e| {
                ffi::OPENSSL_free(p);
                e
            })
        }
    }

    /// Performs public key encryption.
    ///
    /// In order to know the size needed for the output buffer, use [`encrypt_len`](Encrypter::encrypt_len).
    /// Note that the length of the output buffer can be greater of the length of the encoded data.
    /// ```
    /// # use openssl::{
    /// #   encrypt::Encrypter,
    /// #   pkey::PKey,
    /// #   rsa::{Rsa, Padding},
    /// # };
    /// #
    /// # let key = include_bytes!("../test/rsa.pem");
    /// # let private_key = Rsa::private_key_from_pem(key).unwrap();
    /// # let pkey = PKey::from_rsa(private_key).unwrap();
    /// # let input = b"hello world".to_vec();
    /// #
    /// let mut encrypter = Encrypter::new(&pkey).unwrap();
    /// encrypter.set_rsa_padding(Padding::PKCS1).unwrap();
    ///
    /// // Get the length of the output buffer
    /// let buffer_len = encrypter.encrypt_len(&input).unwrap();
    /// let mut encoded = vec![0u8; buffer_len];
    ///
    /// // Encode the data and get its length
    /// let encoded_len = encrypter.encrypt(&input, &mut encoded).unwrap();
    ///
    /// // Use only the part of the buffer with the encoded data
    /// let encoded = &encoded[..encoded_len];
    /// ```
    ///
    /// This corresponds to [`EVP_PKEY_encrypt`].
    ///
    /// [`EVP_PKEY_encrypt`]: https://www.openssl.org/docs/manmaster/man3/EVP_PKEY_encrypt.html
    pub fn encrypt(&self, from: &[u8], to: &mut [u8]) -> Result<usize, ErrorStack> {
        let mut written = to.len();
        unsafe {
            cvt(ffi::EVP_PKEY_encrypt(
                self.pctx,
                to.as_mut_ptr(),
                &mut written,
                from.as_ptr(),
                from.len(),
            ))?;
        }

        Ok(written)
    }

    /// Gets the size of the buffer needed to encrypt the input data.
    ///
    /// This corresponds to [`EVP_PKEY_encrypt`] called with a null pointer as output argument.
    ///
    /// [`EVP_PKEY_encrypt`]: https://www.openssl.org/docs/manmaster/man3/EVP_PKEY_encrypt.html
    pub fn encrypt_len(&self, from: &[u8]) -> Result<usize, ErrorStack> {
        let mut written = 0;
        unsafe {
            cvt(ffi::EVP_PKEY_encrypt(
                self.pctx,
                ptr::null_mut(),
                &mut written,
                from.as_ptr(),
                from.len(),
            ))?;
        }

        Ok(written)
    }
}

/// A type which decrypts data.
pub struct Decrypter<'a> {
    pctx: *mut ffi::EVP_PKEY_CTX,
    _p: PhantomData<&'a ()>,
}

unsafe impl<'a> Sync for Decrypter<'a> {}
unsafe impl<'a> Send for Decrypter<'a> {}

impl<'a> Drop for Decrypter<'a> {
    fn drop(&mut self) {
        unsafe {
            ffi::EVP_PKEY_CTX_free(self.pctx);
        }
    }
}

impl<'a> Decrypter<'a> {
    /// Creates a new `Decrypter`.
    ///
    /// OpenSSL documentation at [`EVP_PKEY_decrypt_init`].
    ///
    /// [`EVP_PKEY_decrypt_init`]: https://www.openssl.org/docs/manmaster/man3/EVP_PKEY_decrypt_init.html
    pub fn new<T>(pkey: &'a PKeyRef<T>) -> Result<Decrypter<'a>, ErrorStack>
    where
        T: HasPrivate,
    {
        unsafe {
            ffi::init();

            let pctx = cvt_p(ffi::EVP_PKEY_CTX_new(pkey.as_ptr(), ptr::null_mut()))?;
            let r = ffi::EVP_PKEY_decrypt_init(pctx);
            if r != 1 {
                ffi::EVP_PKEY_CTX_free(pctx);
                return Err(ErrorStack::get());
            }

            Ok(Decrypter {
                pctx,
                _p: PhantomData,
            })
        }
    }

    /// Returns the RSA padding mode in use.
    ///
    /// This is only useful for RSA keys.
    ///
    /// This corresponds to `EVP_PKEY_CTX_get_rsa_padding`.
    pub fn rsa_padding(&self) -> Result<Padding, ErrorStack> {
        unsafe {
            let mut pad = 0;
            cvt(ffi::EVP_PKEY_CTX_get_rsa_padding(self.pctx, &mut pad))
                .map(|_| Padding::from_raw(pad))
        }
    }
src/sign.rs (line 207)
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
    pub fn rsa_padding(&self) -> Result<Padding, ErrorStack> {
        unsafe {
            let mut pad = 0;
            cvt(ffi::EVP_PKEY_CTX_get_rsa_padding(self.pctx, &mut pad))
                .map(|_| Padding::from_raw(pad))
        }
    }

    /// Sets the RSA padding mode.
    ///
    /// This is only useful for RSA keys.
    ///
    /// This corresponds to [`EVP_PKEY_CTX_set_rsa_padding`].
    ///
    /// [`EVP_PKEY_CTX_set_rsa_padding`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_CTX_set_rsa_padding.html
    pub fn set_rsa_padding(&mut self, padding: Padding) -> Result<(), ErrorStack> {
        unsafe {
            cvt(ffi::EVP_PKEY_CTX_set_rsa_padding(
                self.pctx,
                padding.as_raw(),
            ))
            .map(|_| ())
        }
    }

    /// Sets the RSA PSS salt length.
    ///
    /// This is only useful for RSA keys.
    ///
    /// This corresponds to [`EVP_PKEY_CTX_set_rsa_pss_saltlen`].
    ///
    /// [`EVP_PKEY_CTX_set_rsa_pss_saltlen`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_CTX_set_rsa_pss_saltlen.html
    pub fn set_rsa_pss_saltlen(&mut self, len: RsaPssSaltlen) -> Result<(), ErrorStack> {
        unsafe {
            cvt(ffi::EVP_PKEY_CTX_set_rsa_pss_saltlen(
                self.pctx,
                len.as_raw(),
            ))
            .map(|_| ())
        }
    }

    /// Sets the RSA MGF1 algorithm.
    ///
    /// This is only useful for RSA keys.
    ///
    /// This corresponds to [`EVP_PKEY_CTX_set_rsa_mgf1_md`].
    ///
    /// [`EVP_PKEY_CTX_set_rsa_mgf1_md`]: https://www.openssl.org/docs/manmaster/man7/RSA-PSS.html
    pub fn set_rsa_mgf1_md(&mut self, md: MessageDigest) -> Result<(), ErrorStack> {
        unsafe {
            cvt(ffi::EVP_PKEY_CTX_set_rsa_mgf1_md(
                self.pctx,
                md.as_ptr() as *mut _,
            ))
            .map(|_| ())
        }
    }

    /// Feeds more data into the `Signer`.
    ///
    /// Please note that PureEdDSA (Ed25519 and Ed448 keys) do not support streaming.
    /// Use `sign_oneshot` instead.
    ///
    /// OpenSSL documentation at [`EVP_DigestUpdate`].
    ///
    /// [`EVP_DigestUpdate`]: https://www.openssl.org/docs/manmaster/man3/EVP_DigestInit.html
    pub fn update(&mut self, buf: &[u8]) -> Result<(), ErrorStack> {
        unsafe {
            cvt(ffi::EVP_DigestUpdate(
                self.md_ctx,
                buf.as_ptr() as *const _,
                buf.len(),
            ))
            .map(|_| ())
        }
    }

    /// Computes an upper bound on the signature length.
    ///
    /// The actual signature may be shorter than this value. Check the return value of
    /// `sign` to get the exact length.
    ///
    /// OpenSSL documentation at [`EVP_DigestSignFinal`].
    ///
    /// [`EVP_DigestSignFinal`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_DigestSignFinal.html
    pub fn len(&self) -> Result<usize, ErrorStack> {
        self.len_intern()
    }

    #[cfg(not(ossl111))]
    fn len_intern(&self) -> Result<usize, ErrorStack> {
        unsafe {
            let mut len = 0;
            cvt(ffi::EVP_DigestSignFinal(
                self.md_ctx,
                ptr::null_mut(),
                &mut len,
            ))?;
            Ok(len)
        }
    }

    #[cfg(ossl111)]
    fn len_intern(&self) -> Result<usize, ErrorStack> {
        unsafe {
            let mut len = 0;
            cvt(ffi::EVP_DigestSign(
                self.md_ctx,
                ptr::null_mut(),
                &mut len,
                ptr::null(),
                0,
            ))?;
            Ok(len)
        }
    }

    /// Writes the signature into the provided buffer, returning the number of bytes written.
    ///
    /// This method will fail if the buffer is not large enough for the signature. Use the `len`
    /// method to get an upper bound on the required size.
    ///
    /// OpenSSL documentation at [`EVP_DigestSignFinal`].
    ///
    /// [`EVP_DigestSignFinal`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_DigestSignFinal.html
    pub fn sign(&self, buf: &mut [u8]) -> Result<usize, ErrorStack> {
        unsafe {
            let mut len = buf.len();
            cvt(ffi::EVP_DigestSignFinal(
                self.md_ctx,
                buf.as_mut_ptr() as *mut _,
                &mut len,
            ))?;
            Ok(len)
        }
    }

    /// Returns the signature.
    ///
    /// This is a simple convenience wrapper over `len` and `sign`.
    pub fn sign_to_vec(&self) -> Result<Vec<u8>, ErrorStack> {
        let mut buf = vec![0; self.len()?];
        let len = self.sign(&mut buf)?;
        // The advertised length is not always equal to the real length for things like DSA
        buf.truncate(len);
        Ok(buf)
    }

    /// Signs the data in `data_buf` and writes the signature into the buffer `sig_buf`, returning the
    /// number of bytes written.
    ///
    /// For PureEdDSA (Ed25519 and Ed448 keys), this is the only way to sign data.
    ///
    /// This method will fail if the buffer is not large enough for the signature. Use the `len`
    /// method to get an upper bound on the required size.
    ///
    /// OpenSSL documentation at [`EVP_DigestSign`].
    ///
    /// [`EVP_DigestSign`]: https://www.openssl.org/docs/man1.1.1/man3/EVP_DigestSign.html
    #[cfg(ossl111)]
    pub fn sign_oneshot(
        &mut self,
        sig_buf: &mut [u8],
        data_buf: &[u8],
    ) -> Result<usize, ErrorStack> {
        unsafe {
            let mut sig_len = sig_buf.len();
            cvt(ffi::EVP_DigestSign(
                self.md_ctx,
                sig_buf.as_mut_ptr() as *mut _,
                &mut sig_len,
                data_buf.as_ptr() as *const _,
                data_buf.len(),
            ))?;
            Ok(sig_len)
        }
    }

    /// Returns the signature.
    ///
    /// This is a simple convenience wrapper over `len` and `sign_oneshot`.
    #[cfg(ossl111)]
    pub fn sign_oneshot_to_vec(&mut self, data_buf: &[u8]) -> Result<Vec<u8>, ErrorStack> {
        let mut sig_buf = vec![0; self.len()?];
        let len = self.sign_oneshot(&mut sig_buf, data_buf)?;
        // The advertised length is not always equal to the real length for things like DSA
        sig_buf.truncate(len);
        Ok(sig_buf)
    }
}

impl<'a> Write for Signer<'a> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.update(buf)?;
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

/// A type which can be used to verify the integrity and authenticity
/// of data given the signature.
pub struct Verifier<'a> {
    md_ctx: *mut ffi::EVP_MD_CTX,
    pctx: *mut ffi::EVP_PKEY_CTX,
    pkey_pd: PhantomData<&'a ()>,
}

unsafe impl<'a> Sync for Verifier<'a> {}
unsafe impl<'a> Send for Verifier<'a> {}

impl<'a> Drop for Verifier<'a> {
    fn drop(&mut self) {
        // pkey_ctx is owned by the md_ctx, so no need to explicitly free it.
        unsafe {
            EVP_MD_CTX_free(self.md_ctx);
        }
    }
}

/// A type which verifies cryptographic signatures of data.
impl<'a> Verifier<'a> {
    /// Creates a new `Verifier`.
    ///
    /// This cannot be used with Ed25519 or Ed448 keys. Please refer to
    /// [`Verifier::new_without_digest`].
    ///
    /// OpenSSL documentation at [`EVP_DigestVerifyInit`].
    ///
    /// [`EVP_DigestVerifyInit`]: https://www.openssl.org/docs/manmaster/man3/EVP_DigestVerifyInit.html
    pub fn new<T>(type_: MessageDigest, pkey: &'a PKeyRef<T>) -> Result<Verifier<'a>, ErrorStack>
    where
        T: HasPublic,
    {
        Verifier::new_intern(Some(type_), pkey)
    }

    /// Creates a new `Verifier` without a digest.
    ///
    /// This is the only way to create a `Verifier` for Ed25519 or Ed448 keys.
    ///
    /// OpenSSL documentation at [`EVP_DigestVerifyInit`].
    ///
    /// [`EVP_DigestVerifyInit`]: https://www.openssl.org/docs/manmaster/man3/EVP_DigestVerifyInit.html
    pub fn new_without_digest<T>(pkey: &'a PKeyRef<T>) -> Result<Verifier<'a>, ErrorStack>
    where
        T: HasPublic,
    {
        Verifier::new_intern(None, pkey)
    }

    fn new_intern<T>(
        type_: Option<MessageDigest>,
        pkey: &'a PKeyRef<T>,
    ) -> Result<Verifier<'a>, ErrorStack>
    where
        T: HasPublic,
    {
        unsafe {
            ffi::init();

            let ctx = cvt_p(EVP_MD_CTX_new())?;
            let mut pctx: *mut ffi::EVP_PKEY_CTX = ptr::null_mut();
            let r = ffi::EVP_DigestVerifyInit(
                ctx,
                &mut pctx,
                type_.map(|t| t.as_ptr()).unwrap_or(ptr::null()),
                ptr::null_mut(),
                pkey.as_ptr(),
            );
            if r != 1 {
                EVP_MD_CTX_free(ctx);
                return Err(ErrorStack::get());
            }

            assert!(!pctx.is_null());

            Ok(Verifier {
                md_ctx: ctx,
                pctx,
                pkey_pd: PhantomData,
            })
        }
    }

    /// Returns the RSA padding mode in use.
    ///
    /// This is only useful for RSA keys.
    ///
    /// This corresponds to `EVP_PKEY_CTX_get_rsa_padding`.
    pub fn rsa_padding(&self) -> Result<Padding, ErrorStack> {
        unsafe {
            let mut pad = 0;
            cvt(ffi::EVP_PKEY_CTX_get_rsa_padding(self.pctx, &mut pad))
                .map(|_| Padding::from_raw(pad))
        }
    }

Returns the integer representation of Padding.

Examples found in repository?
src/pkey_ctx.rs (line 362)
358
359
360
361
362
363
364
365
366
367
    pub fn set_rsa_padding(&mut self, padding: Padding) -> Result<(), ErrorStack> {
        unsafe {
            cvt(ffi::EVP_PKEY_CTX_set_rsa_padding(
                self.as_ptr(),
                padding.as_raw(),
            ))?;
        }

        Ok(())
    }
More examples
Hide additional examples
src/encrypt.rs (line 121)
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
    pub fn set_rsa_padding(&mut self, padding: Padding) -> Result<(), ErrorStack> {
        unsafe {
            cvt(ffi::EVP_PKEY_CTX_set_rsa_padding(
                self.pctx,
                padding.as_raw(),
            ))
            .map(|_| ())
        }
    }

    /// Sets the RSA MGF1 algorithm.
    ///
    /// This is only useful for RSA keys.
    ///
    /// This corresponds to [`EVP_PKEY_CTX_set_rsa_mgf1_md`].
    ///
    /// [`EVP_PKEY_CTX_set_rsa_mgf1_md`]: https://www.openssl.org/docs/manmaster/man7/RSA-PSS.html
    pub fn set_rsa_mgf1_md(&mut self, md: MessageDigest) -> Result<(), ErrorStack> {
        unsafe {
            cvt(ffi::EVP_PKEY_CTX_set_rsa_mgf1_md(
                self.pctx,
                md.as_ptr() as *mut _,
            ))
            .map(|_| ())
        }
    }

    /// Sets the RSA OAEP algorithm.
    ///
    /// This is only useful for RSA keys.
    ///
    /// This corresponds to [`EVP_PKEY_CTX_set_rsa_oaep_md`].
    ///
    /// [`EVP_PKEY_CTX_set_rsa_oaep_md`]: https://www.openssl.org/docs/manmaster/man3/EVP_PKEY_CTX_set_rsa_oaep_md.html
    #[cfg(any(ossl102, libressl310))]
    pub fn set_rsa_oaep_md(&mut self, md: MessageDigest) -> Result<(), ErrorStack> {
        unsafe {
            cvt(ffi::EVP_PKEY_CTX_set_rsa_oaep_md(
                self.pctx,
                md.as_ptr() as *mut _,
            ))
            .map(|_| ())
        }
    }

    /// Sets the RSA OAEP label.
    ///
    /// This is only useful for RSA keys.
    ///
    /// This corresponds to [`EVP_PKEY_CTX_set0_rsa_oaep_label`].
    ///
    /// [`EVP_PKEY_CTX_set0_rsa_oaep_label`]: https://www.openssl.org/docs/manmaster/man3/EVP_PKEY_CTX_set0_rsa_oaep_label.html
    #[cfg(any(ossl102, libressl310))]
    pub fn set_rsa_oaep_label(&mut self, label: &[u8]) -> Result<(), ErrorStack> {
        unsafe {
            let p = cvt_p(ffi::OPENSSL_malloc(label.len() as _))?;
            ptr::copy_nonoverlapping(label.as_ptr(), p as *mut u8, label.len());

            cvt(ffi::EVP_PKEY_CTX_set0_rsa_oaep_label(
                self.pctx,
                p as *mut c_void,
                label.len() as c_int,
            ))
            .map(|_| ())
            .map_err(|e| {
                ffi::OPENSSL_free(p);
                e
            })
        }
    }

    /// Performs public key encryption.
    ///
    /// In order to know the size needed for the output buffer, use [`encrypt_len`](Encrypter::encrypt_len).
    /// Note that the length of the output buffer can be greater of the length of the encoded data.
    /// ```
    /// # use openssl::{
    /// #   encrypt::Encrypter,
    /// #   pkey::PKey,
    /// #   rsa::{Rsa, Padding},
    /// # };
    /// #
    /// # let key = include_bytes!("../test/rsa.pem");
    /// # let private_key = Rsa::private_key_from_pem(key).unwrap();
    /// # let pkey = PKey::from_rsa(private_key).unwrap();
    /// # let input = b"hello world".to_vec();
    /// #
    /// let mut encrypter = Encrypter::new(&pkey).unwrap();
    /// encrypter.set_rsa_padding(Padding::PKCS1).unwrap();
    ///
    /// // Get the length of the output buffer
    /// let buffer_len = encrypter.encrypt_len(&input).unwrap();
    /// let mut encoded = vec![0u8; buffer_len];
    ///
    /// // Encode the data and get its length
    /// let encoded_len = encrypter.encrypt(&input, &mut encoded).unwrap();
    ///
    /// // Use only the part of the buffer with the encoded data
    /// let encoded = &encoded[..encoded_len];
    /// ```
    ///
    /// This corresponds to [`EVP_PKEY_encrypt`].
    ///
    /// [`EVP_PKEY_encrypt`]: https://www.openssl.org/docs/manmaster/man3/EVP_PKEY_encrypt.html
    pub fn encrypt(&self, from: &[u8], to: &mut [u8]) -> Result<usize, ErrorStack> {
        let mut written = to.len();
        unsafe {
            cvt(ffi::EVP_PKEY_encrypt(
                self.pctx,
                to.as_mut_ptr(),
                &mut written,
                from.as_ptr(),
                from.len(),
            ))?;
        }

        Ok(written)
    }

    /// Gets the size of the buffer needed to encrypt the input data.
    ///
    /// This corresponds to [`EVP_PKEY_encrypt`] called with a null pointer as output argument.
    ///
    /// [`EVP_PKEY_encrypt`]: https://www.openssl.org/docs/manmaster/man3/EVP_PKEY_encrypt.html
    pub fn encrypt_len(&self, from: &[u8]) -> Result<usize, ErrorStack> {
        let mut written = 0;
        unsafe {
            cvt(ffi::EVP_PKEY_encrypt(
                self.pctx,
                ptr::null_mut(),
                &mut written,
                from.as_ptr(),
                from.len(),
            ))?;
        }

        Ok(written)
    }
}

/// A type which decrypts data.
pub struct Decrypter<'a> {
    pctx: *mut ffi::EVP_PKEY_CTX,
    _p: PhantomData<&'a ()>,
}

unsafe impl<'a> Sync for Decrypter<'a> {}
unsafe impl<'a> Send for Decrypter<'a> {}

impl<'a> Drop for Decrypter<'a> {
    fn drop(&mut self) {
        unsafe {
            ffi::EVP_PKEY_CTX_free(self.pctx);
        }
    }
}

impl<'a> Decrypter<'a> {
    /// Creates a new `Decrypter`.
    ///
    /// OpenSSL documentation at [`EVP_PKEY_decrypt_init`].
    ///
    /// [`EVP_PKEY_decrypt_init`]: https://www.openssl.org/docs/manmaster/man3/EVP_PKEY_decrypt_init.html
    pub fn new<T>(pkey: &'a PKeyRef<T>) -> Result<Decrypter<'a>, ErrorStack>
    where
        T: HasPrivate,
    {
        unsafe {
            ffi::init();

            let pctx = cvt_p(ffi::EVP_PKEY_CTX_new(pkey.as_ptr(), ptr::null_mut()))?;
            let r = ffi::EVP_PKEY_decrypt_init(pctx);
            if r != 1 {
                ffi::EVP_PKEY_CTX_free(pctx);
                return Err(ErrorStack::get());
            }

            Ok(Decrypter {
                pctx,
                _p: PhantomData,
            })
        }
    }

    /// Returns the RSA padding mode in use.
    ///
    /// This is only useful for RSA keys.
    ///
    /// This corresponds to `EVP_PKEY_CTX_get_rsa_padding`.
    pub fn rsa_padding(&self) -> Result<Padding, ErrorStack> {
        unsafe {
            let mut pad = 0;
            cvt(ffi::EVP_PKEY_CTX_get_rsa_padding(self.pctx, &mut pad))
                .map(|_| Padding::from_raw(pad))
        }
    }

    /// Sets the RSA padding mode.
    ///
    /// This is only useful for RSA keys.
    ///
    /// This corresponds to [`EVP_PKEY_CTX_set_rsa_padding`].
    ///
    /// [`EVP_PKEY_CTX_set_rsa_padding`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_CTX_set_rsa_padding.html
    pub fn set_rsa_padding(&mut self, padding: Padding) -> Result<(), ErrorStack> {
        unsafe {
            cvt(ffi::EVP_PKEY_CTX_set_rsa_padding(
                self.pctx,
                padding.as_raw(),
            ))
            .map(|_| ())
        }
    }
src/sign.rs (line 222)
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
    pub fn set_rsa_padding(&mut self, padding: Padding) -> Result<(), ErrorStack> {
        unsafe {
            cvt(ffi::EVP_PKEY_CTX_set_rsa_padding(
                self.pctx,
                padding.as_raw(),
            ))
            .map(|_| ())
        }
    }

    /// Sets the RSA PSS salt length.
    ///
    /// This is only useful for RSA keys.
    ///
    /// This corresponds to [`EVP_PKEY_CTX_set_rsa_pss_saltlen`].
    ///
    /// [`EVP_PKEY_CTX_set_rsa_pss_saltlen`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_CTX_set_rsa_pss_saltlen.html
    pub fn set_rsa_pss_saltlen(&mut self, len: RsaPssSaltlen) -> Result<(), ErrorStack> {
        unsafe {
            cvt(ffi::EVP_PKEY_CTX_set_rsa_pss_saltlen(
                self.pctx,
                len.as_raw(),
            ))
            .map(|_| ())
        }
    }

    /// Sets the RSA MGF1 algorithm.
    ///
    /// This is only useful for RSA keys.
    ///
    /// This corresponds to [`EVP_PKEY_CTX_set_rsa_mgf1_md`].
    ///
    /// [`EVP_PKEY_CTX_set_rsa_mgf1_md`]: https://www.openssl.org/docs/manmaster/man7/RSA-PSS.html
    pub fn set_rsa_mgf1_md(&mut self, md: MessageDigest) -> Result<(), ErrorStack> {
        unsafe {
            cvt(ffi::EVP_PKEY_CTX_set_rsa_mgf1_md(
                self.pctx,
                md.as_ptr() as *mut _,
            ))
            .map(|_| ())
        }
    }

    /// Feeds more data into the `Signer`.
    ///
    /// Please note that PureEdDSA (Ed25519 and Ed448 keys) do not support streaming.
    /// Use `sign_oneshot` instead.
    ///
    /// OpenSSL documentation at [`EVP_DigestUpdate`].
    ///
    /// [`EVP_DigestUpdate`]: https://www.openssl.org/docs/manmaster/man3/EVP_DigestInit.html
    pub fn update(&mut self, buf: &[u8]) -> Result<(), ErrorStack> {
        unsafe {
            cvt(ffi::EVP_DigestUpdate(
                self.md_ctx,
                buf.as_ptr() as *const _,
                buf.len(),
            ))
            .map(|_| ())
        }
    }

    /// Computes an upper bound on the signature length.
    ///
    /// The actual signature may be shorter than this value. Check the return value of
    /// `sign` to get the exact length.
    ///
    /// OpenSSL documentation at [`EVP_DigestSignFinal`].
    ///
    /// [`EVP_DigestSignFinal`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_DigestSignFinal.html
    pub fn len(&self) -> Result<usize, ErrorStack> {
        self.len_intern()
    }

    #[cfg(not(ossl111))]
    fn len_intern(&self) -> Result<usize, ErrorStack> {
        unsafe {
            let mut len = 0;
            cvt(ffi::EVP_DigestSignFinal(
                self.md_ctx,
                ptr::null_mut(),
                &mut len,
            ))?;
            Ok(len)
        }
    }

    #[cfg(ossl111)]
    fn len_intern(&self) -> Result<usize, ErrorStack> {
        unsafe {
            let mut len = 0;
            cvt(ffi::EVP_DigestSign(
                self.md_ctx,
                ptr::null_mut(),
                &mut len,
                ptr::null(),
                0,
            ))?;
            Ok(len)
        }
    }

    /// Writes the signature into the provided buffer, returning the number of bytes written.
    ///
    /// This method will fail if the buffer is not large enough for the signature. Use the `len`
    /// method to get an upper bound on the required size.
    ///
    /// OpenSSL documentation at [`EVP_DigestSignFinal`].
    ///
    /// [`EVP_DigestSignFinal`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_DigestSignFinal.html
    pub fn sign(&self, buf: &mut [u8]) -> Result<usize, ErrorStack> {
        unsafe {
            let mut len = buf.len();
            cvt(ffi::EVP_DigestSignFinal(
                self.md_ctx,
                buf.as_mut_ptr() as *mut _,
                &mut len,
            ))?;
            Ok(len)
        }
    }

    /// Returns the signature.
    ///
    /// This is a simple convenience wrapper over `len` and `sign`.
    pub fn sign_to_vec(&self) -> Result<Vec<u8>, ErrorStack> {
        let mut buf = vec![0; self.len()?];
        let len = self.sign(&mut buf)?;
        // The advertised length is not always equal to the real length for things like DSA
        buf.truncate(len);
        Ok(buf)
    }

    /// Signs the data in `data_buf` and writes the signature into the buffer `sig_buf`, returning the
    /// number of bytes written.
    ///
    /// For PureEdDSA (Ed25519 and Ed448 keys), this is the only way to sign data.
    ///
    /// This method will fail if the buffer is not large enough for the signature. Use the `len`
    /// method to get an upper bound on the required size.
    ///
    /// OpenSSL documentation at [`EVP_DigestSign`].
    ///
    /// [`EVP_DigestSign`]: https://www.openssl.org/docs/man1.1.1/man3/EVP_DigestSign.html
    #[cfg(ossl111)]
    pub fn sign_oneshot(
        &mut self,
        sig_buf: &mut [u8],
        data_buf: &[u8],
    ) -> Result<usize, ErrorStack> {
        unsafe {
            let mut sig_len = sig_buf.len();
            cvt(ffi::EVP_DigestSign(
                self.md_ctx,
                sig_buf.as_mut_ptr() as *mut _,
                &mut sig_len,
                data_buf.as_ptr() as *const _,
                data_buf.len(),
            ))?;
            Ok(sig_len)
        }
    }

    /// Returns the signature.
    ///
    /// This is a simple convenience wrapper over `len` and `sign_oneshot`.
    #[cfg(ossl111)]
    pub fn sign_oneshot_to_vec(&mut self, data_buf: &[u8]) -> Result<Vec<u8>, ErrorStack> {
        let mut sig_buf = vec![0; self.len()?];
        let len = self.sign_oneshot(&mut sig_buf, data_buf)?;
        // The advertised length is not always equal to the real length for things like DSA
        sig_buf.truncate(len);
        Ok(sig_buf)
    }
}

impl<'a> Write for Signer<'a> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.update(buf)?;
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

/// A type which can be used to verify the integrity and authenticity
/// of data given the signature.
pub struct Verifier<'a> {
    md_ctx: *mut ffi::EVP_MD_CTX,
    pctx: *mut ffi::EVP_PKEY_CTX,
    pkey_pd: PhantomData<&'a ()>,
}

unsafe impl<'a> Sync for Verifier<'a> {}
unsafe impl<'a> Send for Verifier<'a> {}

impl<'a> Drop for Verifier<'a> {
    fn drop(&mut self) {
        // pkey_ctx is owned by the md_ctx, so no need to explicitly free it.
        unsafe {
            EVP_MD_CTX_free(self.md_ctx);
        }
    }
}

/// A type which verifies cryptographic signatures of data.
impl<'a> Verifier<'a> {
    /// Creates a new `Verifier`.
    ///
    /// This cannot be used with Ed25519 or Ed448 keys. Please refer to
    /// [`Verifier::new_without_digest`].
    ///
    /// OpenSSL documentation at [`EVP_DigestVerifyInit`].
    ///
    /// [`EVP_DigestVerifyInit`]: https://www.openssl.org/docs/manmaster/man3/EVP_DigestVerifyInit.html
    pub fn new<T>(type_: MessageDigest, pkey: &'a PKeyRef<T>) -> Result<Verifier<'a>, ErrorStack>
    where
        T: HasPublic,
    {
        Verifier::new_intern(Some(type_), pkey)
    }

    /// Creates a new `Verifier` without a digest.
    ///
    /// This is the only way to create a `Verifier` for Ed25519 or Ed448 keys.
    ///
    /// OpenSSL documentation at [`EVP_DigestVerifyInit`].
    ///
    /// [`EVP_DigestVerifyInit`]: https://www.openssl.org/docs/manmaster/man3/EVP_DigestVerifyInit.html
    pub fn new_without_digest<T>(pkey: &'a PKeyRef<T>) -> Result<Verifier<'a>, ErrorStack>
    where
        T: HasPublic,
    {
        Verifier::new_intern(None, pkey)
    }

    fn new_intern<T>(
        type_: Option<MessageDigest>,
        pkey: &'a PKeyRef<T>,
    ) -> Result<Verifier<'a>, ErrorStack>
    where
        T: HasPublic,
    {
        unsafe {
            ffi::init();

            let ctx = cvt_p(EVP_MD_CTX_new())?;
            let mut pctx: *mut ffi::EVP_PKEY_CTX = ptr::null_mut();
            let r = ffi::EVP_DigestVerifyInit(
                ctx,
                &mut pctx,
                type_.map(|t| t.as_ptr()).unwrap_or(ptr::null()),
                ptr::null_mut(),
                pkey.as_ptr(),
            );
            if r != 1 {
                EVP_MD_CTX_free(ctx);
                return Err(ErrorStack::get());
            }

            assert!(!pctx.is_null());

            Ok(Verifier {
                md_ctx: ctx,
                pctx,
                pkey_pd: PhantomData,
            })
        }
    }

    /// Returns the RSA padding mode in use.
    ///
    /// This is only useful for RSA keys.
    ///
    /// This corresponds to `EVP_PKEY_CTX_get_rsa_padding`.
    pub fn rsa_padding(&self) -> Result<Padding, ErrorStack> {
        unsafe {
            let mut pad = 0;
            cvt(ffi::EVP_PKEY_CTX_get_rsa_padding(self.pctx, &mut pad))
                .map(|_| Padding::from_raw(pad))
        }
    }

    /// Sets the RSA padding mode.
    ///
    /// This is only useful for RSA keys.
    ///
    /// This corresponds to [`EVP_PKEY_CTX_set_rsa_padding`].
    ///
    /// [`EVP_PKEY_CTX_set_rsa_padding`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_CTX_set_rsa_padding.html
    pub fn set_rsa_padding(&mut self, padding: Padding) -> Result<(), ErrorStack> {
        unsafe {
            cvt(ffi::EVP_PKEY_CTX_set_rsa_padding(
                self.pctx,
                padding.as_raw(),
            ))
            .map(|_| ())
        }
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.