Debian Codegraph @

crypto/keypair/rsa.go

raw
1 package keypair
2
3 import (
4 "crypto"
5 "crypto/rand"
6 "crypto/rsa"
7 "crypto/x509"
8 "encoding/pem"
9 "strings"
10
11 "github.com/dromara/dongle/coding"
12 "github.com/dromara/dongle/internal/utils"
13 )
14
15 // RsaKeyFormat represents the PEM encoding format for RSA keys.
16 // This ONLY affects key generation (GenKeyPair) and determines the PEM header.
17 //
18 // IMPORTANT: RsaKeyFormat does NOT affect encryption/decryption/signing operations.
19 // For cryptographic operations, use RsaPaddingScheme instead.
20 //
21 // Key parsing (ParsePublicKey/ParsePrivateKey) automatically detects the format
22 // from PEM headers, so this field is not used during parsing.
23 type RsaKeyFormat string
24
25 // Key format constants for RSA key pairs.
26 const (
27 // PKCS1 generates keys with RSA-specific PEM headers.
28 // - Private key: "-----BEGIN RSA PRIVATE KEY-----"
29 // - Public key: "-----BEGIN RSA PUBLIC KEY-----"
30 // - Usage: Legacy compatibility, OpenSSL traditional format
31 PKCS1 RsaKeyFormat = "pkcs1"
32
33 // PKCS8 generates keys with generic PEM headers (recommended).
34 // - Private key: "-----BEGIN PRIVATE KEY-----"
35 // - Public key: "-----BEGIN PUBLIC KEY-----"
36 // - Usage: Modern standard, works with multiple key algorithms
37 PKCS8 RsaKeyFormat = "pkcs8"
38 )
39
40 // RsaPaddingScheme represents the padding scheme for RSA cryptographic operations.
41 //
42 // Different padding schemes are used for different operations:
43 // - PKCS1v15: Can be used for both encryption and signing
44 // - OAEP: Only for encryption (more secure than PKCS1v15)
45 // - PSS: Only for signing (more secure than PKCS1v15)
46 type RsaPaddingScheme string
47
48 const (
49 // PKCS1v15 uses PKCS#1 v1.5 padding for RSA operations.
50 // - For encryption/decryption: rsa.EncryptPKCS1v15 / rsa.DecryptPKCS1v15
51 // - For signing/verification: rsa.SignPKCS1v15 / rsa.VerifyPKCS1v15
52 // - Compatibility: Works with JSEncrypt, PHP openssl_* defaults
53 // - Security: Adequate for most applications, widely supported
54 // - Usage: Can be used for both encryption and signing operations
55 PKCS1v15 RsaPaddingScheme = "pkcs1v15"
56
57 // OAEP uses Optimal Asymmetric Encryption Padding (more secure).
58 // - For encryption/decryption: rsa.EncryptOAEP / rsa.DecryptOAEP
59 // - Compatibility: Modern standard, may not work with older libraries
60 // - Security: Recommended for encryption in new applications
61 // - Usage: ONLY for encryption/decryption operations
62 //
63 // Note: Attempting to use OAEP for signing/verification will return an error.
64 // For signing, use PKCS1v15 or PSS instead.
65 OAEP RsaPaddingScheme = "oaep"
66
67 // PSS uses Probabilistic Signature Scheme (more secure for signing).
68 // - For signing/verification: rsa.SignPSS / rsa.VerifyPSS
69 // - Compatibility: Modern standard, may not work with older libraries
70 // - Security: Recommended for signing in new applications
71 // - Usage: ONLY for signing/verification operations
72 //
73 // Note: Attempting to use PSS for encryption/decryption will return an error.
74 // For encryption, use PKCS1v15 or OAEP instead.
75 PSS RsaPaddingScheme = "pss"
76 )
77
78 // RsaKeyPair represents an RSA key pair with public and private keys.
79 // It supports both PKCS1 and PKCS8 key formats and provides methods for
80 // key generation, formatting, and parsing.
81 type RsaKeyPair struct {
82 // PublicKey contains the PEM-encoded public key
83 PublicKey []byte
84
85 // PrivateKey contains the PEM-encoded private key
86 PrivateKey []byte
87
88 // Signature contains the signature bytes for verification
89 Signature []byte
90
91 // Type specifies the key type (public or private).
92 Type KeyType
93
94 // Format specifies the key format for PEM encoding.
95 // This field affects:
96 // - GenKeyPair(): PEM header format when generating keys
97 // - FormatPublicKey(): PEM header format when formatting public keys
98 // - FormatPrivateKey(): PEM header format when formatting private keys
99 // It does NOT affect cryptographic operations.
100 Format RsaKeyFormat
101
102 // Padding specifies the padding scheme for RSA cryptographic operations.
103 // This field affects encryption, decryption, signing, and verification algorithms.
104 //
105 // Available padding schemes:
106 // - PKCS1v15: Can be used for both encryption and signing operations
107 // - OAEP: ONLY for encryption/decryption (error if used for signing/verification)
108 // - PSS: ONLY for signing/verification (error if used for encryption/decryption)
109 //
110 // Note: Padding is independent from Format. You can use any padding with any key format.
111 Padding RsaPaddingScheme
112
113 // Hash specifies the hash function used for RSA cryptographic operations.
114 // Usage depends on the Padding scheme:
115 // - PKCS1v15: Used for hashing message data before signing
116 // - OAEP: Used for mask generation in encryption/decryption
117 // - PSS: Used for mask generation in signing/verification
118 Hash crypto.Hash
119 }
120
121 // NewRsaKeyPair returns a new RsaKeyPair instance with default settings.
122 // For explicit security requirements:
123 // - For encryption: kp.SetPadding(keypair.OAEP)
124 // - For signing: kp.SetPadding(keypair.PSS)
125 // - For both: kp.SetPadding(keypair.PKCS1v15)
126 func NewRsaKeyPair() *RsaKeyPair {
127 return &RsaKeyPair{
128 Format: PKCS8,
129 Hash: crypto.SHA256,
130 }
131 }
132
133 // GenKeyPair generates a new RsaKeyPair with the specified key size.
134 // The generated keys are formatted according to the current Format setting.
135 //
136 // Note: The generated keys are automatically formatted in PEM format
137 // according to the current Format setting (PKCS1 or PKCS8).
138 func (k *RsaKeyPair) GenKeyPair(size int) error {
139 // Generate a new RSA private key
140 key, err := rsa.GenerateKey(rand.Reader, size)
141 if err != nil {
142 return err
143 }
144
145 // Format keys according to the specified format
146 if k.Format == PKCS1 {
147 // PKCS1 format: Use specific RSA headers
148 privateKeyDer := x509.MarshalPKCS1PrivateKey(key)
149 k.PrivateKey = pem.EncodeToMemory(&pem.Block{
150 Type: "RSA PRIVATE KEY",
151 Bytes: privateKeyDer,
152 })
153 publicKeyDer := x509.MarshalPKCS1PublicKey(&key.PublicKey)
154 k.PublicKey = pem.EncodeToMemory(&pem.Block{
155 Type: "RSA PUBLIC KEY",
156 Bytes: publicKeyDer,
157 })
158 return nil
159 }
160
161 if k.Format == PKCS8 {
162 // PKCS8 format: Use generic headers
163 if privateKeyDer, err := x509.MarshalPKCS8PrivateKey(key); err == nil {
164 k.PrivateKey = pem.EncodeToMemory(&pem.Block{
165 Type: "PRIVATE KEY",
166 Bytes: privateKeyDer,
167 })
168 }
169
170 if publicKeyDer, err := x509.MarshalPKIXPublicKey(&key.PublicKey); err == nil {
171 k.PublicKey = pem.EncodeToMemory(&pem.Block{
172 Type: "PUBLIC KEY",
173 Bytes: publicKeyDer,
174 })
175 }
176 return nil
177 }
178 return UnsupportedKeyFormatError{}
179 }
180
181 // SetPublicKey sets the public key and formats it according to the current format.
182 // The input key is expected to be in PEM format and will be reformatted if necessary.
183 func (k *RsaKeyPair) SetPublicKey(publicKey []byte) error {
184 key, err := k.FormatPublicKey(publicKey)
185 if err == nil {
186 k.PublicKey = key
187 }
188 return err
189 }
190
191 // SetPrivateKey sets the private key and formats it according to the current format.
192 // The input key is expected to be in PEM format and will be reformatted if necessary.
193 func (k *RsaKeyPair) SetPrivateKey(privateKey []byte) error {
194 key, err := k.FormatPrivateKey(privateKey)
195 if err == nil {
196 k.PrivateKey = key
197 }
198 return err
199 }
200
201 // SetType sets the key type (public or private) for the RSA key pair.
202 func (k *RsaKeyPair) SetType(typ KeyType) {
203 k.Type = typ
204 }
205
206 // SetFormat sets the key format for the RSA key pair.
207 // This affects:
208 // - GenKeyPair(): Determines the PEM header format when generating keys
209 // - FormatPublicKey(): Determines the PEM header format when formatting public keys
210 // - FormatPrivateKey(): Determines the PEM header format when formatting private keys
211 func (k *RsaKeyPair) SetFormat(format RsaKeyFormat) {
212 k.Format = format
213 }
214
215 // SetPadding sets the padding scheme for RSA cryptographic operations.
216 //
217 // Padding schemes:
218 // - PKCS1v15: Can be used for both encryption and signing
219 // - OAEP: ONLY for encryption (returns error if used for signing)
220 // - PSS: ONLY for signing (returns error if used for encryption)
221 func (k *RsaKeyPair) SetPadding(padding RsaPaddingScheme) {
222 k.Padding = padding
223 }
224
225 // SetHash sets the hash function used for OAEP padding in RSA operations.
226 func (k *RsaKeyPair) SetHash(hash crypto.Hash) {
227 k.Hash = hash
228 }
229
230 // ParsePublicKey parses the public key from PEM format.
231 // It supports both PKCS1 and PKCS8 formats automatically.
232 //
233 // Note: This method automatically detects the key format from the PEM headers.
234 func (k *RsaKeyPair) ParsePublicKey() (*rsa.PublicKey, error) {
235 publicKey := k.PublicKey
236 if len(publicKey) == 0 {
237 return nil, EmptyPublicKeyError{}
238 }
239 block, _ := pem.Decode(publicKey)
240 if block == nil {
241 return nil, InvalidPublicKeyError{}
242 }
243
244 // PKCS1 format public key
245 if block.Type == "RSA PUBLIC KEY" {
246 pub, err := x509.ParsePKCS1PublicKey(block.Bytes)
247 if err != nil {
248 err = InvalidPublicKeyError{Err: err}
249 }
250 return pub, err
251 }
252
253 // PKCS8 format public key
254 if block.Type == "PUBLIC KEY" {
255 pub, err := x509.ParsePKIXPublicKey(block.Bytes)
256 if err != nil {
257 return nil, InvalidPublicKeyError{Err: err}
258 }
259 return pub.(*rsa.PublicKey), err
260 }
261 return nil, UnsupportedKeyFormatError{}
262 }
263
264 // ParsePrivateKey parses the private key from PEM format.
265 // It supports both PKCS1 and PKCS8 formats automatically.
266 //
267 // Note: This method automatically detects the key format from the PEM headers.
268 func (k *RsaKeyPair) ParsePrivateKey() (*rsa.PrivateKey, error) {
269 privateKey := k.PrivateKey
270 if len(privateKey) == 0 {
271 return nil, EmptyPrivateKeyError{}
272 }
273 block, _ := pem.Decode(privateKey)
274 if block == nil {
275 return nil, InvalidPrivateKeyError{}
276 }
277
278 // PKCS1 format private key
279 if block.Type == "RSA PRIVATE KEY" {
280 pri, err := x509.ParsePKCS1PrivateKey(block.Bytes)
281 if err != nil {
282 return nil, InvalidPrivateKeyError{Err: err}
283 }
284 return pri, err
285 }
286
287 // PKCS8 format private key
288 if block.Type == "PRIVATE KEY" {
289 pri, err := x509.ParsePKCS8PrivateKey(block.Bytes)
290 if err != nil {
291 return nil, InvalidPrivateKeyError{Err: err}
292 }
293 return pri.(*rsa.PrivateKey), err
294 }
295 return nil, UnsupportedKeyFormatError{}
296 }
297
298 // FormatPublicKey formats base64-encoded der public key into the specified PEM format.
299 func (k *RsaKeyPair) FormatPublicKey(publicKey []byte) ([]byte, error) {
300 if len(publicKey) == 0 {
301 return []byte{}, EmptyPublicKeyError{}
302 }
303
304 decoder := coding.NewDecoder().FromBytes(publicKey).ByBase64()
305 if decoder.Error != nil {
306 return []byte{}, InvalidPublicKeyError{Err: decoder.Error}
307 }
308
309 var blockType string
310 switch k.Format {
311 case PKCS1:
312 blockType = "RSA PUBLIC KEY"
313 case PKCS8:
314 blockType = "PUBLIC KEY"
315 default:
316 return []byte{}, UnsupportedKeyFormatError{}
317 }
318
319 // Use pem.EncodeToMemory to format the key
320 return pem.EncodeToMemory(&pem.Block{
321 Type: blockType,
322 Bytes: decoder.ToBytes(),
323 }), nil
324 }
325
326 // FormatPrivateKey formats base64-encoded der private key into the specified PEM format.
327 func (k *RsaKeyPair) FormatPrivateKey(privateKey []byte) ([]byte, error) {
328 if len(privateKey) == 0 {
329 return []byte{}, EmptyPrivateKeyError{}
330 }
331
332 decoder := coding.NewDecoder().FromBytes(privateKey).ByBase64()
333 if decoder.Error != nil {
334 return []byte{}, InvalidPrivateKeyError{Err: decoder.Error}
335 }
336
337 var blockType string
338 switch k.Format {
339 case PKCS1:
340 blockType = "RSA PRIVATE KEY"
341 case PKCS8:
342 blockType = "PRIVATE KEY"
343 default:
344 return []byte{}, UnsupportedKeyFormatError{}
345 }
346
347 // Use pem.EncodeToMemory to format the key
348 return pem.EncodeToMemory(&pem.Block{
349 Type: blockType,
350 Bytes: decoder.ToBytes(),
351 }), nil
352 }
353
354 // CompressPublicKey removes the PEM headers and footers from the public key.
355 // It supports both PKCS1 and PKCS8 formats and removes all whitespace characters.
356 // The resulting byte slice contains only the base64-encoded key data.
357 func (k *RsaKeyPair) CompressPublicKey(publicKey []byte) []byte {
358 // Convert byte slice to string for easier manipulation
359 keyStr := utils.Bytes2String(publicKey)
360
361 // Remove the PEM headers (both PKCS1 and PKCS8)
362 keyStr = strings.ReplaceAll(keyStr, "-----BEGIN PUBLIC KEY-----", "")
363 keyStr = strings.ReplaceAll(keyStr, "-----BEGIN RSA PUBLIC KEY-----", "")
364
365 // Remove the PEM footers (both PKCS1 and PKCS8)
366 keyStr = strings.ReplaceAll(keyStr, "-----END PUBLIC KEY-----", "")
367 keyStr = strings.ReplaceAll(keyStr, "-----END RSA PUBLIC KEY-----", "")
368
369 // Remove all newline characters and whitespace
370 keyStr = strings.ReplaceAll(keyStr, "\n", "")
371 keyStr = strings.ReplaceAll(keyStr, "\r", "")
372 keyStr = strings.ReplaceAll(keyStr, " ", "")
373 keyStr = strings.ReplaceAll(keyStr, "\t", "")
374
375 // Remove any remaining whitespace that might be present
376 keyStr = strings.TrimSpace(keyStr)
377
378 return utils.String2Bytes(keyStr)
379 }
380
381 // CompressPrivateKey removes the PEM headers and footers from the private key.
382 // It supports both PKCS1 and PKCS8 formats and removes all whitespace characters.
383 // The resulting byte slice contains only the base64-encoded key data.
384 func (k *RsaKeyPair) CompressPrivateKey(privateKey []byte) []byte {
385 // Convert byte slice to string for easier manipulation
386 keyStr := utils.Bytes2String(privateKey)
387
388 // Remove the PEM headers (both PKCS1 and PKCS8)
389 keyStr = strings.ReplaceAll(keyStr, "-----BEGIN PRIVATE KEY-----", "")
390 keyStr = strings.ReplaceAll(keyStr, "-----BEGIN RSA PRIVATE KEY-----", "")
391
392 // Remove the PEM footers (both PKCS1 and PKCS8)
393 keyStr = strings.ReplaceAll(keyStr, "-----END PRIVATE KEY-----", "")
394 keyStr = strings.ReplaceAll(keyStr, "-----END RSA PRIVATE KEY-----", "")
395
396 // Remove all newline characters and whitespace
397 keyStr = strings.ReplaceAll(keyStr, "\n", "")
398 keyStr = strings.ReplaceAll(keyStr, "\r", "")
399 keyStr = strings.ReplaceAll(keyStr, " ", "")
400 keyStr = strings.ReplaceAll(keyStr, "\t", "")
401
402 // Remove any remaining whitespace that might be present
403 keyStr = strings.TrimSpace(keyStr)
404
405 return utils.String2Bytes(keyStr)
406 }