boring_imp/
ec.rs

1//! Elliptic Curve
2//!
3//! Cryptology relies on the difficulty of solving mathematical problems, such as the factor
4//! of large integers composed of two large prime numbers and the discrete logarithm of a
5//! random eliptic curve.  This module provides low-level features of the latter.
6//! Elliptic Curve protocols can provide the same security with smaller keys.
7//!
8//! There are 2 forms of elliptic curves, `Fp` and `F2^m`.  These curves use irreducible
9//! trinomial or pentanomial .  Being a generic interface to a wide range of algorithms,
10//! the cuves are generally referenced by [`EcGroup`].  There are many built in groups
11//! found in [`Nid`].
12//!
13//! OpenSSL Wiki explains the fields and curves in detail at [Eliptic Curve Cryptography].
14//!
15//! [`EcGroup`]: struct.EcGroup.html
16//! [`Nid`]: ../nid/struct.Nid.html
17//! [Eliptic Curve Cryptography]: https://wiki.openssl.org/index.php/Elliptic_Curve_Cryptography
18use crate::ffi;
19use foreign_types::{ForeignType, ForeignTypeRef};
20use libc::c_int;
21use std::fmt;
22use std::ptr;
23
24use crate::bn::{BigNumContextRef, BigNumRef};
25use crate::error::ErrorStack;
26use crate::nid::Nid;
27use crate::pkey::{HasParams, HasPrivate, HasPublic, Params, Private, Public};
28use crate::{cvt, cvt_n, cvt_p, init};
29
30/// Compressed or Uncompressed conversion
31///
32/// Conversion from the binary value of the point on the curve is performed in one of
33/// compressed, uncompressed, or hybrid conversions.  The default is compressed, except
34/// for binary curves.
35///
36/// Further documentation is available in the [X9.62] standard.
37///
38/// [X9.62]: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.202.2977&rep=rep1&type=pdf
39#[derive(Copy, Clone)]
40pub struct PointConversionForm(ffi::point_conversion_form_t);
41
42impl PointConversionForm {
43    /// Compressed conversion from point value.
44    pub const COMPRESSED: PointConversionForm =
45        PointConversionForm(ffi::point_conversion_form_t::POINT_CONVERSION_COMPRESSED);
46
47    /// Uncompressed conversion from point value.
48    pub const UNCOMPRESSED: PointConversionForm =
49        PointConversionForm(ffi::point_conversion_form_t::POINT_CONVERSION_UNCOMPRESSED);
50
51    /// Performs both compressed and uncompressed conversions.
52    pub const HYBRID: PointConversionForm =
53        PointConversionForm(ffi::point_conversion_form_t::POINT_CONVERSION_HYBRID);
54}
55
56/// Named Curve or Explicit
57///
58/// This type acts as a boolean as to whether the `EcGroup` is named or explicit.
59#[derive(Copy, Clone)]
60pub struct Asn1Flag(c_int);
61
62impl Asn1Flag {
63    /// Curve defined using polynomial parameters
64    ///
65    /// Most applications use a named EC_GROUP curve, however, support
66    /// is included to explicitly define the curve used to calculate keys
67    /// This information would need to be known by both endpoint to make communication
68    /// effective.
69    ///
70    /// OPENSSL_EC_EXPLICIT_CURVE, but that was only added in 1.1.
71    /// Man page documents that 0 can be used in older versions.
72    ///
73    /// OpenSSL documentation at [`EC_GROUP`]
74    ///
75    /// [`EC_GROUP`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_get_seed_len.html
76    pub const EXPLICIT_CURVE: Asn1Flag = Asn1Flag(0);
77
78    /// Standard Curves
79    ///
80    /// Curves that make up the typical encryption use cases.  The collection of curves
81    /// are well known but extensible.
82    ///
83    /// OpenSSL documentation at [`EC_GROUP`]
84    ///
85    /// [`EC_GROUP`]: https://www.openssl.org/docs/manmaster/man3/EC_GROUP_order_bits.html
86    pub const NAMED_CURVE: Asn1Flag = Asn1Flag(ffi::OPENSSL_EC_NAMED_CURVE);
87}
88
89foreign_type_and_impl_send_sync! {
90    type CType = ffi::EC_GROUP;
91    fn drop = ffi::EC_GROUP_free;
92
93    /// Describes the curve
94    ///
95    /// A curve can be of the named curve type.  These curves can be discovered
96    /// using openssl binary `openssl ecparam -list_curves`.  Other operations
97    /// are available in the [wiki].  These named curves are available in the
98    /// [`Nid`] module.
99    ///
100    /// Curves can also be generated using prime field parameters or a binary field.
101    ///
102    /// Prime fields use the formula `y^2 mod p = x^3 + ax + b mod p`.  Binary
103    /// fields use the formula `y^2 + xy = x^3 + ax^2 + b`.  Named curves have
104    /// assured security.  To prevent accidental vulnerabilities, they should
105    /// be preferred.
106    ///
107    /// [wiki]: https://wiki.openssl.org/index.php/Command_Line_Elliptic_Curve_Operations
108    /// [`Nid`]: ../nid/index.html
109    pub struct EcGroup;
110}
111
112impl EcGroup {
113    /// Returns the group of a standard named curve.
114    ///
115    /// OpenSSL documentation at [`EC_GROUP_new`].
116    ///
117    /// [`EC_GROUP_new`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_new.html
118    pub fn from_curve_name(nid: Nid) -> Result<EcGroup, ErrorStack> {
119        unsafe {
120            init();
121            cvt_p(ffi::EC_GROUP_new_by_curve_name(nid.as_raw())).map(|p| EcGroup::from_ptr(p))
122        }
123    }
124}
125
126impl EcGroupRef {
127    /// Places the components of a curve over a prime field in the provided `BigNum`s.
128    /// The components make up the formula `y^2 mod p = x^3 + ax + b mod p`.
129    ///
130    /// OpenSSL documentation available at [`EC_GROUP_get_curve_GFp`]
131    ///
132    /// [`EC_GROUP_get_curve_GFp`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_get_curve_GFp.html
133    pub fn components_gfp(
134        &self,
135        p: &mut BigNumRef,
136        a: &mut BigNumRef,
137        b: &mut BigNumRef,
138        ctx: &mut BigNumContextRef,
139    ) -> Result<(), ErrorStack> {
140        unsafe {
141            cvt(ffi::EC_GROUP_get_curve_GFp(
142                self.as_ptr(),
143                p.as_ptr(),
144                a.as_ptr(),
145                b.as_ptr(),
146                ctx.as_ptr(),
147            ))
148            .map(|_| ())
149        }
150    }
151
152    /// Places the cofactor of the group in the provided `BigNum`.
153    ///
154    /// OpenSSL documentation at [`EC_GROUP_get_cofactor`]
155    ///
156    /// [`EC_GROUP_get_cofactor`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_get_cofactor.html
157    pub fn cofactor(
158        &self,
159        cofactor: &mut BigNumRef,
160        ctx: &mut BigNumContextRef,
161    ) -> Result<(), ErrorStack> {
162        unsafe {
163            cvt(ffi::EC_GROUP_get_cofactor(
164                self.as_ptr(),
165                cofactor.as_ptr(),
166                ctx.as_ptr(),
167            ))
168            .map(|_| ())
169        }
170    }
171
172    /// Returns the degree of the curve.
173    ///
174    /// OpenSSL documentation at [`EC_GROUP_get_degree`]
175    ///
176    /// [`EC_GROUP_get_degree`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_get_degree.html
177    #[allow(clippy::unnecessary_cast)]
178    pub fn degree(&self) -> u32 {
179        unsafe { ffi::EC_GROUP_get_degree(self.as_ptr()) as u32 }
180    }
181
182    /// Returns the number of bits in the group order.
183    ///
184    /// OpenSSL documentation at [`EC_GROUP_order_bits`]
185    ///
186    /// [`EC_GROUP_order_bits`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_order_bits.html
187    pub fn order_bits(&self) -> u32 {
188        unsafe { ffi::EC_GROUP_order_bits(self.as_ptr()) as u32 }
189    }
190
191    /// Returns the generator for the given curve as a [`EcPoint`].
192    ///
193    /// OpenSSL documentation at [`EC_GROUP_get0_generator`]
194    ///
195    /// [`EC_GROUP_get0_generator`]: https://www.openssl.org/docs/man1.1.0/man3/EC_GROUP_get0_generator.html
196    pub fn generator(&self) -> &EcPointRef {
197        unsafe {
198            let ptr = ffi::EC_GROUP_get0_generator(self.as_ptr());
199            EcPointRef::from_ptr(ptr as *mut _)
200        }
201    }
202
203    /// Places the order of the curve in the provided `BigNum`.
204    ///
205    /// OpenSSL documentation at [`EC_GROUP_get_order`]
206    ///
207    /// [`EC_GROUP_get_order`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_get_order.html
208    pub fn order(
209        &self,
210        order: &mut BigNumRef,
211        ctx: &mut BigNumContextRef,
212    ) -> Result<(), ErrorStack> {
213        unsafe {
214            cvt(ffi::EC_GROUP_get_order(
215                self.as_ptr(),
216                order.as_ptr(),
217                ctx.as_ptr(),
218            ))
219            .map(|_| ())
220        }
221    }
222
223    /// Sets the flag determining if the group corresponds to a named curve or must be explicitly
224    /// parameterized.
225    ///
226    /// This defaults to `EXPLICIT_CURVE` in OpenSSL 1.0.1 and 1.0.2, but `NAMED_CURVE` in OpenSSL
227    /// 1.1.0.
228    pub fn set_asn1_flag(&mut self, flag: Asn1Flag) {
229        unsafe {
230            ffi::EC_GROUP_set_asn1_flag(self.as_ptr(), flag.0);
231        }
232    }
233
234    /// Returns the name of the curve, if a name is associated.
235    ///
236    /// OpenSSL documentation at [`EC_GROUP_get_curve_name`]
237    ///
238    /// [`EC_GROUP_get_curve_name`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_get_curve_name.html
239    pub fn curve_name(&self) -> Option<Nid> {
240        let nid = unsafe { ffi::EC_GROUP_get_curve_name(self.as_ptr()) };
241        if nid > 0 {
242            Some(Nid::from_raw(nid))
243        } else {
244            None
245        }
246    }
247}
248
249foreign_type_and_impl_send_sync! {
250    type CType = ffi::EC_POINT;
251    fn drop = ffi::EC_POINT_free;
252
253    /// Represents a point on the curve
254    ///
255    /// OpenSSL documentation at [`EC_POINT_new`]
256    ///
257    /// [`EC_POINT_new`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_new.html
258    pub struct EcPoint;
259}
260
261impl EcPointRef {
262    /// Computes `a + b`, storing the result in `self`.
263    ///
264    /// OpenSSL documentation at [`EC_POINT_add`]
265    ///
266    /// [`EC_POINT_add`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_add.html
267    pub fn add(
268        &mut self,
269        group: &EcGroupRef,
270        a: &EcPointRef,
271        b: &EcPointRef,
272        ctx: &mut BigNumContextRef,
273    ) -> Result<(), ErrorStack> {
274        unsafe {
275            cvt(ffi::EC_POINT_add(
276                group.as_ptr(),
277                self.as_ptr(),
278                a.as_ptr(),
279                b.as_ptr(),
280                ctx.as_ptr(),
281            ))
282            .map(|_| ())
283        }
284    }
285
286    /// Computes `q * m`, storing the result in `self`.
287    ///
288    /// OpenSSL documentation at [`EC_POINT_mul`]
289    ///
290    /// [`EC_POINT_mul`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_mul.html
291    pub fn mul(
292        &mut self,
293        group: &EcGroupRef,
294        q: &EcPointRef,
295        m: &BigNumRef,
296        // FIXME should be &mut
297        ctx: &BigNumContextRef,
298    ) -> Result<(), ErrorStack> {
299        unsafe {
300            cvt(ffi::EC_POINT_mul(
301                group.as_ptr(),
302                self.as_ptr(),
303                ptr::null(),
304                q.as_ptr(),
305                m.as_ptr(),
306                ctx.as_ptr(),
307            ))
308            .map(|_| ())
309        }
310    }
311
312    /// Computes `generator * n`, storing the result in `self`.
313    pub fn mul_generator(
314        &mut self,
315        group: &EcGroupRef,
316        n: &BigNumRef,
317        // FIXME should be &mut
318        ctx: &BigNumContextRef,
319    ) -> Result<(), ErrorStack> {
320        unsafe {
321            cvt(ffi::EC_POINT_mul(
322                group.as_ptr(),
323                self.as_ptr(),
324                n.as_ptr(),
325                ptr::null(),
326                ptr::null(),
327                ctx.as_ptr(),
328            ))
329            .map(|_| ())
330        }
331    }
332
333    /// Computes `generator * n + q * m`, storing the result in `self`.
334    pub fn mul_full(
335        &mut self,
336        group: &EcGroupRef,
337        n: &BigNumRef,
338        q: &EcPointRef,
339        m: &BigNumRef,
340        ctx: &mut BigNumContextRef,
341    ) -> Result<(), ErrorStack> {
342        unsafe {
343            cvt(ffi::EC_POINT_mul(
344                group.as_ptr(),
345                self.as_ptr(),
346                n.as_ptr(),
347                q.as_ptr(),
348                m.as_ptr(),
349                ctx.as_ptr(),
350            ))
351            .map(|_| ())
352        }
353    }
354
355    /// Inverts `self`.
356    ///
357    /// OpenSSL documentation at [`EC_POINT_invert`]
358    ///
359    /// [`EC_POINT_invert`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_invert.html
360    pub fn invert(&mut self, group: &EcGroupRef, ctx: &BigNumContextRef) -> Result<(), ErrorStack> {
361        unsafe {
362            cvt(ffi::EC_POINT_invert(
363                group.as_ptr(),
364                self.as_ptr(),
365                ctx.as_ptr(),
366            ))
367            .map(|_| ())
368        }
369    }
370
371    /// Serializes the point to a binary representation.
372    ///
373    /// OpenSSL documentation at [`EC_POINT_point2oct`]
374    ///
375    /// [`EC_POINT_point2oct`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_point2oct.html
376    pub fn to_bytes(
377        &self,
378        group: &EcGroupRef,
379        form: PointConversionForm,
380        ctx: &mut BigNumContextRef,
381    ) -> Result<Vec<u8>, ErrorStack> {
382        unsafe {
383            let len = ffi::EC_POINT_point2oct(
384                group.as_ptr(),
385                self.as_ptr(),
386                form.0,
387                ptr::null_mut(),
388                0,
389                ctx.as_ptr(),
390            );
391            if len == 0 {
392                return Err(ErrorStack::get());
393            }
394            let mut buf = vec![0; len];
395            let len = ffi::EC_POINT_point2oct(
396                group.as_ptr(),
397                self.as_ptr(),
398                form.0,
399                buf.as_mut_ptr(),
400                len,
401                ctx.as_ptr(),
402            );
403            if len == 0 {
404                Err(ErrorStack::get())
405            } else {
406                Ok(buf)
407            }
408        }
409    }
410
411    /// Creates a new point on the specified curve with the same value.
412    ///
413    /// OpenSSL documentation at [`EC_POINT_dup`]
414    ///
415    /// [`EC_POINT_dup`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_dup.html
416    pub fn to_owned(&self, group: &EcGroupRef) -> Result<EcPoint, ErrorStack> {
417        unsafe {
418            cvt_p(ffi::EC_POINT_dup(self.as_ptr(), group.as_ptr())).map(|p| EcPoint::from_ptr(p))
419        }
420    }
421
422    /// Determines if this point is equal to another.
423    ///
424    /// OpenSSL doucmentation at [`EC_POINT_cmp`]
425    ///
426    /// [`EC_POINT_cmp`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_cmp.html
427    pub fn eq(
428        &self,
429        group: &EcGroupRef,
430        other: &EcPointRef,
431        ctx: &mut BigNumContextRef,
432    ) -> Result<bool, ErrorStack> {
433        unsafe {
434            let res = cvt_n(ffi::EC_POINT_cmp(
435                group.as_ptr(),
436                self.as_ptr(),
437                other.as_ptr(),
438                ctx.as_ptr(),
439            ))?;
440            Ok(res == 0)
441        }
442    }
443
444    /// Place affine coordinates of a curve over a prime field in the provided
445    /// `x` and `y` `BigNum`s
446    ///
447    /// OpenSSL documentation at [`EC_POINT_get_affine_coordinates_GFp`]
448    ///
449    /// [`EC_POINT_get_affine_coordinates_GFp`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_get_affine_coordinates_GFp.html
450    pub fn affine_coordinates_gfp(
451        &self,
452        group: &EcGroupRef,
453        x: &mut BigNumRef,
454        y: &mut BigNumRef,
455        ctx: &mut BigNumContextRef,
456    ) -> Result<(), ErrorStack> {
457        unsafe {
458            cvt(ffi::EC_POINT_get_affine_coordinates_GFp(
459                group.as_ptr(),
460                self.as_ptr(),
461                x.as_ptr(),
462                y.as_ptr(),
463                ctx.as_ptr(),
464            ))
465            .map(|_| ())
466        }
467    }
468}
469
470impl EcPoint {
471    /// Creates a new point on the specified curve.
472    ///
473    /// OpenSSL documentation at [`EC_POINT_new`]
474    ///
475    /// [`EC_POINT_new`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_new.html
476    pub fn new(group: &EcGroupRef) -> Result<EcPoint, ErrorStack> {
477        unsafe { cvt_p(ffi::EC_POINT_new(group.as_ptr())).map(|p| EcPoint::from_ptr(p)) }
478    }
479
480    /// Creates point from a binary representation
481    ///
482    /// OpenSSL documentation at [`EC_POINT_oct2point`]
483    ///
484    /// [`EC_POINT_oct2point`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_oct2point.html
485    pub fn from_bytes(
486        group: &EcGroupRef,
487        buf: &[u8],
488        ctx: &mut BigNumContextRef,
489    ) -> Result<EcPoint, ErrorStack> {
490        let point = EcPoint::new(group)?;
491        unsafe {
492            cvt(ffi::EC_POINT_oct2point(
493                group.as_ptr(),
494                point.as_ptr(),
495                buf.as_ptr(),
496                buf.len(),
497                ctx.as_ptr(),
498            ))?;
499        }
500        Ok(point)
501    }
502}
503
504generic_foreign_type_and_impl_send_sync! {
505    type CType = ffi::EC_KEY;
506    fn drop = ffi::EC_KEY_free;
507
508    /// Public and optional Private key on the given curve
509    ///
510    /// OpenSSL documentation at [`EC_KEY_new`]
511    ///
512    /// [`EC_KEY_new`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_new.html
513    pub struct EcKey<T>;
514
515    /// Reference to [`EcKey`]
516    ///
517    /// [`EcKey`]: struct.EcKey.html
518    pub struct EcKeyRef<T>;
519}
520
521impl<T> EcKeyRef<T>
522where
523    T: HasPrivate,
524{
525    private_key_to_pem! {
526        /// Serializes the private key to a PEM-encoded ECPrivateKey structure.
527        ///
528        /// The output will have a header of `-----BEGIN EC PRIVATE KEY-----`.
529        ///
530        /// This corresponds to [`PEM_write_bio_ECPrivateKey`].
531        ///
532        /// [`PEM_write_bio_ECPrivateKey`]: https://www.openssl.org/docs/man1.1.0/crypto/PEM_write_bio_ECPrivateKey.html
533        private_key_to_pem,
534        /// Serializes the private key to a PEM-encoded encrypted ECPrivateKey structure.
535        ///
536        /// The output will have a header of `-----BEGIN EC PRIVATE KEY-----`.
537        ///
538        /// This corresponds to [`PEM_write_bio_ECPrivateKey`].
539        ///
540        /// [`PEM_write_bio_ECPrivateKey`]: https://www.openssl.org/docs/man1.1.0/crypto/PEM_write_bio_ECPrivateKey.html
541        private_key_to_pem_passphrase,
542        ffi::PEM_write_bio_ECPrivateKey
543    }
544
545    to_der! {
546        /// Serializes the private key into a DER-encoded ECPrivateKey structure.
547        ///
548        /// This corresponds to [`i2d_ECPrivateKey`].
549        ///
550        /// [`i2d_ECPrivateKey`]: https://www.openssl.org/docs/man1.0.2/crypto/d2i_ECPrivate_key.html
551        private_key_to_der,
552        ffi::i2d_ECPrivateKey
553    }
554
555    /// Return [`EcPoint`] associated with the private key
556    ///
557    /// OpenSSL documentation at [`EC_KEY_get0_private_key`]
558    ///
559    /// [`EC_KEY_get0_private_key`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_get0_private_key.html
560    pub fn private_key(&self) -> &BigNumRef {
561        unsafe {
562            let ptr = ffi::EC_KEY_get0_private_key(self.as_ptr());
563            BigNumRef::from_ptr(ptr as *mut _)
564        }
565    }
566}
567
568impl<T> EcKeyRef<T>
569where
570    T: HasPublic,
571{
572    /// Returns the public key.
573    ///
574    /// OpenSSL documentation at [`EC_KEY_get0_public_key`]
575    ///
576    /// [`EC_KEY_get0_public_key`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_get0_public_key.html
577    pub fn public_key(&self) -> &EcPointRef {
578        unsafe {
579            let ptr = ffi::EC_KEY_get0_public_key(self.as_ptr());
580            EcPointRef::from_ptr(ptr as *mut _)
581        }
582    }
583
584    to_pem! {
585        /// Serialies the public key into a PEM-encoded SubjectPublicKeyInfo structure.
586        ///
587        /// The output will have a header of `-----BEGIN PUBLIC KEY-----`.
588        ///
589        /// This corresponds to [`PEM_write_bio_EC_PUBKEY`].
590        ///
591        /// [`PEM_write_bio_EC_PUBKEY`]: https://www.openssl.org/docs/man1.1.0/crypto/PEM_write_bio_EC_PUBKEY.html
592        public_key_to_pem,
593        ffi::PEM_write_bio_EC_PUBKEY
594    }
595
596    to_der! {
597        /// Serializes the public key into a DER-encoded SubjectPublicKeyInfo structure.
598        ///
599        /// This corresponds to [`i2d_EC_PUBKEY`].
600        ///
601        /// [`i2d_EC_PUBKEY`]: https://www.openssl.org/docs/man1.1.0/crypto/i2d_EC_PUBKEY.html
602        public_key_to_der,
603        ffi::i2d_EC_PUBKEY
604    }
605}
606
607impl<T> EcKeyRef<T>
608where
609    T: HasParams,
610{
611    /// Return [`EcGroup`] of the `EcKey`
612    ///
613    /// OpenSSL documentation at [`EC_KEY_get0_group`]
614    ///
615    /// [`EC_KEY_get0_group`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_get0_group.html
616    pub fn group(&self) -> &EcGroupRef {
617        unsafe {
618            let ptr = ffi::EC_KEY_get0_group(self.as_ptr());
619            EcGroupRef::from_ptr(ptr as *mut _)
620        }
621    }
622
623    /// Checks the key for validity.
624    ///
625    /// OpenSSL documentation at [`EC_KEY_check_key`]
626    ///
627    /// [`EC_KEY_check_key`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_check_key.html
628    pub fn check_key(&self) -> Result<(), ErrorStack> {
629        unsafe { cvt(ffi::EC_KEY_check_key(self.as_ptr())).map(|_| ()) }
630    }
631}
632
633impl<T> ToOwned for EcKeyRef<T> {
634    type Owned = EcKey<T>;
635
636    fn to_owned(&self) -> EcKey<T> {
637        unsafe {
638            let r = ffi::EC_KEY_up_ref(self.as_ptr());
639            assert!(r == 1);
640            EcKey::from_ptr(self.as_ptr())
641        }
642    }
643}
644
645impl EcKey<Params> {
646    /// Constructs an `EcKey` corresponding to a known curve.
647    ///
648    /// It will not have an associated public or private key. This kind of key is primarily useful
649    /// to be provided to the `set_tmp_ecdh` methods on `Ssl` and `SslContextBuilder`.
650    ///
651    /// OpenSSL documentation at [`EC_KEY_new_by_curve_name`]
652    ///
653    /// [`EC_KEY_new_by_curve_name`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_new_by_curve_name.html
654    pub fn from_curve_name(nid: Nid) -> Result<EcKey<Params>, ErrorStack> {
655        unsafe {
656            init();
657            cvt_p(ffi::EC_KEY_new_by_curve_name(nid.as_raw())).map(|p| EcKey::from_ptr(p))
658        }
659    }
660
661    /// Constructs an `EcKey` corresponding to a curve.
662    ///
663    /// This corresponds to [`EC_KEY_set_group`].
664    ///
665    /// [`EC_KEY_set_group`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_new.html
666    pub fn from_group(group: &EcGroupRef) -> Result<EcKey<Params>, ErrorStack> {
667        unsafe {
668            cvt_p(ffi::EC_KEY_new())
669                .map(|p| EcKey::from_ptr(p))
670                .and_then(|key| {
671                    cvt(ffi::EC_KEY_set_group(key.as_ptr(), group.as_ptr())).map(|_| key)
672                })
673        }
674    }
675}
676
677impl EcKey<Public> {
678    /// Constructs an `EcKey` from the specified group with the associated `EcPoint`, public_key.
679    ///
680    /// This will only have the associated public_key.
681    ///
682    /// # Example
683    ///
684    /// ```no_run
685    /// use boring::bn::BigNumContext;
686    /// use boring::ec::*;
687    /// use boring::nid::Nid;
688    /// use boring::pkey::PKey;
689    ///
690    /// // get bytes from somewhere, i.e. this will not produce a valid key
691    /// let public_key: Vec<u8> = vec![];
692    ///
693    /// // create an EcKey from the binary form of a EcPoint
694    /// let group = EcGroup::from_curve_name(Nid::SECP256K1).unwrap();
695    /// let mut ctx = BigNumContext::new().unwrap();
696    /// let point = EcPoint::from_bytes(&group, &public_key, &mut ctx).unwrap();
697    /// let key = EcKey::from_public_key(&group, &point);
698    /// ```
699    pub fn from_public_key(
700        group: &EcGroupRef,
701        public_key: &EcPointRef,
702    ) -> Result<EcKey<Public>, ErrorStack> {
703        unsafe {
704            cvt_p(ffi::EC_KEY_new())
705                .map(|p| EcKey::from_ptr(p))
706                .and_then(|key| {
707                    cvt(ffi::EC_KEY_set_group(key.as_ptr(), group.as_ptr())).map(|_| key)
708                })
709                .and_then(|key| {
710                    cvt(ffi::EC_KEY_set_public_key(
711                        key.as_ptr(),
712                        public_key.as_ptr(),
713                    ))
714                    .map(|_| key)
715                })
716        }
717    }
718
719    /// Constructs a public key from its affine coordinates.
720    pub fn from_public_key_affine_coordinates(
721        group: &EcGroupRef,
722        x: &BigNumRef,
723        y: &BigNumRef,
724    ) -> Result<EcKey<Public>, ErrorStack> {
725        unsafe {
726            cvt_p(ffi::EC_KEY_new())
727                .map(|p| EcKey::from_ptr(p))
728                .and_then(|key| {
729                    cvt(ffi::EC_KEY_set_group(key.as_ptr(), group.as_ptr())).map(|_| key)
730                })
731                .and_then(|key| {
732                    cvt(ffi::EC_KEY_set_public_key_affine_coordinates(
733                        key.as_ptr(),
734                        x.as_ptr(),
735                        y.as_ptr(),
736                    ))
737                    .map(|_| key)
738                })
739        }
740    }
741
742    from_pem! {
743        /// Decodes a PEM-encoded SubjectPublicKeyInfo structure containing a EC key.
744        ///
745        /// The input should have a header of `-----BEGIN PUBLIC KEY-----`.
746        ///
747        /// This corresponds to [`PEM_read_bio_EC_PUBKEY`].
748        ///
749        /// [`PEM_read_bio_EC_PUBKEY`]: https://www.openssl.org/docs/man1.1.0/crypto/PEM_read_bio_EC_PUBKEY.html
750        public_key_from_pem,
751        EcKey<Public>,
752        ffi::PEM_read_bio_EC_PUBKEY
753    }
754
755    from_der! {
756        /// Decodes a DER-encoded SubjectPublicKeyInfo structure containing a EC key.
757        ///
758        /// This corresponds to [`d2i_EC_PUBKEY`].
759        ///
760        /// [`d2i_EC_PUBKEY`]: https://www.openssl.org/docs/man1.1.0/crypto/d2i_EC_PUBKEY.html
761        public_key_from_der,
762        EcKey<Public>,
763        ffi::d2i_EC_PUBKEY,
764        ::libc::c_long
765    }
766}
767
768impl EcKey<Private> {
769    /// Generates a new public/private key pair on the specified curve.
770    pub fn generate(group: &EcGroupRef) -> Result<EcKey<Private>, ErrorStack> {
771        unsafe {
772            cvt_p(ffi::EC_KEY_new())
773                .map(|p| EcKey::from_ptr(p))
774                .and_then(|key| {
775                    cvt(ffi::EC_KEY_set_group(key.as_ptr(), group.as_ptr())).map(|_| key)
776                })
777                .and_then(|key| cvt(ffi::EC_KEY_generate_key(key.as_ptr())).map(|_| key))
778        }
779    }
780
781    /// Constructs an public/private key pair given a curve, a private key and a public key point.
782    pub fn from_private_components(
783        group: &EcGroupRef,
784        private_number: &BigNumRef,
785        public_key: &EcPointRef,
786    ) -> Result<EcKey<Private>, ErrorStack> {
787        unsafe {
788            cvt_p(ffi::EC_KEY_new())
789                .map(|p| EcKey::from_ptr(p))
790                .and_then(|key| {
791                    cvt(ffi::EC_KEY_set_group(key.as_ptr(), group.as_ptr())).map(|_| key)
792                })
793                .and_then(|key| {
794                    cvt(ffi::EC_KEY_set_private_key(
795                        key.as_ptr(),
796                        private_number.as_ptr(),
797                    ))
798                    .map(|_| key)
799                })
800                .and_then(|key| {
801                    cvt(ffi::EC_KEY_set_public_key(
802                        key.as_ptr(),
803                        public_key.as_ptr(),
804                    ))
805                    .map(|_| key)
806                })
807        }
808    }
809
810    private_key_from_pem! {
811        /// Deserializes a private key from a PEM-encoded ECPrivateKey structure.
812        ///
813        /// The input should have a header of `-----BEGIN EC PRIVATE KEY-----`.
814        ///
815        /// This corresponds to `PEM_read_bio_ECPrivateKey`.
816        private_key_from_pem,
817
818        /// Deserializes a private key from a PEM-encoded encrypted ECPrivateKey structure.
819        ///
820        /// The input should have a header of `-----BEGIN EC PRIVATE KEY-----`.
821        ///
822        /// This corresponds to `PEM_read_bio_ECPrivateKey`.
823        private_key_from_pem_passphrase,
824
825        /// Deserializes a private key from a PEM-encoded encrypted ECPrivateKey structure.
826        ///
827        /// The callback should fill the password into the provided buffer and return its length.
828        ///
829        /// The input should have a header of `-----BEGIN EC PRIVATE KEY-----`.
830        ///
831        /// This corresponds to `PEM_read_bio_ECPrivateKey`.
832        private_key_from_pem_callback,
833        EcKey<Private>,
834        ffi::PEM_read_bio_ECPrivateKey
835    }
836
837    from_der! {
838        /// Decodes a DER-encoded elliptic curve private key structure.
839        ///
840        /// This corresponds to [`d2i_ECPrivateKey`].
841        ///
842        /// [`d2i_ECPrivateKey`]: https://www.openssl.org/docs/man1.0.2/crypto/d2i_ECPrivate_key.html
843        private_key_from_der,
844        EcKey<Private>,
845        ffi::d2i_ECPrivateKey,
846        ::libc::c_long
847    }
848}
849
850impl<T> Clone for EcKey<T> {
851    fn clone(&self) -> EcKey<T> {
852        (**self).to_owned()
853    }
854}
855
856impl<T> fmt::Debug for EcKey<T> {
857    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
858        write!(f, "EcKey")
859    }
860}
861
862#[cfg(test)]
863mod test {
864    use hex::FromHex;
865
866    use super::*;
867    use crate::bn::{BigNum, BigNumContext};
868    use crate::nid::Nid;
869
870    #[test]
871    fn key_new_by_curve_name() {
872        EcKey::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
873    }
874
875    #[test]
876    fn generate() {
877        let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
878        EcKey::generate(&group).unwrap();
879    }
880
881    #[test]
882    fn cofactor() {
883        let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
884        let mut ctx = BigNumContext::new().unwrap();
885        let mut cofactor = BigNum::new().unwrap();
886        group.cofactor(&mut cofactor, &mut ctx).unwrap();
887        let one = BigNum::from_u32(1).unwrap();
888        assert_eq!(cofactor, one);
889    }
890
891    #[test]
892    #[allow(clippy::redundant_clone)]
893    fn dup() {
894        let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
895        let key = EcKey::generate(&group).unwrap();
896        drop(key.clone());
897    }
898
899    #[test]
900    fn point_new() {
901        let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
902        EcPoint::new(&group).unwrap();
903    }
904
905    #[test]
906    fn point_bytes() {
907        let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
908        let key = EcKey::generate(&group).unwrap();
909        let point = key.public_key();
910        let mut ctx = BigNumContext::new().unwrap();
911        let bytes = point
912            .to_bytes(&group, PointConversionForm::COMPRESSED, &mut ctx)
913            .unwrap();
914        let point2 = EcPoint::from_bytes(&group, &bytes, &mut ctx).unwrap();
915        assert!(point.eq(&group, &point2, &mut ctx).unwrap());
916    }
917
918    #[test]
919    fn point_owned() {
920        let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
921        let key = EcKey::generate(&group).unwrap();
922        let point = key.public_key();
923        let owned = point.to_owned(&group).unwrap();
924        let mut ctx = BigNumContext::new().unwrap();
925        assert!(owned.eq(&group, point, &mut ctx).unwrap());
926    }
927
928    #[test]
929    fn mul_generator() {
930        let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
931        let key = EcKey::generate(&group).unwrap();
932        let mut ctx = BigNumContext::new().unwrap();
933        let mut public_key = EcPoint::new(&group).unwrap();
934        public_key
935            .mul_generator(&group, key.private_key(), &ctx)
936            .unwrap();
937        assert!(public_key.eq(&group, key.public_key(), &mut ctx).unwrap());
938    }
939
940    #[test]
941    fn generator() {
942        let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
943        let gen = group.generator();
944        let one = BigNum::from_u32(1).unwrap();
945        let mut ctx = BigNumContext::new().unwrap();
946        let mut ecp = EcPoint::new(&group).unwrap();
947        ecp.mul_generator(&group, &one, &ctx).unwrap();
948        assert!(ecp.eq(&group, gen, &mut ctx).unwrap());
949    }
950
951    #[test]
952    fn key_from_public_key() {
953        let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
954        let key = EcKey::generate(&group).unwrap();
955        let mut ctx = BigNumContext::new().unwrap();
956        let bytes = key
957            .public_key()
958            .to_bytes(&group, PointConversionForm::COMPRESSED, &mut ctx)
959            .unwrap();
960
961        drop(key);
962        let public_key = EcPoint::from_bytes(&group, &bytes, &mut ctx).unwrap();
963        let ec_key = EcKey::from_public_key(&group, &public_key).unwrap();
964        assert!(ec_key.check_key().is_ok());
965    }
966
967    #[test]
968    fn key_from_private_components() {
969        let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
970        let key = EcKey::generate(&group).unwrap();
971
972        let dup_key =
973            EcKey::from_private_components(&group, key.private_key(), key.public_key()).unwrap();
974        dup_key.check_key().unwrap();
975
976        assert!(key.private_key() == dup_key.private_key());
977    }
978
979    #[test]
980    fn key_from_affine_coordinates() {
981        let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
982        let x = Vec::from_hex("30a0424cd21c2944838a2d75c92b37e76ea20d9f00893a3b4eee8a3c0aafec3e")
983            .unwrap();
984        let y = Vec::from_hex("e04b65e92456d9888b52b379bdfbd51ee869ef1f0fc65b6659695b6cce081723")
985            .unwrap();
986
987        let xbn = BigNum::from_slice(&x).unwrap();
988        let ybn = BigNum::from_slice(&y).unwrap();
989
990        let ec_key = EcKey::from_public_key_affine_coordinates(&group, &xbn, &ybn).unwrap();
991        assert!(ec_key.check_key().is_ok());
992    }
993
994    #[test]
995    fn get_affine_coordinates() {
996        let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
997        let x = Vec::from_hex("30a0424cd21c2944838a2d75c92b37e76ea20d9f00893a3b4eee8a3c0aafec3e")
998            .unwrap();
999        let y = Vec::from_hex("e04b65e92456d9888b52b379bdfbd51ee869ef1f0fc65b6659695b6cce081723")
1000            .unwrap();
1001
1002        let xbn = BigNum::from_slice(&x).unwrap();
1003        let ybn = BigNum::from_slice(&y).unwrap();
1004
1005        let ec_key = EcKey::from_public_key_affine_coordinates(&group, &xbn, &ybn).unwrap();
1006
1007        let mut xbn2 = BigNum::new().unwrap();
1008        let mut ybn2 = BigNum::new().unwrap();
1009        let mut ctx = BigNumContext::new().unwrap();
1010        let ec_key_pk = ec_key.public_key();
1011        ec_key_pk
1012            .affine_coordinates_gfp(&group, &mut xbn2, &mut ybn2, &mut ctx)
1013            .unwrap();
1014        assert_eq!(xbn2, xbn);
1015        assert_eq!(ybn2, ybn);
1016    }
1017}