Add LoadPrivateKey(s) functions
This commit is contained in:
		
							
								
								
									
										41
									
								
								keys.go
									
									
									
									
									
								
							
							
						
						
									
										41
									
								
								keys.go
									
									
									
									
									
								
							| @@ -102,3 +102,44 @@ func generateKeys(path string) (ed25519.PublicKey, ed25519.PrivateKey, error) { | |||||||
|  |  | ||||||
| 	return pub, priv, nil | 	return pub, priv, nil | ||||||
| } | } | ||||||
|  |  | ||||||
|  | // LoadPrivateKeys loads the private keys at all the provided paths. | ||||||
|  | // | ||||||
|  | // Any invalid keys are skipped. | ||||||
|  | func LoadPrivateKeys(paths ...string) []ed25519.PrivateKey { | ||||||
|  | 	out := make([]ed25519.PrivateKey, len(paths)) | ||||||
|  | 	for i, path := range paths { | ||||||
|  | 		privkey, err := LoadPrivateKey(path) | ||||||
|  | 		if err != nil { | ||||||
|  | 			continue | ||||||
|  | 		} | ||||||
|  | 		out[i] = privkey | ||||||
|  | 	} | ||||||
|  | 	return out | ||||||
|  | } | ||||||
|  |  | ||||||
|  | // LoadPrivateKey loads a private Ed25519 key from the given path. | ||||||
|  | func LoadPrivateKey(path string) (ed25519.PrivateKey, error) { | ||||||
|  | 	privData, err := os.ReadFile(path) | ||||||
|  | 	if err != nil { | ||||||
|  | 		return nil, err | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	privBlock, _ := pem.Decode(privData) | ||||||
|  |  | ||||||
|  | 	if privBlock == nil { | ||||||
|  | 		return nil, errors.New("invalid private key data") | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	privkey, err := x509.ParsePKCS8PrivateKey(privBlock.Bytes) | ||||||
|  | 	if err != nil { | ||||||
|  | 		return nil, err | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	priv, ok := privkey.(ed25519.PrivateKey) | ||||||
|  | 	if !ok { | ||||||
|  | 		return nil, errors.New("invalid private key type") | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	return priv, nil | ||||||
|  | } | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user