safebags.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2015 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package pkcs12
  5. import (
  6. "crypto/x509"
  7. "encoding/asn1"
  8. "errors"
  9. )
  10. var (
  11. // see https://tools.ietf.org/html/rfc7292#appendix-D
  12. oidCertTypeX509Certificate = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 22, 1})
  13. oidPKCS8ShroundedKeyBag = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 10, 1, 2})
  14. oidCertBag = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 10, 1, 3})
  15. )
  16. type certBag struct {
  17. Id asn1.ObjectIdentifier
  18. Data []byte `asn1:"tag:0,explicit"`
  19. }
  20. func decodePkcs8ShroudedKeyBag(asn1Data, password []byte) (privateKey interface{}, err error) {
  21. pkinfo := new(encryptedPrivateKeyInfo)
  22. if err = unmarshal(asn1Data, pkinfo); err != nil {
  23. return nil, errors.New("pkcs12: error decoding PKCS#8 shrouded key bag: " + err.Error())
  24. }
  25. pkData, err := pbDecrypt(pkinfo, password)
  26. if err != nil {
  27. return nil, errors.New("pkcs12: error decrypting PKCS#8 shrouded key bag: " + err.Error())
  28. }
  29. ret := new(asn1.RawValue)
  30. if err = unmarshal(pkData, ret); err != nil {
  31. return nil, errors.New("pkcs12: error unmarshaling decrypted private key: " + err.Error())
  32. }
  33. if privateKey, err = x509.ParsePKCS8PrivateKey(pkData); err != nil {
  34. return nil, errors.New("pkcs12: error parsing PKCS#8 private key: " + err.Error())
  35. }
  36. return privateKey, nil
  37. }
  38. func decodeCertBag(asn1Data []byte) (x509Certificates []byte, err error) {
  39. bag := new(certBag)
  40. if err := unmarshal(asn1Data, bag); err != nil {
  41. return nil, errors.New("pkcs12: error decoding cert bag: " + err.Error())
  42. }
  43. if !bag.Id.Equal(oidCertTypeX509Certificate) {
  44. return nil, NotImplementedError("only X509 certificates are supported")
  45. }
  46. return bag.Data, nil
  47. }