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