github.phpd.cn/hashicorp/packer@v1.3.2/builder/azure/pkcs12/crypto.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  	"bytes"
     9  	"crypto/cipher"
    10  	"crypto/des"
    11  	"crypto/rand"
    12  	"crypto/x509/pkix"
    13  	"encoding/asn1"
    14  	"errors"
    15  	"io"
    16  
    17  	"github.com/hashicorp/packer/builder/azure/pkcs12/rc2"
    18  )
    19  
    20  const (
    21  	pbeIterationCount = 2048
    22  	pbeSaltSizeBytes  = 8
    23  )
    24  
    25  var (
    26  	oidPBEWithSHAAnd3KeyTripleDESCBC = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 3})
    27  	oidPBEWithSHAAnd40BitRC2CBC      = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 6})
    28  )
    29  
    30  // pbeCipher is an abstraction of a PKCS#12 cipher.
    31  type pbeCipher interface {
    32  	// create returns a cipher.Block given a key.
    33  	create(key []byte) (cipher.Block, error)
    34  	// deriveKey returns a key derived from the given password and salt.
    35  	deriveKey(salt, password []byte, iterations int) []byte
    36  	// deriveKey returns an IV derived from the given password and salt.
    37  	deriveIV(salt, password []byte, iterations int) []byte
    38  }
    39  
    40  type shaWithTripleDESCBC struct{}
    41  
    42  func (shaWithTripleDESCBC) create(key []byte) (cipher.Block, error) {
    43  	return des.NewTripleDESCipher(key)
    44  }
    45  
    46  func (shaWithTripleDESCBC) deriveKey(salt, password []byte, iterations int) []byte {
    47  	return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 1, 24)
    48  }
    49  
    50  func (shaWithTripleDESCBC) deriveIV(salt, password []byte, iterations int) []byte {
    51  	return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 2, 8)
    52  }
    53  
    54  type shaWith40BitRC2CBC struct{}
    55  
    56  func (shaWith40BitRC2CBC) create(key []byte) (cipher.Block, error) {
    57  	return rc2.New(key, len(key)*8)
    58  }
    59  
    60  func (shaWith40BitRC2CBC) deriveKey(salt, password []byte, iterations int) []byte {
    61  	return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 1, 5)
    62  }
    63  
    64  func (shaWith40BitRC2CBC) deriveIV(salt, password []byte, iterations int) []byte {
    65  	return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 2, 8)
    66  }
    67  
    68  type pbeParams struct {
    69  	Salt       []byte
    70  	Iterations int
    71  }
    72  
    73  func pbDecrypterFor(algorithm pkix.AlgorithmIdentifier, password []byte) (cipher.BlockMode, int, error) {
    74  	var cipherType pbeCipher
    75  
    76  	switch {
    77  	case algorithm.Algorithm.Equal(oidPBEWithSHAAnd3KeyTripleDESCBC):
    78  		cipherType = shaWithTripleDESCBC{}
    79  	case algorithm.Algorithm.Equal(oidPBEWithSHAAnd40BitRC2CBC):
    80  		cipherType = shaWith40BitRC2CBC{}
    81  	default:
    82  		return nil, 0, NotImplementedError("algorithm " + algorithm.Algorithm.String() + " is not supported")
    83  	}
    84  
    85  	var params pbeParams
    86  	if err := unmarshal(algorithm.Parameters.FullBytes, &params); err != nil {
    87  		return nil, 0, err
    88  	}
    89  
    90  	key := cipherType.deriveKey(params.Salt, password, params.Iterations)
    91  	iv := cipherType.deriveIV(params.Salt, password, params.Iterations)
    92  
    93  	block, err := cipherType.create(key)
    94  	if err != nil {
    95  		return nil, 0, err
    96  	}
    97  
    98  	return cipher.NewCBCDecrypter(block, iv), block.BlockSize(), nil
    99  }
   100  
   101  func pbDecrypt(info decryptable, password []byte) (decrypted []byte, err error) {
   102  	cbc, blockSize, err := pbDecrypterFor(info.Algorithm(), password)
   103  	if err != nil {
   104  		return nil, err
   105  	}
   106  
   107  	encrypted := info.Data()
   108  	if len(encrypted) == 0 {
   109  		return nil, errors.New("pkcs12: empty encrypted data")
   110  	}
   111  	if len(encrypted)%blockSize != 0 {
   112  		return nil, errors.New("pkcs12: input is not a multiple of the block size")
   113  	}
   114  	decrypted = make([]byte, len(encrypted))
   115  	cbc.CryptBlocks(decrypted, encrypted)
   116  
   117  	psLen := int(decrypted[len(decrypted)-1])
   118  	if psLen == 0 || psLen > blockSize {
   119  		return nil, ErrDecryption
   120  	}
   121  
   122  	if len(decrypted) < psLen {
   123  		return nil, ErrDecryption
   124  	}
   125  	ps := decrypted[len(decrypted)-psLen:]
   126  	decrypted = decrypted[:len(decrypted)-psLen]
   127  	if bytes.Compare(ps, bytes.Repeat([]byte{byte(psLen)}, psLen)) != 0 {
   128  		return nil, ErrDecryption
   129  	}
   130  
   131  	return
   132  }
   133  
   134  func pad(src []byte, blockSize int) []byte {
   135  	paddingLength := blockSize - len(src)%blockSize
   136  	paddingText := bytes.Repeat([]byte{byte(paddingLength)}, paddingLength)
   137  	return append(src, paddingText...)
   138  }
   139  
   140  func pbEncrypt(plainText, salt, password []byte, iterations int) (cipherText []byte, err error) {
   141  	if _, err := io.ReadFull(rand.Reader, salt); err != nil {
   142  		return nil, errors.New("pkcs12: failed to create a random salt value: " + err.Error())
   143  	}
   144  
   145  	cipherType := shaWithTripleDESCBC{}
   146  	key := cipherType.deriveKey(salt, password, iterations)
   147  	iv := cipherType.deriveIV(salt, password, iterations)
   148  
   149  	block, err := cipherType.create(key)
   150  	if err != nil {
   151  		return nil, errors.New("pkcs12: failed to create a block cipher: " + err.Error())
   152  	}
   153  
   154  	paddedPlainText := pad(plainText, block.BlockSize())
   155  
   156  	encrypter := cipher.NewCBCEncrypter(block, iv)
   157  	cipherText = make([]byte, len(paddedPlainText))
   158  	encrypter.CryptBlocks(cipherText, paddedPlainText)
   159  
   160  	return cipherText, nil
   161  }
   162  
   163  // decryptable abstracts a object that contains ciphertext.
   164  type decryptable interface {
   165  	Algorithm() pkix.AlgorithmIdentifier
   166  	Data() []byte
   167  }