1use crate::ffi;
4use foreign_types::{ForeignType, ForeignTypeRef};
5use libc::c_int;
6use openssl_macros::corresponds;
7use std::mem;
8use std::ptr;
9
10use crate::bn::{BigNum, BigNumRef};
11use crate::ec::EcKeyRef;
12use crate::error::ErrorStack;
13use crate::pkey::{HasPrivate, HasPublic};
14use crate::{cvt_n, cvt_p};
15
16foreign_type_and_impl_send_sync! {
17 type CType = ffi::ECDSA_SIG;
18 fn drop = ffi::ECDSA_SIG_free;
19
20 pub struct EcdsaSig;
26}
27
28impl EcdsaSig {
29 #[corresponds(ECDSA_do_sign)]
31 pub fn sign<T>(data: &[u8], eckey: &EcKeyRef<T>) -> Result<EcdsaSig, ErrorStack>
32 where
33 T: HasPrivate,
34 {
35 unsafe {
36 assert!(data.len() <= c_int::MAX as usize);
37 let sig = cvt_p(ffi::ECDSA_do_sign(
38 data.as_ptr(),
39 data.len(),
40 eckey.as_ptr(),
41 ))?;
42 Ok(EcdsaSig::from_ptr(sig))
43 }
44 }
45
46 #[corresponds(ECDSA_SIG_set0)]
49 pub fn from_private_components(r: BigNum, s: BigNum) -> Result<EcdsaSig, ErrorStack> {
50 unsafe {
51 let sig = cvt_p(ffi::ECDSA_SIG_new())?;
52 ECDSA_SIG_set0(sig, r.as_ptr(), s.as_ptr());
53 mem::forget((r, s));
54 Ok(EcdsaSig::from_ptr(sig))
55 }
56 }
57
58 from_der! {
59 #[corresponds(d2i_ECDSA_SIG)]
61 from_der,
62 EcdsaSig,
63 ffi::d2i_ECDSA_SIG,
64 ::libc::c_long
65 }
66}
67
68impl EcdsaSigRef {
69 to_der! {
70 #[corresponds(i2d_ECDSA_SIG)]
72 to_der,
73 ffi::i2d_ECDSA_SIG
74 }
75
76 #[corresponds(ECDSA_do_verify)]
78 pub fn verify<T>(&self, data: &[u8], eckey: &EcKeyRef<T>) -> Result<bool, ErrorStack>
79 where
80 T: HasPublic,
81 {
82 unsafe {
83 assert!(data.len() <= c_int::MAX as usize);
84 cvt_n(ffi::ECDSA_do_verify(
85 data.as_ptr(),
86 data.len(),
87 self.as_ptr(),
88 eckey.as_ptr(),
89 ))
90 .map(|x| x == 1)
91 }
92 }
93
94 #[corresponds(ECDSA_SIG_get0)]
96 #[must_use]
97 pub fn r(&self) -> &BigNumRef {
98 unsafe {
99 let mut r = ptr::null();
100 ECDSA_SIG_get0(self.as_ptr(), &mut r, ptr::null_mut());
101 BigNumRef::from_ptr(r.cast_mut())
102 }
103 }
104
105 #[corresponds(ECDSA_SIG_get0)]
107 #[must_use]
108 pub fn s(&self) -> &BigNumRef {
109 unsafe {
110 let mut s = ptr::null();
111 ECDSA_SIG_get0(self.as_ptr(), ptr::null_mut(), &mut s);
112 BigNumRef::from_ptr(s.cast_mut())
113 }
114 }
115}
116
117use crate::ffi::{ECDSA_SIG_get0, ECDSA_SIG_set0};