LoadPrivateKey loads the encrypted private key from the passed file and decrypts it.
(password []byte, file string)
| 166 | |
| 167 | // LoadPrivateKey loads the encrypted private key from the passed file and decrypts it. |
| 168 | func LoadPrivateKey(password []byte, file string) (crypto.PrivateKey, error) { |
| 169 | keyBytes, err := os.ReadFile(file) |
| 170 | if err != nil { |
| 171 | return nil, err |
| 172 | } |
| 173 | |
| 174 | block, _ := pem.Decode(keyBytes) |
| 175 | if block == nil { |
| 176 | return nil, errors.New("could not decode the private key: " + err.Error()) |
| 177 | } |
| 178 | |
| 179 | if block.Type != "RSA PRIVATE KEY" && block.Type != "ECDSA PRIVATE KEY" { |
| 180 | return nil, errors.New("unsupported key type: " + block.Type) |
| 181 | } |
| 182 | |
| 183 | keyBytes, err = x509.DecryptPEMBlock(block, password) |
| 184 | if err != nil { |
| 185 | return nil, errors.New("could decrypt CA key: " + err.Error()) |
| 186 | } |
| 187 | |
| 188 | if block.Type == "RSA PRIVATE KEY" { |
| 189 | return x509.ParsePKCS1PrivateKey(keyBytes) |
| 190 | } |
| 191 | |
| 192 | return x509.ParseECPrivateKey(keyBytes) |
| 193 | } |
| 194 | |
| 195 | // StorePrivateKey encrypts the private key and stores it in the returned file. |
| 196 | func StorePrivateKey(key crypto.PrivateKey, password []byte, file string) error { |