|
1 | 1 | """ |
2 | 2 | Example file: Demonstrating how to serialize a PrivateKey to DER (hex) |
3 | 3 | and then load it back. |
4 | | -*WARNING* DER seeds should not be printed or exposed in a real‑world scenario |
| 4 | +*WARNING* DER‐encoded private keys should not be printed or exposed in a real-world scenario. |
5 | 5 | """ |
| 6 | + |
6 | 7 | from cryptography.exceptions import InvalidSignature |
7 | 8 | from hiero_sdk_python.crypto.private_key import PrivateKey |
8 | 9 |
|
9 | 10 | def example_serialize_ed25519_der() -> None: |
10 | | - |
11 | 11 | print("=== Ed25519: Serialize to DER ===") |
12 | | - privkey = PrivateKey.generate_ed25519() |
| 12 | + |
| 13 | + privkey = PrivateKey.generate("ed25519") |
13 | 14 | print("Generated Ed25519 key:", privkey) |
14 | 15 |
|
15 | | - # Convert to DER (TraditionalOpenSSL) |
| 16 | + # This emits PKCS#8 DER by default |
16 | 17 | der_bytes = privkey.to_bytes_der() |
17 | 18 | print("DER bytes length =", len(der_bytes)) |
18 | 19 |
|
19 | 20 | der_hex = der_bytes.hex() |
20 | 21 | print("DER hex =", der_hex) |
21 | 22 |
|
22 | | - # Load it back |
| 23 | + # Load it back from hex |
23 | 24 | privkey2 = PrivateKey.from_string_der(der_hex) |
24 | | - print("Loaded back from DER =", privkey2) |
| 25 | + print("Loaded back from DER:", privkey2) |
25 | 26 |
|
26 | | - # Sign test |
| 27 | + # Sign & verify |
27 | 28 | signature = privkey2.sign(b"test") |
28 | 29 | privkey2.public_key().verify(signature, b"test") |
29 | 30 | print("Ed25519 DER reload: Verified signature OK.\n") |
30 | 31 |
|
31 | 32 | def example_serialize_ecdsa_der() -> None: |
32 | | - |
33 | 33 | print("=== ECDSA: Serialize to DER ===") |
34 | | - privkey = PrivateKey.generate_ecdsa() |
| 34 | + |
| 35 | + # use generate("ecdsa") |
| 36 | + privkey = PrivateKey.generate("ecdsa") |
35 | 37 | print("Generated ECDSA key:", privkey) |
36 | 38 |
|
37 | | - # Convert to DER |
38 | 39 | der_bytes = privkey.to_bytes_der() |
| 40 | + print("DER bytes length =", len(der_bytes)) |
| 41 | + |
39 | 42 | der_hex = der_bytes.hex() |
40 | 43 | print("DER hex =", der_hex) |
41 | 44 |
|
42 | | - # Load it back |
43 | 45 | privkey2 = PrivateKey.from_string_der(der_hex) |
44 | | - print("Loaded back from DER =", privkey2) |
| 46 | + print("Loaded back from DER:", privkey2) |
45 | 47 |
|
46 | | - # Sign test |
47 | 48 | signature = privkey2.sign(b"hello ECDSA serialization") |
48 | 49 | privkey2.public_key().verify(signature, b"hello ECDSA serialization") |
49 | 50 | print("ECDSA DER reload: Verified signature OK.\n") |
|
0 commit comments