| 1 | // |
| 2 | // Copyright (c) SAS Institute Inc. |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | // |
| 16 | |
| 17 | package certloader |
| 18 | |
| 19 | import ( |
| 20 | "crypto/x509" |
| 21 | "errors" |
| 22 | |
| 23 | "software.sslmate.com/src/go-pkcs12" |
| 24 | |
| 25 | "github.com/sassoftware/relic/v7/lib/passprompt" |
| 26 | ) |
| 27 | |
| 28 | func ParsePKCS12(blob []byte, prompt passprompt.PasswordGetter) (*Certificate, error) { |
| 29 | var password string |
| 30 | var triedEmpty bool |
| 31 | for { |
| 32 | var err error |
| 33 | password, err = prompt.GetPasswd("Password for PKCS12: ") |
| 34 | if err != nil { |
| 35 | return nil, err |
| 36 | } else if password == "" { |
| 37 | if triedEmpty { |
| 38 | return nil, errors.New("aborted") |
| 39 | } |
| 40 | triedEmpty = true |
| 41 | } |
| 42 | priv, leaf, chain, err := pkcs12.DecodeChain(blob, password) |
| 43 | if errors.Is(err, pkcs12.ErrIncorrectPassword) { |
| 44 | continue |
| 45 | } else if err != nil { |
| 46 | return nil, err |
| 47 | } |
| 48 | certs := append([]*x509.Certificate{leaf}, chain...) |
| 49 | return &Certificate{ |
| 50 | PrivateKey: priv, |
| 51 | Leaf: leaf, |
| 52 | Certificates: certs, |
| 53 | }, nil |
| 54 | } |
| 55 | } |