...

Source file src/github.com/sassoftware/relic/lib/pkcs7/marshal.go

Documentation: github.com/sassoftware/relic/lib/pkcs7

     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 pkcs7
    18  
    19  import (
    20  	"bytes"
    21  	"crypto/x509"
    22  	"encoding/asn1"
    23  	"errors"
    24  	"fmt"
    25  )
    26  
    27  // Parse a signature from bytes
    28  func Unmarshal(blob []byte) (*ContentInfoSignedData, error) {
    29  	psd := new(ContentInfoSignedData)
    30  	if rest, err := asn1.Unmarshal(blob, psd); err != nil {
    31  		return nil, err
    32  	} else if len(bytes.TrimRight(rest, "\x00")) != 0 {
    33  		return nil, errors.New("pkcs7: trailing garbage after PKCS#7 structure")
    34  	}
    35  	return psd, nil
    36  }
    37  
    38  // Marshal the signature to bytes
    39  func (psd *ContentInfoSignedData) Marshal() ([]byte, error) {
    40  	return asn1.Marshal(*psd)
    41  }
    42  
    43  // Remove and return inlined content from the document, leaving a detached signature
    44  func (psd *ContentInfoSignedData) Detach() ([]byte, error) {
    45  	content, err := psd.Content.ContentInfo.Bytes()
    46  	if err != nil {
    47  		return nil, fmt.Errorf("pkcs7: %s", err)
    48  	}
    49  	psd.Content.ContentInfo, _ = NewContentInfo(psd.Content.ContentInfo.ContentType, nil)
    50  	return content, nil
    51  }
    52  
    53  // dump raw certificates to structure
    54  func marshalCertificates(certs []*x509.Certificate) RawCertificates {
    55  	var buf bytes.Buffer
    56  	for _, cert := range certs {
    57  		buf.Write(cert.Raw)
    58  	}
    59  	val := asn1.RawValue{Bytes: buf.Bytes(), Class: 2, Tag: 0, IsCompound: true}
    60  	b, _ := asn1.Marshal(val)
    61  	return RawCertificates{Raw: b}
    62  }
    63  
    64  // parse raw certificates from structure
    65  func (raw RawCertificates) Parse() ([]*x509.Certificate, error) {
    66  	var val asn1.RawValue
    67  	if len(raw.Raw) == 0 {
    68  		return nil, nil
    69  	}
    70  	if _, err := asn1.Unmarshal(raw.Raw, &val); err != nil {
    71  		return nil, err
    72  	}
    73  	return x509.ParseCertificates(val.Bytes)
    74  }
    75  

View as plain text