Debian Codegraph @

third_party/rust/nss-gk-api/src/ec.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 use crate::{der, PR_FALSE};
8 use crate::err::{secstatus_to_res, Error, IntoResult};
9 use crate::init;
10
11 use crate::p11::PK11ObjectType::PK11_TypePrivKey;
12 use crate::p11::PK11_ExportDERPrivateKeyInfo;
13 use crate::p11::PK11_GenerateKeyPair;
14 use crate::p11::PK11_ImportDERPrivateKeyInfoAndReturnKey;
15 use crate::p11::PK11_PubDeriveWithKDF;
16 use crate::p11::PK11_ReadRawAttribute;
17 use crate::p11::PK11_ImportPublicKey;
18 use crate::p11::SECKEY_DecodeDERSubjectPublicKeyInfo;
19 use crate::p11::Slot;
20 use crate::p11::KU_ALL;
21
22 use crate::util::SECItemMut;
23
24 use crate::PrivateKey;
25 use crate::PublicKey;
26 use crate::SECItem;
27 use crate::SECItemBorrowed;
28
29 use pkcs11_bindings::CKA_VALUE;
30 use pkcs11_bindings::CKM_EC_EDWARDS_KEY_PAIR_GEN;
31 use pkcs11_bindings::CKM_EC_KEY_PAIR_GEN;
32 use pkcs11_bindings::CKM_EC_MONTGOMERY_KEY_PAIR_GEN;
33 use pkcs11_bindings::CK_FALSE;
34
35 use std::ptr;
36 //
37 // Constants
38 //
39
40 #[derive(Clone, Debug, Eq, PartialEq)]
41 pub enum EcCurve {
42 P256,
43 P384,
44 P521,
45 X25519,
46 Ed25519,
47 }
48
49 pub type EcdhPublicKey = PublicKey;
50 pub type EcdhPrivateKey = PrivateKey;
51
52 pub struct EcdhKeypair {
53 pub public: EcdhPublicKey,
54 pub private: EcdhPrivateKey,
55 }
56
57 #[derive(Clone, Debug, Eq, PartialEq)]
58 pub struct Ecdh(EcCurve);
59
60 impl Ecdh {
61 pub fn new(&self, curve: EcCurve) -> Self {
62 Self(curve)
63 }
64
65 pub fn generate_keypair(&self, curve: EcCurve) -> Result<EcdhKeypair, crate::Error> {
66 return ecdh_keygen(curve);
67 }
68 }
69
70 // Object identifiers in DER tag-length-value form
71 pub const OID_EC_PUBLIC_KEY_BYTES: &[u8] = &[
72 /* RFC 5480 (id-ecPublicKey) */
73 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01,
74 ];
75 pub const OID_SECP256R1_BYTES: &[u8] = &[
76 /* RFC 5480 (secp256r1) */
77 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07,
78 ];
79 pub const OID_SECP384R1_BYTES: &[u8] = &[
80 /* RFC 5480 (secp384r1) */
81 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x34,
82 ];
83 pub const OID_SECP521R1_BYTES: &[u8] = &[
84 /* RFC 5480 (secp521r1) */
85 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x35,
86 ];
87
88 pub const OID_ED25519_BYTES: &[u8] = &[/* RFC 8410 (id-ed25519) */ 0x2b, 0x65, 0x70];
89 pub const OID_RS256_BYTES: &[u8] = &[
90 /* RFC 4055 (sha256WithRSAEncryption) */
91 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b,
92 ];
93
94 pub const OID_X25519_BYTES: &[u8] = &[
95 /* https://tools.ietf.org/html/draft-josefsson-pkix-newcurves-01
96 * 1.3.6.1.4.1.11591.15.1 */
97 0x2b, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01,
98 ];
99
100 pub fn object_id(val: &[u8]) -> Result<Vec<u8>, Error> {
101 let mut out = Vec::with_capacity(der::MAX_TAG_AND_LENGTH_BYTES + val.len());
102 der::write_tag_and_length(&mut out, der::TAG_OBJECT_ID, val.len())?;
103 out.extend_from_slice(val);
104 Ok(out)
105 }
106
107 fn ec_curve_to_oid(alg: &EcCurve) -> Result<Vec<u8>, Error> {
108 match alg {
109 EcCurve::X25519 => Ok(OID_X25519_BYTES.to_vec()),
110 EcCurve::Ed25519 => Ok(OID_ED25519_BYTES.to_vec()),
111 EcCurve::P256 => Ok(OID_SECP256R1_BYTES.to_vec()),
112 EcCurve::P384 => Ok(OID_SECP384R1_BYTES.to_vec()),
113 EcCurve::P521 => Ok(OID_SECP521R1_BYTES.to_vec()),
114 }
115 }
116
117 fn ec_curve_to_ckm(alg: &EcCurve) -> pkcs11_bindings::CK_MECHANISM_TYPE {
118 match alg {
119 EcCurve::P256 | EcCurve::P384 | EcCurve::P521 => CKM_EC_KEY_PAIR_GEN.into(),
120 EcCurve::Ed25519 => CKM_EC_EDWARDS_KEY_PAIR_GEN.into(),
121 EcCurve::X25519 => CKM_EC_MONTGOMERY_KEY_PAIR_GEN.into(),
122 }
123 }
124
125 //
126 // Curve functions
127 //
128
129 pub fn ecdh_keygen(curve: EcCurve) -> Result<EcdhKeypair, crate::Error> {
130 init();
131
132 // Get the OID for the Curve
133 let curve_oid = ec_curve_to_oid(&curve)?;
134 let oid_bytes = object_id(&curve_oid)?;
135 let mut oid = SECItemBorrowed::wrap(&oid_bytes);
136 let oid_ptr: *mut SECItem = oid.as_mut();
137
138 // Get the Mechanism based on the Curve and its use
139 let ckm = ec_curve_to_ckm(&curve);
140
141 // Get the PKCS11 slot
142 let slot = Slot::internal()?;
143
144 // Create a pointer for the public key
145 let mut pk_ptr = ptr::null_mut();
146
147 // https://github.com/mozilla/nss-gk-api/issues/1
148 unsafe {
149 let sk = PK11_GenerateKeyPair(
150 *slot,
151 ckm,
152 oid_ptr.cast(),
153 &mut pk_ptr,
154 CK_FALSE.into(),
155 CK_FALSE.into(),
156 ptr::null_mut(),
157 )
158 .into_result()?;
159
160 let pk = EcdhPublicKey::from_ptr(pk_ptr)?;
161
162 let kp = EcdhKeypair {
163 public: pk,
164 private: sk,
165 };
166
167 Ok(kp)
168 }
169 }
170
171 pub fn export_ec_private_key_pkcs8(key: PrivateKey) -> Result<Vec<u8>, Error> {
172 init();
173 unsafe {
174 let sk: crate::ScopedSECItem = PK11_ExportDERPrivateKeyInfo(*key, ptr::null_mut())
175 .into_result()
176 .unwrap();
177 return Ok(sk.into_vec());
178 }
179 }
180
181 pub fn import_ec_public_key_from_spki(spki: &[u8]) -> Result<PublicKey, Error> {
182 init();
183 let mut spki_item = SECItemBorrowed::wrap(&spki);
184 let spki_item_ptr = spki_item.as_mut();
185 let slot = Slot::internal()?;
186 unsafe {
187 let spki = SECKEY_DecodeDERSubjectPublicKeyInfo(spki_item_ptr)
188 .into_result()
189 .unwrap();
190 let pk: PublicKey = crate::p11::SECKEY_ExtractPublicKey(spki.as_mut().unwrap())
191 .into_result()
192 .unwrap();
193
194 let handle = PK11_ImportPublicKey(*slot, *pk, PR_FALSE);
195 if handle == pkcs11_bindings::CK_INVALID_HANDLE
196 {
197 return Err(Error::InvalidInput)
198 }
199
200 Ok(pk)
201 }
202 }
203
204 pub fn import_ec_private_key_pkcs8(pki: &[u8]) -> Result<PrivateKey, Error> {
205 init();
206
207 // Get the PKCS11 slot
208 let slot = Slot::internal()?;
209 let mut der_pki = SECItemBorrowed::wrap(&pki);
210 let der_pki_ptr: *mut SECItem = der_pki.as_mut();
211
212 // Create a pointer for the private key
213 let mut pk_ptr = ptr::null_mut();
214
215 unsafe {
216 secstatus_to_res(PK11_ImportDERPrivateKeyInfoAndReturnKey(
217 *slot,
218 der_pki_ptr,
219 ptr::null_mut(),
220 ptr::null_mut(),
221 0,
222 0,
223 KU_ALL,
224 &mut pk_ptr,
225 ptr::null_mut(),
226 ))
227 .expect("PKCS8 encoded key import has failed");
228
229 let sk = EcdhPrivateKey::from_ptr(pk_ptr)?;
230 Ok(sk)
231 }
232 }
233
234 pub fn export_ec_private_key_from_raw(key: PrivateKey) -> Result<Vec<u8>, Error> {
235 init();
236 let mut key_item = SECItemMut::make_empty();
237 unsafe { PK11_ReadRawAttribute(PK11_TypePrivKey, key.cast(), CKA_VALUE, key_item.as_mut()) };
238 Ok(key_item.as_slice().to_owned())
239 }
240
241 pub fn ecdh(sk: PrivateKey, pk: PublicKey) -> Result<Vec<u8>, Error> {
242 init();
243 let sym_key = unsafe {
244 PK11_PubDeriveWithKDF(
245 sk.cast(),
246 pk.cast(),
247 0,
248 ptr::null_mut(),
249 ptr::null_mut(),
250 pkcs11_bindings::CKM_ECDH1_DERIVE,
251 pkcs11_bindings::CKM_SHA512_HMAC,
252 pkcs11_bindings::CKA_SIGN,
253 0,
254 pkcs11_bindings::CKD_NULL,
255 ptr::null_mut(),
256 ptr::null_mut(),
257 )
258 .into_result()?
259 };
260
261 let key = sym_key.key_data().unwrap();
262 Ok(key.to_vec())
263 }
264
265 pub fn convert_to_public(sk: PrivateKey) -> Result<PublicKey, Error> {
266 init();
267 unsafe {
268 let pk = crate::p11::SECKEY_ConvertToPublicKey(*sk).into_result()?;
269 Ok(pk)
270 }
271 }
272
273 pub fn sign(
274 private_key: PrivateKey,
275 data: &[u8],
276 mechanism: std::os::raw::c_ulong,
277 ) -> Result<Vec<u8>, Error> {
278 init();
279 let data_signature = vec![0u8; 0x40];
280
281 let mut data_to_sign = SECItemBorrowed::wrap(&data);
282 let mut signature = SECItemBorrowed::wrap(&data_signature);
283 unsafe {
284 secstatus_to_res(crate::p11::PK11_SignWithMechanism(
285 private_key.as_mut().unwrap(),
286 mechanism,
287 std::ptr::null_mut(),
288 signature.as_mut(),
289 data_to_sign.as_mut(),
290 ))
291 .expect("Signature has failed");
292
293 let signature = signature.as_slice().to_vec();
294 Ok(signature)
295 }
296 }
297
298 pub fn sign_ecdsa(private_key: PrivateKey, data: &[u8]) -> Result<Vec<u8>, Error> {
299 sign(private_key, data, crate::p11::CKM_ECDSA.into())
300 }
301
302 pub fn sign_eddsa(private_key: PrivateKey, data: &[u8]) -> Result<Vec<u8>, Error> {
303 sign(private_key, data, crate::p11::CKM_EDDSA.into())
304 }
305
306 pub fn verify(
307 public_key: PublicKey,
308 data: &[u8],
309 signature: &[u8],
310 mechanism: std::os::raw::c_ulong,
311 ) -> Result<bool, Error> {
312 init();
313 unsafe {
314 let mut data_to_sign = SECItemBorrowed::wrap(&data);
315 let mut signature = SECItemBorrowed::wrap(&signature);
316
317 let rv = crate::p11::PK11_VerifyWithMechanism(
318 public_key.as_mut().unwrap(),
319 mechanism.into(),
320 std::ptr::null_mut(),
321 signature.as_mut(),
322 data_to_sign.as_mut(),
323 std::ptr::null_mut(),
324 );
325
326 match rv {
327 0 => Ok(true),
328 _ => Ok(false),
329 }
330 }
331 }
332
333 pub fn verify_ecdsa(public_key: PublicKey, data: &[u8], signature: &[u8]) -> Result<bool, Error> {
334 verify(public_key, data, signature, crate::p11::CKM_ECDSA.into())
335 }
336
337 pub fn verify_eddsa(public_key: PublicKey, data: &[u8], signature: &[u8]) -> Result<bool, Error> {
338 verify(public_key, data, signature, crate::p11::CKM_EDDSA.into())
339 }