Debian Codegraph @

crypto/keypair/ed25519.go

raw
1 package keypair
2
3 import (
4 "crypto/ed25519"
5 "crypto/rand"
6 "crypto/x509"
7 "encoding/pem"
8 "strings"
9
10 "github.com/dromara/dongle/coding"
11 "github.com/dromara/dongle/internal/utils"
12 )
13
14 // Ed25519KeyPair represents an ED25519 key pair with public and private keys.
15 // It supports PKCS8 format and provides methods for key generation,
16 // formatting, and parsing.
17 type Ed25519KeyPair struct {
18 // PublicKey contains the PEM-encoded public key
19 PublicKey []byte
20
21 // PrivateKey contains the PEM-encoded private key
22 PrivateKey []byte
23
24 // Signature contains the signature bytes for verification
25 Signature []byte
26 }
27
28 // NewEd25519KeyPair returns a new Ed25519KeyPair instance.
29 func NewEd25519KeyPair() *Ed25519KeyPair {
30 return &Ed25519KeyPair{}
31 }
32
33 // GenKeyPair generates a new Ed25519KeyPair instance.
34 // The generated keys are formatted in PEM format using PKCS8 format.
35 //
36 // Note: The generated keys are automatically formatted in PEM format using PKCS8 format.
37 func (k *Ed25519KeyPair) GenKeyPair() error {
38 publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
39 if err != nil {
40 return err
41 }
42
43 // ED25519 only supports PKCS8 format
44 if privateKeyDer, err := x509.MarshalPKCS8PrivateKey(privateKey); err == nil {
45 k.PrivateKey = pem.EncodeToMemory(&pem.Block{
46 Type: "PRIVATE KEY",
47 Bytes: privateKeyDer,
48 })
49 }
50
51 if publicKeyDer, err := x509.MarshalPKIXPublicKey(publicKey); err == nil {
52 k.PublicKey = pem.EncodeToMemory(&pem.Block{
53 Type: "PUBLIC KEY",
54 Bytes: publicKeyDer,
55 })
56 }
57
58 return nil
59 }
60
61 // SetPublicKey sets the public key and formats it in PKCS8 format.
62 // The input key is expected to be in PEM format and will be reformatted if necessary.
63 func (k *Ed25519KeyPair) SetPublicKey(publicKey []byte) error {
64 key, err := k.FormatPublicKey(publicKey)
65 if err == nil {
66 k.PublicKey = key
67 }
68 return err
69 }
70
71 // SetPrivateKey sets the private key and formats it in PKCS8 format.
72 // The input key is expected to be in PEM format and will be reformatted if necessary.
73 func (k *Ed25519KeyPair) SetPrivateKey(privateKey []byte) error {
74 key, err := k.FormatPrivateKey(privateKey)
75 if err == nil {
76 k.PrivateKey = key
77 }
78 return err
79 }
80
81 // ParsePublicKey parses the public key from PEM format and returns a Go crypto/ed25519.PublicKey.
82 // It supports PKCS8 format.
83 //
84 // Note: This method automatically detects the key format from the PEM headers.
85 func (k *Ed25519KeyPair) ParsePublicKey() (ed25519.PublicKey, error) {
86 publicKey := k.PublicKey
87 if len(publicKey) == 0 {
88 return nil, EmptyPublicKeyError{}
89 }
90 block, _ := pem.Decode(publicKey)
91 if block == nil {
92 return nil, InvalidPublicKeyError{}
93 }
94
95 // Parse based on the PEM block type
96 if block.Type == "PUBLIC KEY" {
97 // PKCS8 format public key
98 pub, err := x509.ParsePKIXPublicKey(block.Bytes)
99 if err != nil {
100 return nil, InvalidPublicKeyError{Err: err}
101 }
102 return pub.(ed25519.PublicKey), nil
103 }
104 return nil, UnsupportedKeyFormatError{}
105 }
106
107 // ParsePrivateKey parses the private key from PEM format and returns a Go crypto/ed25519.PrivateKey.
108 // It supports PKCS8 format.
109 //
110 // Note: This method automatically detects the key format from the PEM headers.
111 func (k *Ed25519KeyPair) ParsePrivateKey() (ed25519.PrivateKey, error) {
112 privateKey := k.PrivateKey
113 if len(privateKey) == 0 {
114 return nil, EmptyPrivateKeyError{}
115 }
116 block, _ := pem.Decode(privateKey)
117 if block == nil {
118 return nil, InvalidPrivateKeyError{}
119 }
120
121 // Parse based on the PEM block type
122 if block.Type == "PRIVATE KEY" {
123 // PKCS8 format private key
124 pri, err := x509.ParsePKCS8PrivateKey(block.Bytes)
125 if err != nil {
126 return nil, InvalidPrivateKeyError{Err: err}
127 }
128 return pri.(ed25519.PrivateKey), nil
129 }
130 return nil, UnsupportedKeyFormatError{}
131 }
132
133 // FormatPublicKey formats base64-encoded der public key into the specified PEM format.
134 func (k *Ed25519KeyPair) FormatPublicKey(publicKey []byte) ([]byte, error) {
135 if len(publicKey) == 0 {
136 return []byte{}, EmptyPublicKeyError{}
137 }
138
139 decoder := coding.NewDecoder().FromBytes(publicKey).ByBase64()
140 if decoder.Error != nil {
141 return []byte{}, InvalidPublicKeyError{Err: decoder.Error}
142 }
143
144 // ED25519 only supports PKCS8 format
145 // Use pem.EncodeToMemory to format the key
146 return pem.EncodeToMemory(&pem.Block{
147 Type: "PUBLIC KEY",
148 Bytes: decoder.ToBytes(),
149 }), nil
150 }
151
152 // FormatPrivateKey formats base64-encoded der private key into the specified PEM format.
153 func (k *Ed25519KeyPair) FormatPrivateKey(privateKey []byte) ([]byte, error) {
154 if len(privateKey) == 0 {
155 return []byte{}, EmptyPrivateKeyError{}
156 }
157
158 decoder := coding.NewDecoder().FromBytes(privateKey).ByBase64()
159 if decoder.Error != nil {
160 return []byte{}, InvalidPrivateKeyError{Err: decoder.Error}
161 }
162
163 // ED25519 only supports PKCS8 format
164 // Use pem.EncodeToMemory to format the key
165 return pem.EncodeToMemory(&pem.Block{
166 Type: "PRIVATE KEY",
167 Bytes: decoder.ToBytes(),
168 }), nil
169 }
170
171 // CompressPublicKey removes the PEM headers and footers from the public key.
172 // It supports PKCS8 format and removes all whitespace characters.
173 // The resulting byte slice contains only the base64-encoded key data.
174 func (k *Ed25519KeyPair) CompressPublicKey(publicKey []byte) []byte {
175 // Convert byte slice to string for easier manipulation
176 keyStr := utils.Bytes2String(publicKey)
177
178 // Remove the PEM headers (only PKCS8 for ED25519)
179 keyStr = strings.ReplaceAll(keyStr, "-----BEGIN PUBLIC KEY-----", "")
180
181 // Remove the PEM footers (only PKCS8 for ED25519)
182 keyStr = strings.ReplaceAll(keyStr, "-----END PUBLIC KEY-----", "")
183
184 // Remove all newline characters and whitespace
185 keyStr = strings.ReplaceAll(keyStr, "\n", "")
186 keyStr = strings.ReplaceAll(keyStr, "\r", "")
187 keyStr = strings.ReplaceAll(keyStr, " ", "")
188 keyStr = strings.ReplaceAll(keyStr, "\t", "")
189
190 // Remove any remaining whitespace that might be present
191 keyStr = strings.TrimSpace(keyStr)
192
193 return utils.String2Bytes(keyStr)
194 }
195
196 // CompressPrivateKey removes the PEM headers and footers from the private key.
197 // It supports PKCS8 format and removes all whitespace characters.
198 // The resulting byte slice contains only the base64-encoded key data.
199 func (k *Ed25519KeyPair) CompressPrivateKey(privateKey []byte) []byte {
200 // Convert byte slice to string for easier manipulation
201 keyStr := utils.Bytes2String(privateKey)
202
203 // Remove the PEM headers (only PKCS8 for ED25519)
204 keyStr = strings.ReplaceAll(keyStr, "-----BEGIN PRIVATE KEY-----", "")
205
206 // Remove the PEM footers (only PKCS8 for ED25519)
207 keyStr = strings.ReplaceAll(keyStr, "-----END PRIVATE KEY-----", "")
208
209 // Remove all newline characters and whitespace
210 keyStr = strings.ReplaceAll(keyStr, "\n", "")
211 keyStr = strings.ReplaceAll(keyStr, "\r", "")
212 keyStr = strings.ReplaceAll(keyStr, " ", "")
213 keyStr = strings.ReplaceAll(keyStr, "\t", "")
214
215 // Remove any remaining whitespace that might be present
216 keyStr = strings.TrimSpace(keyStr)
217
218 return utils.String2Bytes(keyStr)
219 }