RustCrypto / formats

Cryptography-related format encoders/decoders: DER, PEM, PKCS, PKIX
228 stars 122 forks source link

How do I create a valid PKCS5-encrypted DER or PEM file using pkcs8? #1351

Closed gshuflin closed 2 months ago

gshuflin commented 4 months ago

Continuation of https://github.com/RustCrypto/formats/issues/1349. The last thing I need to figure out is how to create a PKCS5-encrypted ed25519 using rust code, that openssl can successfully parse.

I've updated my test repo with a couple of commits that try to take the 32 bytes of Ed25519 private key, and turn them into some other data structure, that I can call some encrypt method upon. ( https://github.com/gshuflin/generate-pkcs8-format-key/commit/560c8173ef217f8f26c6cce215080a29d694b77f , https://github.com/gshuflin/generate-pkcs8-format-key/commit/e4d163c0d25210fed35e60109ad1e6bde36c3baf ) . When I try either of these solutions, I can generate a key, that fails with some error like:

$ openssl pkey -in new-encrypted.der
Enter pass phrase for new-encrypted.der:
Could not read key from new-encrypted.der
80C5A90401000000:error:030000AC:digital envelope routines:scrypt_alg:memory limit exceeded:providers/implementations/kdfs/scrypt.c:482:
80C5A90401000000:error:030000AB:digital envelope routines:PKCS5_v2_scrypt_keyivgen_ex:illegal scrypt parameters:crypto/asn1/p5_scrypt.c:260:

When I attempt to generate unencrypted keys, that works just fine.

I note that the EncodePrivateKey trait from the pkcs8 crate directly (https://docs.rs/pkcs8/latest/pkcs8/trait.EncodePrivateKey.html) has a to_pkcs8_encrypted_der method, that is not present on the version of this trait from ed25519::pkcs8.

tarcieri commented 4 months ago

@gshuflin yes, you need to directly import pkcs8 and enable its pkcs5 feature, and it will have to_pkcs8_encrypted_der/to_pkcs8_encrypted_pem