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 5package pkcs12 6 7import ( 8 "crypto/x509" 9 "encoding/asn1" 10 "errors" 11) 12 13var ( 14 // see https://tools.ietf.org/html/rfc7292#appendix-D 15 oidCertTypeX509Certificate = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 9, 22, 1}) 16 oidPKCS8ShroundedKeyBag = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 10, 1, 2}) 17 oidCertBag = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 10, 1, 3}) 18) 19 20type certBag struct { 21 Id asn1.ObjectIdentifier 22 Data []byte `asn1:"tag:0,explicit"` 23} 24 25func decodePkcs8ShroudedKeyBag(asn1Data, password []byte) (privateKey interface{}, err error) { 26 pkinfo := new(encryptedPrivateKeyInfo) 27 if err = unmarshal(asn1Data, pkinfo); err != nil { 28 return nil, errors.New("pkcs12: error decoding PKCS#8 shrouded key bag: " + err.Error()) 29 } 30 31 pkData, err := pbDecrypt(pkinfo, password) 32 if err != nil { 33 return nil, errors.New("pkcs12: error decrypting PKCS#8 shrouded key bag: " + err.Error()) 34 } 35 36 ret := new(asn1.RawValue) 37 if err = unmarshal(pkData, ret); err != nil { 38 return nil, errors.New("pkcs12: error unmarshaling decrypted private key: " + err.Error()) 39 } 40 41 if privateKey, err = x509.ParsePKCS8PrivateKey(pkData); err != nil { 42 return nil, errors.New("pkcs12: error parsing PKCS#8 private key: " + err.Error()) 43 } 44 45 return privateKey, nil 46} 47 48func decodeCertBag(asn1Data []byte) (x509Certificates []byte, err error) { 49 bag := new(certBag) 50 if err := unmarshal(asn1Data, bag); err != nil { 51 return nil, errors.New("pkcs12: error decoding cert bag: " + err.Error()) 52 } 53 if !bag.Id.Equal(oidCertTypeX509Certificate) { 54 return nil, NotImplementedError("only X509 certificates are supported") 55 } 56 return bag.Data, nil 57} 58