github.com/jlmucb/cloudproxy@v0.0.0-20170830161738-b5aa0b619bc4/go/tao/keys.go (about)

     1  //  Copyright (c) 2014, Google Inc.  All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package tao
    16  
    17  import (
    18  	"bytes"
    19  	"crypto"
    20  	"crypto/aes"
    21  	"crypto/cipher"
    22  	"crypto/ecdsa"
    23  	"crypto/elliptic"
    24  	"crypto/hmac"
    25  	"crypto/rand"
    26  	"crypto/rsa"
    27  	"crypto/sha256"
    28  	"crypto/sha512"
    29  	"crypto/x509"
    30  	"crypto/x509/pkix"
    31  	"encoding/asn1"
    32  
    33  	"errors"
    34  	"fmt"
    35  	"log"
    36  	"math/big"
    37  	"time"
    38  
    39  	"github.com/golang/protobuf/proto"
    40  	"github.com/jlmucb/cloudproxy/go/tao/auth"
    41  
    42  	"golang.org/x/crypto/hkdf"
    43  )
    44  
    45  // A Signer is used to sign and verify signatures
    46  type Signer struct {
    47  	Header *CryptoHeader
    48  
    49  	PrivKey crypto.PrivateKey
    50  }
    51  
    52  // A Verifier is used to verify signatures.
    53  type Verifier struct {
    54  	Header *CryptoHeader
    55  
    56  	PubKey crypto.PublicKey
    57  }
    58  
    59  // A Crypter is used to encrypt and decrypt data.
    60  type Crypter struct {
    61  	Header *CryptoHeader
    62  
    63  	EncryptingKeyBytes []byte
    64  	HmacKeyBytes       []byte
    65  }
    66  
    67  // A Deriver is used to derive key material from a context using HKDF.
    68  type Deriver struct {
    69  	Header *CryptoHeader
    70  
    71  	Secret []byte
    72  }
    73  
    74  // ZeroBytes clears the bytes in a slice.
    75  func ZeroBytes(b []byte) {
    76  	for i := range b {
    77  		b[i] = 0
    78  	}
    79  }
    80  
    81  func randBytes(size int) ([]byte, error) {
    82  	buf := make([]byte, size)
    83  	_, err := rand.Read(buf)
    84  	return buf, err
    85  }
    86  
    87  func SerializeRsaPrivateComponents(rsaKey *rsa.PrivateKey) ([][]byte, error) {
    88  	// mod, e, d, p, q
    89  	var keyComponents [][]byte
    90  	if rsaKey.PublicKey.N == nil {
    91  		return nil, errors.New("No modulus")
    92  	}
    93  	keyComponents = append(keyComponents, rsaKey.PublicKey.N.Bytes())
    94  	e := rsaKey.PublicKey.E
    95  	eInt := big.NewInt(int64(e))
    96  	keyComponents = append(keyComponents, eInt.Bytes())
    97  	d := rsaKey.D
    98  	if d == nil {
    99  		return keyComponents, nil
   100  	}
   101  	keyComponents = append(keyComponents, d.Bytes())
   102  	p := rsaKey.Primes[0]
   103  	if p == nil {
   104  		return keyComponents, nil
   105  	}
   106  	keyComponents = append(keyComponents, p.Bytes())
   107  	q := rsaKey.Primes[1]
   108  	if q == nil {
   109  		return keyComponents, nil
   110  	}
   111  	keyComponents = append(keyComponents, q.Bytes())
   112  	return keyComponents, nil
   113  }
   114  
   115  func DeserializeRsaPrivateComponents(keyComponents [][]byte, rsaKey *rsa.PrivateKey) error {
   116  	if len(keyComponents) < 3 {
   117  		return errors.New("Too few key components")
   118  	}
   119  	rsaKey.PublicKey.N = new(big.Int)
   120  	rsaKey.PublicKey.N.SetBytes(keyComponents[0])
   121  	eInt := new(big.Int)
   122  	eInt.SetBytes(keyComponents[1])
   123  	rsaKey.PublicKey.E = int(eInt.Int64())
   124  	rsaKey.D = new(big.Int)
   125  	rsaKey.D.SetBytes(keyComponents[2])
   126  	if len(keyComponents) < 5 {
   127  		return nil
   128  	}
   129  	p := new(big.Int)
   130  	p.SetBytes(keyComponents[3])
   131  	q := new(big.Int)
   132  	q.SetBytes(keyComponents[4])
   133  	rsaKey.Primes = make([]*big.Int, 2)
   134  	rsaKey.Primes[0] = p
   135  	rsaKey.Primes[1] = q
   136  	return nil
   137  }
   138  
   139  func SerializeEcdsaPrivateComponents(ecKey *ecdsa.PrivateKey) ([]byte, error) {
   140  	return x509.MarshalECPrivateKey(ecKey)
   141  }
   142  
   143  func DeserializeEcdsaPrivateComponents(keyBytes []byte) (*ecdsa.PrivateKey, error) {
   144  	return x509.ParseECPrivateKey(keyBytes)
   145  }
   146  
   147  func SerializeRsaPublicComponents(rsaKey *rsa.PublicKey) ([][]byte, error) {
   148  	// should this use return x509.ParsePKIXPublicKey(keyBytes)?
   149  	// mod, e, d
   150  	var keyComponents [][]byte
   151  	if rsaKey.N == nil {
   152  		return nil, errors.New("No modulus")
   153  	}
   154  	keyComponents = append(keyComponents, rsaKey.N.Bytes())
   155  	eInt := big.NewInt(int64(rsaKey.E))
   156  	keyComponents = append(keyComponents, eInt.Bytes())
   157  	return keyComponents, nil
   158  }
   159  
   160  func DeserializeRsaPublicComponents(rsaKey *rsa.PublicKey, keyComponents [][]byte) error {
   161  	if len(keyComponents) < 2 {
   162  		return errors.New("Too few key components")
   163  	}
   164  	rsaKey.N = new(big.Int)
   165  	rsaKey.N.SetBytes(keyComponents[0])
   166  	eInt := new(big.Int)
   167  	eInt.SetBytes(keyComponents[1])
   168  	rsaKey.E = int(eInt.Int64())
   169  	return nil
   170  }
   171  
   172  func SerializeEcdsaPublicComponents(ecKey *ecdsa.PublicKey) ([]byte, error) {
   173  	return x509.MarshalPKIXPublicKey(ecKey)
   174  }
   175  
   176  func DeserializeEcdsaPublicComponents(keyBytes []byte) (crypto.PrivateKey, error) {
   177  	return x509.ParsePKIXPublicKey(keyBytes)
   178  }
   179  
   180  func KeyComponentsFromSigner(s *Signer) ([][]byte, error) {
   181  	var keyComponents [][]byte
   182  	if s.Header.KeyType == nil {
   183  		return nil, errors.New("Empty key type")
   184  	}
   185  	switch *s.Header.KeyType {
   186  	case "rsa1024", "rsa2048", "rsa3072":
   187  		// Serialize modulus, public-exponent, private-exponent, P, Q
   188  		keyComponents, err := SerializeRsaPrivateComponents((s.PrivKey).(*rsa.PrivateKey))
   189  		if err != nil {
   190  			return nil, errors.New("Can't Serialize")
   191  		}
   192  		return keyComponents, nil
   193  	case "ecdsap256", "ecdsap384", "ecdsap521":
   194  		// Serialize
   195  		keyComponent, err := SerializeEcdsaPrivateComponents((s.PrivKey).(*ecdsa.PrivateKey))
   196  		if err != nil {
   197  			return nil, errors.New("Can't Serialize")
   198  		}
   199  		keyComponents = append(keyComponents, keyComponent)
   200  		return keyComponents, nil
   201  	default:
   202  		return nil, errors.New("Unknown signer key")
   203  	}
   204  	return keyComponents, nil
   205  }
   206  
   207  func KeyComponentsFromVerifier(v *Verifier) ([][]byte, error) {
   208  	var keyComponents [][]byte
   209  	if v.Header.KeyType == nil {
   210  		return nil, errors.New("Empty key type")
   211  	}
   212  	switch *v.Header.KeyType {
   213  	case "rsa1024-public", "rsa2048-public", "rsa3072-public":
   214  		// Serialize modulus, public-exponent, private-exponent, P, Q
   215  		keyComponents, err := SerializeRsaPublicComponents((v.PubKey).(*rsa.PublicKey))
   216  		if err != nil {
   217  			return nil, errors.New("Can't Serialize")
   218  		}
   219  		return keyComponents, nil
   220  	case "ecdsap256-public", "ecdsap384-public", "ecdsap521-public":
   221  		// Serialize
   222  		keyComponent, err := SerializeEcdsaPublicComponents((v.PubKey).(*ecdsa.PublicKey))
   223  		if err != nil {
   224  			return nil, errors.New("Can't Serialize")
   225  		}
   226  		keyComponents = append(keyComponents, keyComponent)
   227  		return keyComponents, nil
   228  	default:
   229  	}
   230  	return keyComponents, nil
   231  }
   232  
   233  func KeyComponentsFromCrypter(c *Crypter) ([][]byte, error) {
   234  	var keyComponents [][]byte
   235  	if c.Header.KeyType == nil {
   236  		return nil, errors.New("Empty key type")
   237  	}
   238  	switch *c.Header.KeyType {
   239  	case "aes128-ctr-hmacsha256", "aes256-ctr-hmacsha384", "aes256-ctr-hmacsha512":
   240  		keyComponents = append(keyComponents, c.EncryptingKeyBytes)
   241  		keyComponents = append(keyComponents, c.HmacKeyBytes)
   242  	default:
   243  		return nil, errors.New("Unknown crypter key")
   244  	}
   245  	return keyComponents, nil
   246  }
   247  
   248  func KeyComponentsFromDeriver(d *Deriver) ([][]byte, error) {
   249  	var keyComponents [][]byte
   250  	if d.Header.KeyType == nil {
   251  		return nil, errors.New("Empty key type")
   252  	}
   253  	switch *d.Header.KeyType {
   254  	case "hdkf-sha256":
   255  		keyComponents = append(keyComponents, d.Secret)
   256  		return keyComponents, nil
   257  	default:
   258  		return nil, errors.New("Unknown deriver key")
   259  	}
   260  	return keyComponents, nil
   261  }
   262  
   263  func PrivateKeyFromCryptoKey(k CryptoKey) (crypto.PrivateKey, error) {
   264  	if k.KeyHeader.KeyType == nil {
   265  		return nil, errors.New("Empty key type")
   266  	}
   267  	switch *k.KeyHeader.KeyType {
   268  	case "rsa1024", "rsa2048", "rsa3072":
   269  		rsaKey := new(rsa.PrivateKey)
   270  		err := DeserializeRsaPrivateComponents(k.KeyComponents, rsaKey)
   271  		if err != nil {
   272  			return nil, errors.New("Can't DeserializeRsaPrivateComponents")
   273  		}
   274  		return crypto.PrivateKey(rsaKey), nil
   275  	case "ecdsap256", "ecdsap384", "ecdsap521":
   276  		ecKey, err := DeserializeEcdsaPrivateComponents(k.KeyComponents[0])
   277  		if err != nil {
   278  			return nil, errors.New("Can't DeserializeEcdsaPrivateComponents")
   279  		}
   280  		return crypto.PrivateKey(ecKey), nil
   281  	default:
   282  	}
   283  	return nil, errors.New("Unsupported key type")
   284  }
   285  
   286  func PublicKeyFromCryptoKey(k CryptoKey) (crypto.PublicKey, error) {
   287  	var publicKey crypto.PublicKey
   288  	if k.KeyHeader == nil {
   289  		return nil, errors.New("Empty key header")
   290  	}
   291  	switch *k.KeyHeader.KeyType {
   292  	case "rsa1024-public", "rsa2048-public", "rsa3072-public":
   293  		rsaKey := new(rsa.PublicKey)
   294  		err := DeserializeRsaPublicComponents(rsaKey, k.KeyComponents)
   295  		if err != nil {
   296  			return nil, errors.New("Can't DeserializeRsaPublicComponents")
   297  		}
   298  		publicKey = crypto.PublicKey(rsaKey)
   299  		return publicKey, nil
   300  	case "ecdsap256-public", "ecdsap521-public", "ecdsap384-public":
   301  		ecKey, err := DeserializeEcdsaPublicComponents(k.KeyComponents[0])
   302  		if err != nil {
   303  			return nil, errors.New("Can't DeserializeEcdsaPublicComponents")
   304  		}
   305  		publicKey = crypto.PublicKey(ecKey)
   306  		return publicKey, nil
   307  	default:
   308  		return nil, errors.New("Unsupported key type")
   309  	}
   310  	return publicKey, errors.New("Unsupported key type")
   311  }
   312  
   313  func (k *CryptoKey) Clear() {
   314  	for i := 0; i < len(k.KeyComponents); i++ {
   315  		ZeroBytes(k.KeyComponents[i])
   316  	}
   317  }
   318  
   319  func (s *Signer) Clear() {
   320  	if (s.PrivKey).(*ecdsa.PrivateKey) != nil {
   321  		// TODO: ZeroBytes([]byte((s.PrivKey).(*ecdsa.PrivateKey)))
   322  	} else if (s.PrivKey).(*rsa.PrivateKey) != nil {
   323  	}
   324  }
   325  
   326  func (c *Crypter) Clear() {
   327  	ZeroBytes(c.EncryptingKeyBytes)
   328  	ZeroBytes(c.HmacKeyBytes)
   329  }
   330  
   331  func (d *Deriver) Clear() {
   332  	ZeroBytes(d.Secret)
   333  }
   334  
   335  func CryptoKeyFromSigner(s *Signer) (*CryptoKey, error) {
   336  	keyComponents, err := KeyComponentsFromSigner(s)
   337  	if err != nil {
   338  		return nil, errors.New("Can't get key components")
   339  	}
   340  	ck := &CryptoKey{
   341  		KeyHeader: s.Header,
   342  	}
   343  	ck.KeyComponents = keyComponents
   344  	return ck, nil
   345  }
   346  
   347  func CryptoKeyFromVerifier(v *Verifier) (*CryptoKey, error) {
   348  	keyComponents, err := KeyComponentsFromVerifier(v)
   349  	if err != nil {
   350  		return nil, errors.New("Can't get key components")
   351  	}
   352  	ck := &CryptoKey{
   353  		KeyHeader: v.Header,
   354  	}
   355  	ck.KeyComponents = keyComponents
   356  	return ck, nil
   357  }
   358  
   359  func CryptoKeyFromCrypter(c *Crypter) (*CryptoKey, error) {
   360  	keyComponents, err := KeyComponentsFromCrypter(c)
   361  	if err != nil {
   362  		return nil, errors.New("Can't get key components")
   363  	}
   364  	ck := &CryptoKey{
   365  		KeyHeader: c.Header,
   366  	}
   367  	ck.KeyComponents = keyComponents
   368  	return ck, nil
   369  }
   370  
   371  func CryptoKeyFromDeriver(d *Deriver) (*CryptoKey, error) {
   372  	keyComponents, err := KeyComponentsFromDeriver(d)
   373  	if err != nil {
   374  		return nil, errors.New("Can't get key components")
   375  	}
   376  	ck := &CryptoKey{
   377  		KeyHeader: d.Header,
   378  	}
   379  	ck.KeyComponents = keyComponents
   380  	return ck, nil
   381  }
   382  
   383  func PrintCryptoKeyHeader(header CryptoHeader) {
   384  	if header.Version == nil || *header.Version != CryptoVersion_CRYPTO_VERSION_2 {
   385  		fmt.Printf("Wrong version\n")
   386  	}
   387  	if header.KeyName == nil {
   388  		fmt.Printf("No key name\n")
   389  	} else {
   390  		fmt.Printf("Key name: %s\n", *header.KeyName)
   391  	}
   392  	if header.KeyType == nil {
   393  		fmt.Printf("No key type\n")
   394  	} else {
   395  		fmt.Printf("Key type: %s\n", *header.KeyType)
   396  	}
   397  	if header.KeyPurpose == nil {
   398  		fmt.Printf("No Purpose\n")
   399  	} else {
   400  		fmt.Printf("Purpose: %s\n", *header.KeyPurpose)
   401  	}
   402  	if header.KeyStatus == nil {
   403  		fmt.Printf("No key status\n")
   404  	} else {
   405  		fmt.Printf("Key status: %s\n", *header.KeyStatus)
   406  	}
   407  }
   408  
   409  func PrintCryptoKey(cryptoKey *CryptoKey) {
   410  	if cryptoKey.KeyHeader == nil {
   411  		fmt.Printf("No key header\n")
   412  		return
   413  	}
   414  	PrintCryptoKeyHeader(*cryptoKey.KeyHeader)
   415  	n := len(cryptoKey.KeyComponents)
   416  	for i := 0; i < n; i++ {
   417  		fmt.Printf("Component %d: %x\n", i, cryptoKey.KeyComponents[i])
   418  	}
   419  }
   420  
   421  func MarshalCryptoKey(ck CryptoKey) []byte {
   422  	b, err := proto.Marshal(&ck)
   423  	if err != nil {
   424  		return nil
   425  	}
   426  	return b
   427  }
   428  
   429  func UnmarshalCryptoKey(bytes []byte) (*CryptoKey, error) {
   430  	ck := new(CryptoKey)
   431  	err := proto.Unmarshal(bytes, ck)
   432  	if err != nil {
   433  		return nil, err
   434  	}
   435  	return ck, nil
   436  }
   437  
   438  func GenerateCryptoKey(keyType string, keyName *string, keyEpoch *int32, keyPurpose *string, keyStatus *string) *CryptoKey {
   439  	cryptoKey := new(CryptoKey)
   440  	switch keyType {
   441  	case "aes128-raw":
   442  		keyBuf, err := randBytes(16)
   443  		if err != nil {
   444  			return nil
   445  		}
   446  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyBuf)
   447  	case "aes256-raw":
   448  		keyBuf, err := randBytes(32)
   449  		if err != nil {
   450  			return nil
   451  		}
   452  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyBuf)
   453  	case "aes128-ctr":
   454  		keyBuf, err := randBytes(16)
   455  		if err != nil {
   456  			return nil
   457  		}
   458  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyBuf)
   459  		ivBuf, err := randBytes(16)
   460  		if err != nil {
   461  			return nil
   462  		}
   463  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, ivBuf)
   464  	case "aes256-ctr":
   465  		keyBuf, err := randBytes(32)
   466  		if err != nil {
   467  			return nil
   468  		}
   469  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyBuf)
   470  		hmacBuf, err := randBytes(32)
   471  		if err != nil {
   472  			return nil
   473  		}
   474  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, hmacBuf)
   475  	case "aes128-ctr-hmacsha256":
   476  		keyBuf, err := randBytes(16)
   477  		if err != nil {
   478  			return nil
   479  		}
   480  		hmacBuf, err := randBytes(32)
   481  		if err != nil {
   482  			return nil
   483  		}
   484  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyBuf)
   485  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, hmacBuf)
   486  	case "aes256-ctr-hmacsha384":
   487  		keyBuf, err := randBytes(32)
   488  		if err != nil {
   489  			return nil
   490  		}
   491  		hmacBuf, err := randBytes(48)
   492  		if err != nil {
   493  			return nil
   494  		}
   495  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyBuf)
   496  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, hmacBuf)
   497  	case "aes256-ctr-hmacsha512":
   498  		keyBuf, err := randBytes(32)
   499  		if err != nil {
   500  			return nil
   501  		}
   502  		hmacBuf, err := randBytes(64)
   503  		if err != nil {
   504  			return nil
   505  		}
   506  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyBuf)
   507  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, hmacBuf)
   508  	case "hmacsha256":
   509  		keyBuf, err := randBytes(32)
   510  		if err != nil {
   511  			return nil
   512  		}
   513  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyBuf)
   514  	case "hmacsha384":
   515  		keyBuf, err := randBytes(48)
   516  		if err != nil {
   517  			return nil
   518  		}
   519  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyBuf)
   520  	case "hmacsha512":
   521  		keyBuf, err := randBytes(64)
   522  		if err != nil {
   523  			return nil
   524  		}
   525  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyBuf)
   526  	case "rsa1024":
   527  		rsaKey, err := rsa.GenerateKey(rand.Reader, 1024)
   528  		if err != nil {
   529  			return nil
   530  		}
   531  		// Serialize modulus, public-exponent, private-exponent, P, Q
   532  		keyComponents, err := SerializeRsaPrivateComponents(rsaKey)
   533  		if err != nil {
   534  			return nil
   535  		}
   536  		for i := 0; i < len(keyComponents); i++ {
   537  			cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyComponents[i])
   538  		}
   539  	case "rsa2048":
   540  		rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
   541  		if err != nil {
   542  			return nil
   543  		}
   544  		keyComponents, err := SerializeRsaPrivateComponents(rsaKey)
   545  		if err != nil {
   546  			return nil
   547  		}
   548  		for i := 0; i < len(keyComponents); i++ {
   549  			cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyComponents[i])
   550  		}
   551  	case "rsa3072":
   552  		rsaKey, err := rsa.GenerateKey(rand.Reader, 3072)
   553  		if err != nil {
   554  			return nil
   555  		}
   556  		keyComponents, err := SerializeRsaPrivateComponents(rsaKey)
   557  		if err != nil {
   558  			return nil
   559  		}
   560  		for i := 0; i < len(keyComponents); i++ {
   561  			cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyComponents[i])
   562  		}
   563  	case "ecdsap256":
   564  		ecKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
   565  		if err != nil {
   566  			return nil
   567  		}
   568  		keyComponent, err := SerializeEcdsaPrivateComponents(ecKey)
   569  		if err != nil {
   570  			return nil
   571  		}
   572  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyComponent)
   573  	case "ecdsap384":
   574  		ecKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
   575  		if err != nil {
   576  			return nil
   577  		}
   578  		keyComponent, err := SerializeEcdsaPrivateComponents(ecKey)
   579  		if err != nil {
   580  			return nil
   581  		}
   582  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyComponent)
   583  	case "ecdsap521":
   584  		ecKey, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
   585  		if err != nil {
   586  			return nil
   587  		}
   588  		keyComponent, err := SerializeEcdsaPrivateComponents(ecKey)
   589  		if err != nil {
   590  			return nil
   591  		}
   592  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyComponent)
   593  	case "hdkf-sha256":
   594  		keyBuf, err := randBytes(32)
   595  		if err != nil {
   596  			return nil
   597  		}
   598  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyBuf)
   599  	case "hdkf-sha384":
   600  		keyBuf, err := randBytes(48)
   601  		if err != nil {
   602  			return nil
   603  		}
   604  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyBuf)
   605  	case "hdkf-sha512":
   606  		keyBuf, err := randBytes(64)
   607  		if err != nil {
   608  			return nil
   609  		}
   610  		cryptoKey.KeyComponents = append(cryptoKey.KeyComponents, keyBuf)
   611  	default:
   612  		return nil
   613  	}
   614  	ver := CryptoVersion_CRYPTO_VERSION_2
   615  	ch := &CryptoHeader{
   616  		Version:    &ver,
   617  		KeyName:    keyName,
   618  		KeyEpoch:   keyEpoch,
   619  		KeyType:    &keyType,
   620  		KeyPurpose: keyPurpose,
   621  		KeyStatus:  keyStatus,
   622  	}
   623  	cryptoKey.KeyHeader = ch
   624  	return cryptoKey
   625  }
   626  
   627  func SignerFromCryptoKey(k CryptoKey) *Signer {
   628  	privateKey, err := PrivateKeyFromCryptoKey(k)
   629  	if err != nil {
   630  		return nil
   631  	}
   632  	if k.KeyHeader.KeyType == nil {
   633  		return nil
   634  	}
   635  	s := &Signer{
   636  		Header:  k.KeyHeader,
   637  		PrivKey: privateKey,
   638  	}
   639  	return s
   640  }
   641  
   642  func VerifierFromCryptoKey(k CryptoKey) *Verifier {
   643  	publicKey, err := PublicKeyFromCryptoKey(k)
   644  	if err != nil {
   645  		return nil
   646  	}
   647  	if k.KeyHeader.KeyType == nil {
   648  		return nil
   649  	}
   650  	v := &Verifier{
   651  		Header: k.KeyHeader,
   652  		PubKey: publicKey,
   653  	}
   654  	return v
   655  }
   656  
   657  func CrypterFromCryptoKey(k CryptoKey) *Crypter {
   658  	if k.KeyHeader.KeyType == nil {
   659  		return nil
   660  	}
   661  	c := &Crypter{
   662  		Header: k.KeyHeader,
   663  	}
   664  	switch *k.KeyHeader.KeyType {
   665  	case "aes128-ctr", "aes256-ctr":
   666  		c.EncryptingKeyBytes = k.KeyComponents[0]
   667  	case "aes128-gcm", "aes256-gcm",
   668  		"aes128-ctr-hmacsha256", "aes256-ctr-hmacsha384", "aes256-ctr-hmacsha512":
   669  		c.EncryptingKeyBytes = k.KeyComponents[0]
   670  		c.HmacKeyBytes = k.KeyComponents[1]
   671  	case "hmacsha256", "hmacsha384", "hmacsha512":
   672  		c.HmacKeyBytes = k.KeyComponents[1]
   673  	default:
   674  		return nil
   675  	}
   676  	return c
   677  }
   678  
   679  func DeriverFromCryptoKey(k CryptoKey) *Deriver {
   680  	d := &Deriver{
   681  		Header: k.KeyHeader,
   682  		Secret: k.KeyComponents[0],
   683  	}
   684  	return d
   685  }
   686  
   687  func (s *Signer) GetVerifierFromSigner() *Verifier {
   688  	var pub crypto.PublicKey
   689  	if s.Header.KeyType == nil {
   690  		return nil
   691  	}
   692  	switch *s.Header.KeyType {
   693  	case "rsa1024", "rsa2048", "rsa3072":
   694  		pub = &(s.PrivKey).(*rsa.PrivateKey).PublicKey
   695  		break
   696  	case "ecdsap256", "ecdsap384", "ecdsap521":
   697  		pub = &(s.PrivKey).(*ecdsa.PrivateKey).PublicKey
   698  		break
   699  	default:
   700  		return nil
   701  	}
   702  	newKeyType := *s.Header.KeyType + "-public"
   703  	var newHeader CryptoHeader
   704  	newHeader.Version = s.Header.Version
   705  	newHeader.KeyName = s.Header.KeyName
   706  	newHeader.KeyEpoch = s.Header.KeyEpoch
   707  	newHeader.KeyType = &newKeyType
   708  	strVerifying := "verifying"
   709  	newHeader.KeyPurpose = &strVerifying
   710  	newHeader.KeyStatus = s.Header.KeyStatus
   711  	v := &Verifier{
   712  		Header: &newHeader,
   713  		PubKey: pub,
   714  	}
   715  	return v
   716  }
   717  
   718  func VerifierKeyFromCanonicalKeyBytes(vb []byte) (*Verifier, error) {
   719  	publicKey, err := x509.ParsePKIXPublicKey(vb)
   720  	if err != nil {
   721  		return nil, err
   722  	}
   723  	keyName := "Anonymous_verifier"
   724  	keyType := VerifierTypeFromSuiteName(TaoCryptoSuite)
   725  	keyPurpose := "verifying"
   726  	keyStatus := "active"
   727  	keyEpoch := int32(1)
   728  	ch := &CryptoHeader{
   729  		KeyName:    &keyName,
   730  		KeyType:    keyType,
   731  		KeyPurpose: &keyPurpose,
   732  		KeyStatus:  &keyStatus,
   733  		KeyEpoch:   &keyEpoch,
   734  	}
   735  	v := &Verifier{
   736  		Header: ch,
   737  		PubKey: publicKey,
   738  	}
   739  	return v, nil
   740  }
   741  
   742  func (v *Verifier) GetVerifierPublicKey() crypto.PublicKey {
   743  	return v.PubKey
   744  }
   745  
   746  func (s *Signer) GetSignerPrivateKey() crypto.PrivateKey {
   747  	return s.PrivKey
   748  }
   749  
   750  func (v *Verifier) CanonicalKeyBytesFromVerifier() ([]byte, error) {
   751  	return x509.MarshalPKIXPublicKey(v.PubKey)
   752  }
   753  
   754  func (s *Signer) CanonicalKeyBytesFromSigner() ([]byte, error) {
   755  	return s.GetVerifierFromSigner().CanonicalKeyBytesFromVerifier()
   756  }
   757  
   758  func MakeUniversalKeyNameFromCanonicalBytes(cn []byte) []byte {
   759  	// FIX: Should the algorithm be selected from TaoCryptoSuite
   760  	h := sha256.Sum256(cn)
   761  	return h[0:32]
   762  }
   763  
   764  func (s *Signer) UniversalKeyNameFromSigner() ([]byte, error) {
   765  	return s.GetVerifierFromSigner().UniversalKeyNameFromVerifier()
   766  }
   767  
   768  func (v *Verifier) UniversalKeyNameFromVerifier() ([]byte, error) {
   769  	kb, err := v.CanonicalKeyBytesFromVerifier()
   770  	if err != nil {
   771  		return nil, err
   772  	}
   773  	return MakeUniversalKeyNameFromCanonicalBytes(kb), nil
   774  }
   775  
   776  // ToPrincipal produces a "key" type Prin for this signer. This contains a
   777  // serialized CryptoKey for the public portion of the signing key.
   778  func (s *Signer) ToPrincipal() auth.Prin {
   779  	var empty []byte
   780  	// Note: ToPrincipal returns keybytes not universal name
   781  	data, err := s.CanonicalKeyBytesFromSigner()
   782  	if err != nil {
   783  		return auth.NewKeyPrin(empty)
   784  	}
   785  	return auth.NewKeyPrin(data)
   786  }
   787  
   788  // ToPrincipal produces a "key" type Prin for this verifier. This contains a
   789  // hash of a serialized CryptoKey for this key.
   790  func (v *Verifier) ToPrincipal() auth.Prin {
   791  	// Note: ToPrincipal returns keybytes not universal name
   792  	var empty []byte
   793  	data, err := v.CanonicalKeyBytesFromVerifier()
   794  	if err != nil {
   795  		return auth.NewKeyPrin(empty)
   796  	}
   797  	return auth.NewKeyPrin(data)
   798  }
   799  
   800  // NewX509Name returns a new pkix.Name.
   801  func NewX509Name(p *X509Details) *pkix.Name {
   802  	return &pkix.Name{
   803  		Country:            []string{p.GetCountry()},
   804  		Organization:       []string{p.GetOrganization()},
   805  		OrganizationalUnit: []string{p.GetOrganizationalUnit()},
   806  		Province:           []string{p.GetState()},
   807  		CommonName:         string(p.GetCommonName()),
   808  	}
   809  }
   810  
   811  func PrintPKIXName(title string, name *pkix.Name) {
   812  	log.Printf("%s common name: %s, ", title, name.CommonName)
   813  	for i := 0 ; i < len(name.Organization); i++ {
   814  		log.Printf("organization: %s, ", name.Organization[i])
   815  	}
   816  	for i := 0 ; i < len(name.OrganizationalUnit); i++ {
   817  		log.Printf("organization unit: %s, ", name.OrganizationalUnit[i])
   818  	}
   819  	log.Printf("\n")
   820  }
   821  
   822  // PrepareX509Template fills out an X.509 template for use in x509.CreateCertificate.
   823  func PrepareX509Template(pkAlg int, sigAlg int, sn int64, subjectName *pkix.Name) *x509.Certificate {
   824  	return &x509.Certificate{
   825  		SignatureAlgorithm: x509.ECDSAWithSHA256,
   826  		PublicKeyAlgorithm: x509.ECDSA,
   827  		Version:            2, // x509v3
   828  		// It's always allowed for self-signed certs to have serial 1.
   829  		SerialNumber: new(big.Int).SetInt64(sn),
   830  		Subject:      *subjectName,
   831  		NotBefore:    time.Now(),
   832  		NotAfter:     time.Now().AddDate(1 /* years */, 0 /* months */, 0 /* days */),
   833  		// TODO(tmroeder): I'm not sure which of these I need to make
   834  		// OpenSSL happy.
   835  		KeyUsage:    x509.KeyUsageKeyAgreement | x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature,
   836  		ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
   837  	}
   838  }
   839  
   840  // CreateSelfSignedDER creates a DER representation of a new self-signed
   841  // certificate for the given name.
   842  func (s *Signer) CreateSelfSignedDER(pkAlg int, sigAlg int, sn int64, name *pkix.Name) ([]byte, error) {
   843  	template := PrepareX509Template(pkAlg, sigAlg, sn, name)
   844  	template.BasicConstraintsValid = true
   845  	template.IsCA = true
   846  	template.Issuer = template.Subject
   847  	if s.Header.KeyType == nil {
   848  		return nil, errors.New("No key type")
   849  	}
   850  	var pub interface{}
   851  	switch *s.Header.KeyType {
   852  	case "rsa1024", "rsa2048", "rsa3072":
   853  		pub = &(s.PrivKey).(*rsa.PrivateKey).PublicKey
   854  	case "ecdsap256", "ecdsap384", "ecdsap521":
   855  		pub = &(s.PrivKey).(*ecdsa.PrivateKey).PublicKey
   856  	default:
   857  		return nil, errors.New("Unsupported key type")
   858  	}
   859  	der, err := x509.CreateCertificate(rand.Reader, template, template, pub, s.PrivKey)
   860  	if err != nil {
   861  		return nil, err
   862  	}
   863  	return der, nil
   864  }
   865  
   866  // CreateSelfSignedX509 creates a self-signed X.509 certificate for the public
   867  // key of this Signer.
   868  func (s *Signer) CreateSelfSignedX509(pkAlg int, sigAlg int, sn int64, name *pkix.Name) (*x509.Certificate, error) {
   869  	template := PrepareX509Template(pkAlg, sigAlg, sn, name)
   870  	template.IsCA = true
   871  	template.BasicConstraintsValid = true
   872  	template.Issuer = template.Subject
   873  
   874  	if s.Header.KeyType == nil {
   875  		return nil, errors.New("No key type")
   876  	}
   877  	var pub interface{}
   878  	switch *s.Header.KeyType {
   879  	case "rsa1024", "rsa2048", "rsa3072":
   880  		pub = &(s.PrivKey).(*rsa.PrivateKey).PublicKey
   881  	case "ecdsap256", "ecdsap384", "ecdsap521":
   882  		pub = &(s.PrivKey).(*ecdsa.PrivateKey).PublicKey
   883  	default:
   884  		return nil, errors.New("Unsupported key type")
   885  	}
   886  
   887  	der, err := x509.CreateCertificate(rand.Reader, template, template, pub, s.PrivKey)
   888  	if err != nil {
   889  		return nil, err
   890  	}
   891  
   892  	return x509.ParseCertificate(der)
   893  }
   894  
   895  // CreateCRL creates a signed X.509 certificate list for revoked certificates.
   896  func (s *Signer) CreateCRL(cert *x509.Certificate, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) ([]byte, error) {
   897  	if cert == nil {
   898  		return nil, errors.New("Missing issuing certificate required to create CRL.")
   899  	}
   900  	return cert.CreateCRL(rand.Reader, s.PrivKey, revokedCerts, now, expiry)
   901  }
   902  
   903  // CreateSignedX509FromTemplate creates a signed X.509 certificate for some other subject's
   904  // key.
   905  func (s *Signer) CreateSignedX509FromTemplate(caCert *x509.Certificate, template *x509.Certificate,
   906  	subjectKey *Verifier, pkAlg int, sigAlg int) (*x509.Certificate, error) {
   907  
   908  	der, err := x509.CreateCertificate(rand.Reader, template, caCert, subjectKey.PubKey, s.PrivKey)
   909  	if err != nil {
   910  		return nil, err
   911  	}
   912  	return x509.ParseCertificate(der)
   913  }
   914  
   915  // CreateSignedX509 creates a signed X.509 certificate for some other subject's
   916  // key.
   917  // Should take template as argument.
   918  func (s *Signer) CreateSignedX509(caCert *x509.Certificate, sn int, subjectKey *Verifier,
   919  	pkAlg int, sigAlg int, subjectName *pkix.Name) (*x509.Certificate, error) {
   920  	template := PrepareX509Template(pkAlg, sigAlg, int64(sn), subjectName)
   921  	template.SerialNumber = new(big.Int).SetInt64(int64(sn))
   922  	return s.CreateSignedX509FromTemplate(caCert, template, subjectKey, pkAlg, sigAlg)
   923  }
   924  
   925  // Derive uses HKDF with HMAC-SHA256 to derive key bytes in its material
   926  // parameter.
   927  func (d *Deriver) Derive(salt, context, material []byte) error {
   928  	if d.Header.KeyType == nil {
   929  		return errors.New("Unspecified HKDF") 
   930  	}
   931  	switch *d.Header.KeyType {
   932  	default:
   933  		return errors.New("Unsupported HKDF") 
   934  	case "hdkf-sha256":
   935  		f := hkdf.New(sha256.New, d.Secret, salt, context)
   936  		if _, err := f.Read(material); err != nil {
   937  			return err
   938  		}
   939  	case "hdkf-sha384":
   940  		f := hkdf.New(sha512.New384, d.Secret, salt, context)
   941  		if _, err := f.Read(material); err != nil {
   942  			return err
   943  		}
   944  	case "hdkf-sha512":
   945  		f := hkdf.New(sha512.New, d.Secret, salt, context)
   946  		if _, err := f.Read(material); err != nil {
   947  			return err
   948  		}
   949  	}
   950  
   951  	return nil
   952  }
   953  
   954  // An ecdsaSignature wraps the two components of the signature from an ECDSA
   955  // private key. This is copied from the Go crypto/x509 source: it just uses a
   956  // simple two-element structure to marshal a DSA signature as ASN.1 in an X.509
   957  // certificate.
   958  type ecdsaSignature struct {
   959  	R, S *big.Int
   960  }
   961  
   962  // Sign computes a sigature over the contextualized data, using the
   963  // private key of the signer.
   964  func (s *Signer) Sign(data []byte, context string) ([]byte, error) {
   965  
   966  	var sig []byte
   967  
   968  	newKeyType := *s.Header.KeyType + "-public"
   969  	newHeader := *s.Header
   970  	newHeader.KeyType = &newKeyType
   971  
   972  	b, err := contextualizedSHA256(&newHeader, data, context, sha256.Size)
   973  	if err != nil {
   974  		return nil, err
   975  	}
   976  
   977  	// TODO(tmroeder): for compatibility with the C++ version, we should
   978  	// compute ECDSA signatures over hashes truncated to fit in the ECDSA
   979  	// signature.
   980  	if s.Header.KeyType == nil {
   981  		return nil, errors.New("Empty header")
   982  	}
   983  	switch *s.Header.KeyType {
   984  	case "ecdsap256", "ecdsap384", "ecdsap521":
   985  		R, S, err := ecdsa.Sign(rand.Reader, s.PrivKey.(*ecdsa.PrivateKey), b)
   986  		if err != nil {
   987  			return nil, err
   988  		}
   989  		sig, err = asn1.Marshal(ecdsaSignature{R, S})
   990  		if err != nil {
   991  			return nil, err
   992  		}
   993  	case "rsa1024", "rsa2048", "rsa3072":
   994  		// Use PSS?
   995  		// Change sig, err = s.PrivKey.(*rsa.PrivateKey).Sign(rand.Reader, b, nil)
   996  		sig, err = rsa.SignPKCS1v15(rand.Reader, s.PrivKey.(*rsa.PrivateKey), crypto.SHA256, b)
   997  		if err != nil {
   998  			return nil, err
   999  		}
  1000  	default:
  1001  		return nil, errors.New("Unsupported signing algorithm")
  1002  	}
  1003  
  1004  	sd := &SignedData{
  1005  		Header:    &newHeader,
  1006  		Signature: sig,
  1007  	}
  1008  	return proto.Marshal(sd)
  1009  }
  1010  
  1011  // Verify checks a signature over the contextualized data, using the
  1012  // public key of the verifier.
  1013  func (v *Verifier) Verify(data []byte, context string, sig []byte) (bool, error) {
  1014  	// Deserialize the data and extract the CryptoHeader.
  1015  	var sd SignedData
  1016  	if err := proto.Unmarshal(sig, &sd); err != nil {
  1017  		return false, err
  1018  	}
  1019  	if v == nil || v.Header == nil || v.Header.KeyType == nil || sd.Header == nil || sd.Header.KeyType == nil {
  1020  		return false, errors.New("NIL ptr")
  1021  	}
  1022  	if v.Header.KeyType == nil || sd.Header.KeyType == nil || *v.Header.KeyType != *sd.Header.KeyType {
  1023  		return false, errors.New("Wrong signature algorithm")
  1024  	}
  1025  
  1026  	switch *v.Header.KeyType {
  1027  	case "ecdsap256-public", "ecdsap384-public", "ecdsap521-public":
  1028  		var ecSig ecdsaSignature
  1029  		// We ignore the first parameter, since we don't mind if there's more
  1030  		// data after the signature.
  1031  		if _, err := asn1.Unmarshal(sd.Signature, &ecSig); err != nil {
  1032  			return false, err
  1033  		}
  1034  		b, err := contextualizedSHA256(sd.Header, data, context, sha256.Size)
  1035  		if err != nil {
  1036  			return false, err
  1037  		}
  1038  		return ecdsa.Verify((v.PubKey).(*ecdsa.PublicKey), b, ecSig.R, ecSig.S), nil
  1039  	case "rsa1024-public", "rsa2048-public", "rsa3072-public":
  1040  		b, err := contextualizedSHA256(sd.Header, data, context, sha256.Size)
  1041  		if err != nil {
  1042  			return false, err
  1043  		}
  1044  		err = rsa.VerifyPKCS1v15((v.PubKey).(*rsa.PublicKey), crypto.SHA256, b, sd.Signature)
  1045  		if err == nil {
  1046  			return true, nil
  1047  		}
  1048  		return false, err
  1049  	default:
  1050  		return false, errors.New("Unsupported signing algorithm")
  1051  	}
  1052  	return false, nil
  1053  }
  1054  
  1055  // MarshalKey serializes a Verifier.
  1056  func (v *Verifier) MarshalKey() []byte {
  1057  	var ck CryptoKey
  1058  	if v.Header == nil || v.Header.KeyType == nil {
  1059  		return nil
  1060  	}
  1061  	ck.KeyHeader = v.Header
  1062  
  1063  	switch *v.Header.KeyType {
  1064  	case "ecdsap256", "ecdsap384", "ecdsap521":
  1065  		keyComponent, err := SerializeEcdsaPublicComponents((v.PubKey).(*ecdsa.PublicKey))
  1066  		if err != nil {
  1067  			return nil
  1068  		}
  1069  		ck.KeyComponents = append(ck.KeyComponents, keyComponent)
  1070  		return MarshalCryptoKey(ck)
  1071  	default:
  1072  		return nil
  1073  	}
  1074  	return nil
  1075  }
  1076  
  1077  // UnmarshalKey deserializes a Verifier.
  1078  func UnmarshalKey(material []byte) (*Verifier, error) {
  1079  	var ck CryptoKey
  1080  	err := proto.Unmarshal(material, &ck)
  1081  	if err != nil {
  1082  		return nil, errors.New("Can't Unmarshal verifier")
  1083  	}
  1084  	// make sure its a verifying ecdsa key using sha
  1085  	if *ck.KeyHeader.KeyPurpose != "verifying" {
  1086  		return nil, errors.New("Not a verifying key")
  1087  	}
  1088  	v := VerifierFromCryptoKey(ck)
  1089  	if v == nil {
  1090  		return nil, errors.New("VerifierFromCryptoKey failed")
  1091  	}
  1092  	return v, nil
  1093  }
  1094  
  1095  // SignsForPrincipal returns true when prin is (or is a subprincipal of) this verifier key.
  1096  func (v *Verifier) SignsForPrincipal(prin auth.Prin) bool {
  1097  	return auth.SubprinOrIdentical(prin, v.ToPrincipal())
  1098  }
  1099  
  1100  func IsP256(ecPk *ecdsa.PublicKey) bool {
  1101  	// This check is insufficient
  1102  	if ecPk.Curve.Params().BitSize == 256 {
  1103  		return true
  1104  	}
  1105  	return false
  1106  }
  1107  
  1108  func IsP384(ecPk *ecdsa.PublicKey) bool {
  1109  	if ecPk.Curve.Params().BitSize == 384 {
  1110  		return true
  1111  	}
  1112  	return false
  1113  }
  1114  
  1115  func IsP521(ecPk *ecdsa.PublicKey) bool {
  1116  	if ecPk.Curve.Params().BitSize == 521 {
  1117  		return true
  1118  	}
  1119  	return false
  1120  }
  1121  
  1122  // VerifierFromX509 creates a Verifier from an X509 certificate.
  1123  func VerifierFromX509(cert *x509.Certificate) (*Verifier, error) {
  1124  	keyEpoch := int32(1)
  1125  	var keyType *string
  1126  	if cert.PublicKeyAlgorithm == x509.ECDSA {
  1127  		ecPk := cert.PublicKey.(*ecdsa.PublicKey)
  1128  		if IsP256(ecPk) {
  1129  			keyType = ptrFromString("ecdsap256-public")
  1130  		} else if IsP384(ecPk) {
  1131  			keyType = ptrFromString("ecdsap384-public")
  1132  		} else if IsP521(ecPk) {
  1133  			keyType = ptrFromString("ecdsap384-public")
  1134  		} else {
  1135  			return nil, errors.New("Unsupported ecdsa key type")
  1136  		}
  1137  	} else if cert.PublicKeyAlgorithm == x509.RSA {
  1138  		rsaPk := cert.PublicKey.(*rsa.PublicKey)
  1139  		if rsaPk.N.BitLen() > 1022 && rsaPk.N.BitLen() <= 1024 {
  1140  			keyType = ptrFromString("rsa1024-public")
  1141  		} else if rsaPk.N.BitLen() > 2046 && rsaPk.N.BitLen() <= 2048 {
  1142  			keyType = ptrFromString("rsa2048-public")
  1143  		} else if rsaPk.N.BitLen() > 3070 && rsaPk.N.BitLen() <= 3072 {
  1144  			keyType = ptrFromString("rsa3072-public")
  1145  		} else {
  1146  			return nil, errors.New("Unsupported rsa key type")
  1147  		}
  1148  		return nil, errors.New("RSA not supported in FromX509")
  1149  	} else {
  1150  		return nil, errors.New("Unsupported PublicKeyAlgorithm")
  1151  	}
  1152  	h := &CryptoHeader{
  1153  		KeyName:    ptrFromString("Anonymous verifying key"),
  1154  		KeyType:    keyType,
  1155  		KeyPurpose: ptrFromString("verifying"),
  1156  		KeyEpoch:   &keyEpoch,
  1157  		KeyStatus:  ptrFromString("active"),
  1158  	}
  1159  	v := &Verifier{
  1160  		Header: h,
  1161  		PubKey: cert.PublicKey,
  1162  	}
  1163  	return v, nil
  1164  }
  1165  
  1166  // Equals checks to see if the public key in the X.509 certificate matches the
  1167  // public key in the verifier.
  1168  func (v *Verifier) KeyEqual(cert *x509.Certificate) bool {
  1169  	v2, err := VerifierFromX509(cert)
  1170  	if err != nil {
  1171  		return false
  1172  	}
  1173  
  1174  	p := v.ToPrincipal()
  1175  	p2 := v2.ToPrincipal()
  1176  	return p.Identical(p2)
  1177  }
  1178  
  1179  // contextualizeData produces a single string from a header, data, and a context.
  1180  func contextualizeData(data []byte, context string) ([]byte, error) {
  1181  	s := &ContextualizedData{
  1182  		Context: proto.String(context),
  1183  		Data:    data,
  1184  	}
  1185  	return proto.Marshal(s)
  1186  }
  1187  
  1188  // contextualizedSHA256 performs a SHA-256 sum over contextualized data.
  1189  func contextualizedSHA256(h *CryptoHeader, data []byte, context string, digestLen int) ([]byte, error) {
  1190  	b, err := contextualizeData(data, context)
  1191  	if err != nil {
  1192  		return nil, err
  1193  	}
  1194  	hash := sha256.Sum256(b)
  1195  	return hash[:digestLen], nil
  1196  }
  1197  
  1198  // Handles both aes128/sha256 and aes256/sha256
  1199  func (c *Crypter) encryptAes128ctrHmacsha256(plain []byte) ([]byte, error) {
  1200  	block, err := aes.NewCipher(c.EncryptingKeyBytes)
  1201  	if err != nil {
  1202  		return nil, err
  1203  	}
  1204  
  1205  	// A ciphertext consists of an IV, encrypted bytes, and the output of
  1206  	// HMAC-SHA256.
  1207  	ciphertext := make([]byte, aes.BlockSize+len(plain))
  1208  	iv := ciphertext[:aes.BlockSize]
  1209  	if _, err := rand.Read(iv); err != nil {
  1210  		return nil, err
  1211  	}
  1212  
  1213  	s := cipher.NewCTR(block, iv)
  1214  	s.XORKeyStream(ciphertext[aes.BlockSize:], plain)
  1215  
  1216  	mac := hmac.New(sha256.New, c.HmacKeyBytes)
  1217  	mac.Write(ciphertext)
  1218  	m := mac.Sum(nil)
  1219  
  1220  	ed := &EncryptedData{
  1221  		Header:     c.Header,
  1222  		Iv:         iv,
  1223  		Ciphertext: ciphertext[aes.BlockSize:],
  1224  		Mac:        m,
  1225  	}
  1226  
  1227  	return proto.Marshal(ed)
  1228  }
  1229  
  1230  // Handles both aes128/sha256 and aes256/sha256
  1231  func (c *Crypter) decryptAes128ctrHmacsha256(ciphertext []byte) ([]byte, error) {
  1232  	var ed EncryptedData
  1233  	if err := proto.Unmarshal(ciphertext, &ed); err != nil {
  1234  		return nil, err
  1235  	}
  1236  	if *ed.Header.Version != CryptoVersion_CRYPTO_VERSION_2 {
  1237  		return nil, errors.New("bad version")
  1238  	}
  1239  	if ed.Header.KeyType == nil || c.Header.KeyType == nil {
  1240  		return nil, errors.New("empty key header")
  1241  	}
  1242  	if *ed.Header.KeyType != *c.Header.KeyType {
  1243  		return nil, errors.New("bad key type")
  1244  	}
  1245  
  1246  	// Check the HMAC before touching the ciphertext.
  1247  	fullCiphertext := make([]byte, len(ed.Iv)+len(ed.Ciphertext))
  1248  	copy(fullCiphertext, ed.Iv)
  1249  	copy(fullCiphertext[len(ed.Iv):], ed.Ciphertext)
  1250  
  1251  	mac := hmac.New(sha256.New, c.HmacKeyBytes)
  1252  	mac.Write(fullCiphertext)
  1253  	m := mac.Sum(nil)
  1254  	if !hmac.Equal(m, ed.Mac) {
  1255  		return nil, errors.New("bad HMAC")
  1256  	}
  1257  
  1258  	block, err := aes.NewCipher(c.EncryptingKeyBytes)
  1259  	if err != nil {
  1260  		return nil, err
  1261  	}
  1262  
  1263  	s := cipher.NewCTR(block, ed.Iv)
  1264  	plain := make([]byte, len(ed.Ciphertext))
  1265  	s.XORKeyStream(plain, ed.Ciphertext)
  1266  	return plain, nil
  1267  }
  1268  
  1269  func (c *Crypter) encryptAes256ctrHmacsha512(plain []byte) ([]byte, error) {
  1270  	block, err := aes.NewCipher(c.EncryptingKeyBytes)
  1271  	if err != nil {
  1272  		return nil, err
  1273  	}
  1274  
  1275  	// A ciphertext consists of an IV, encrypted bytes, and the output of
  1276  	// HMAC-SHA512.
  1277  	ciphertext := make([]byte, aes.BlockSize+len(plain))
  1278  	iv := ciphertext[:aes.BlockSize]
  1279  	if _, err := rand.Read(iv); err != nil {
  1280  		return nil, err
  1281  	}
  1282  
  1283  	s := cipher.NewCTR(block, iv)
  1284  	s.XORKeyStream(ciphertext[aes.BlockSize:], plain)
  1285  
  1286  	mac := hmac.New(sha512.New, c.HmacKeyBytes)
  1287  	mac.Write(ciphertext)
  1288  	m := mac.Sum(nil)
  1289  
  1290  	ed := &EncryptedData{
  1291  		Header:     c.Header,
  1292  		Iv:         iv,
  1293  		Ciphertext: ciphertext[aes.BlockSize:],
  1294  		Mac:        m,
  1295  	}
  1296  
  1297  	return proto.Marshal(ed)
  1298  }
  1299  
  1300  func (c *Crypter) decryptAes256ctrHmacsha512(ciphertext []byte) ([]byte, error) {
  1301  	var ed EncryptedData
  1302  	if err := proto.Unmarshal(ciphertext, &ed); err != nil {
  1303  		return nil, err
  1304  	}
  1305  	if *ed.Header.Version != CryptoVersion_CRYPTO_VERSION_2 {
  1306  		return nil, errors.New("bad version")
  1307  	}
  1308  	if ed.Header.KeyType == nil || c.Header.KeyType == nil {
  1309  		return nil, errors.New("empty key header")
  1310  	}
  1311  	if *ed.Header.KeyType != "aes256-ctr-hmacsha512" {
  1312  		return nil, errors.New("bad key type")
  1313  	}
  1314  
  1315  	// Check the HMAC before touching the ciphertext.
  1316  	fullCiphertext := make([]byte, len(ed.Iv)+len(ed.Ciphertext))
  1317  	copy(fullCiphertext, ed.Iv)
  1318  	copy(fullCiphertext[len(ed.Iv):], ed.Ciphertext)
  1319  
  1320  	mac := hmac.New(sha512.New, c.HmacKeyBytes)
  1321  	mac.Write(fullCiphertext)
  1322  	m := mac.Sum(nil)
  1323  	if !hmac.Equal(m, ed.Mac) {
  1324  		return nil, errors.New("bad HMAC")
  1325  	}
  1326  
  1327  	block, err := aes.NewCipher(c.EncryptingKeyBytes)
  1328  	if err != nil {
  1329  		return nil, err
  1330  	}
  1331  
  1332  	s := cipher.NewCTR(block, ed.Iv)
  1333  	plain := make([]byte, len(ed.Ciphertext))
  1334  	s.XORKeyStream(plain, ed.Ciphertext)
  1335  	return plain, nil
  1336  }
  1337  
  1338  func (c *Crypter) encryptAes256ctrHmacsha384(plain []byte) ([]byte, error) {
  1339  	block, err := aes.NewCipher(c.EncryptingKeyBytes)
  1340  	if err != nil {
  1341  		return nil, err
  1342  	}
  1343  
  1344  	// A ciphertext consists of an IV, encrypted bytes, and the output of
  1345  	// HMAC-SHA384.
  1346  	ciphertext := make([]byte, aes.BlockSize+len(plain))
  1347  	iv := ciphertext[:aes.BlockSize]
  1348  	if _, err := rand.Read(iv); err != nil {
  1349  		return nil, err
  1350  	}
  1351  
  1352  	s := cipher.NewCTR(block, iv)
  1353  	s.XORKeyStream(ciphertext[aes.BlockSize:], plain)
  1354  
  1355  	mac := hmac.New(sha512.New384, c.HmacKeyBytes)
  1356  	mac.Write(ciphertext)
  1357  	m := mac.Sum(nil)
  1358  
  1359  	ed := &EncryptedData{
  1360  		Header:     c.Header,
  1361  		Iv:         iv,
  1362  		Ciphertext: ciphertext[aes.BlockSize:],
  1363  		Mac:        m,
  1364  	}
  1365  
  1366  	return proto.Marshal(ed)
  1367  }
  1368  
  1369  func (c *Crypter) decryptAes256ctrHmacsha384(ciphertext []byte) ([]byte, error) {
  1370  	var ed EncryptedData
  1371  	if err := proto.Unmarshal(ciphertext, &ed); err != nil {
  1372  		return nil, err
  1373  	}
  1374  	if *ed.Header.Version != CryptoVersion_CRYPTO_VERSION_2 {
  1375  		return nil, errors.New("bad version")
  1376  	}
  1377  	if ed.Header.KeyType == nil || c.Header.KeyType == nil {
  1378  		return nil, errors.New("empty key header")
  1379  	}
  1380  	if *ed.Header.KeyType != "aes256-ctr-hmacsha384" {
  1381  		return nil, errors.New("bad key type")
  1382  	}
  1383  
  1384  	// Check the HMAC before touching the ciphertext.
  1385  	fullCiphertext := make([]byte, len(ed.Iv)+len(ed.Ciphertext))
  1386  	copy(fullCiphertext, ed.Iv)
  1387  	copy(fullCiphertext[len(ed.Iv):], ed.Ciphertext)
  1388  
  1389  	mac := hmac.New(sha512.New384, c.HmacKeyBytes)
  1390  	mac.Write(fullCiphertext)
  1391  	m := mac.Sum(nil)
  1392  	if !hmac.Equal(m, ed.Mac) {
  1393  		return nil, errors.New("bad HMAC")
  1394  	}
  1395  
  1396  	block, err := aes.NewCipher(c.EncryptingKeyBytes)
  1397  	if err != nil {
  1398  		return nil, err
  1399  	}
  1400  
  1401  	s := cipher.NewCTR(block, ed.Iv)
  1402  	plain := make([]byte, len(ed.Ciphertext))
  1403  	s.XORKeyStream(plain, ed.Ciphertext)
  1404  	return plain, nil
  1405  }
  1406  
  1407  // Encrypt encrypts plaintext into ciphertext with integrity
  1408  // with a MAC.
  1409  func (c *Crypter) Encrypt(plain []byte) ([]byte, error) {
  1410  	if c == nil || c.Header == nil || c.Header.KeyType == nil {
  1411  		return nil, errors.New("Key Type not set")
  1412  	}
  1413  	switch *c.Header.KeyType {
  1414  	case "aes128-ctr-hmacsha256":
  1415  		return c.encryptAes128ctrHmacsha256(plain)
  1416  	case "aes256-ctr-hmacsha384":
  1417  		return c.encryptAes256ctrHmacsha384(plain)
  1418  	case "aes256-ctr-hmacsha512":
  1419  		return c.encryptAes256ctrHmacsha512(plain)
  1420  	default:
  1421  		return nil, errors.New("Unsupported crypting algorithm")
  1422  	}
  1423  }
  1424  
  1425  // Decrypt checks the MAC then decrypts ciphertext into plaintext.
  1426  func (c *Crypter) Decrypt(ciphertext []byte) ([]byte, error) {
  1427  	if c.Header.KeyType == nil {
  1428  		return nil, errors.New("Key Type not set")
  1429  	}
  1430  	switch *c.Header.KeyType {
  1431  	case "aes128-ctr-hmacsha256":
  1432  		return c.decryptAes128ctrHmacsha256(ciphertext)
  1433  	case "aes256-ctr-hmacsha384":
  1434  		return c.decryptAes256ctrHmacsha384(ciphertext)
  1435  	case "aes256-ctr-hmacsha512":
  1436  		return c.decryptAes256ctrHmacsha512(ciphertext)
  1437  	default:
  1438  		return nil, errors.New("Unsupported crypting algorithm")
  1439  	}
  1440  }
  1441  
  1442  // This code is duplicated in VerifierFromCanonicalBytes
  1443  // MarshalSignerDER serializes the signer to DER.
  1444  func MarshalSignerDER(s *Signer) ([]byte, error) {
  1445  	// TODO: only ecdsa is supported, but this code is redundant now.
  1446  	if s.Header.KeyType == nil {
  1447  		return nil, errors.New("Unsupported alg for MarshalSignerDER")
  1448  	}
  1449  	switch *s.Header.KeyType {
  1450  	case "ecdsap256", "ecdsap384", "ecdsap521":
  1451  		return x509.MarshalECPrivateKey((s.PrivKey).(*ecdsa.PrivateKey))
  1452  	default:
  1453  		return nil, errors.New("Unsupported alg for MarshalSignerDER")
  1454  	}
  1455  	return nil, errors.New("Unsupported alg for MarshalSignerDER")
  1456  }
  1457  
  1458  // UnmarshalSignerDER deserializes a Signer from DER.
  1459  func UnmarshalSignerDER(signer []byte) (*Signer, error) {
  1460  	// TODO: only ecdsa is supported
  1461  	keyName := "Unnamed ECDSA signer"
  1462  	keyEpoch := int32(1)
  1463  	keyType := "ecdsap256"
  1464  	keyPurpose := "singing"
  1465  	keyStatus := "active"
  1466  	h := &CryptoHeader{
  1467  		KeyName:    &keyName,
  1468  		KeyEpoch:   &keyEpoch,
  1469  		KeyType:    &keyType,
  1470  		KeyPurpose: &keyPurpose,
  1471  		KeyStatus:  &keyStatus,
  1472  	}
  1473  	k := &Signer{
  1474  		Header: h,
  1475  	}
  1476  	privateKey, err := x509.ParseECPrivateKey(signer)
  1477  	if err != nil {
  1478  		return nil, err
  1479  	}
  1480  	k.PrivKey = privateKey
  1481  	return k, nil
  1482  }
  1483  
  1484  func GenerateAnonymousSigner() *Signer {
  1485  	keyName := "Anonymous_signer"
  1486  	keyType := SignerTypeFromSuiteName(TaoCryptoSuite)
  1487  	if keyType == nil {
  1488  		return nil
  1489  	}
  1490  	keyPurpose := "signing"
  1491  	keyStatus := "active"
  1492  	keyEpoch := int32(1)
  1493  	s, err := InitializeSigner(nil, *keyType, &keyName, &keyEpoch, &keyPurpose, &keyStatus)
  1494  	if err != nil {
  1495  		return nil
  1496  	}
  1497  	return s
  1498  }
  1499  
  1500  func GenerateAnonymousCrypter() *Crypter {
  1501  	keyName := "Anonymous_crypter"
  1502  	keyType := CrypterTypeFromSuiteName(TaoCryptoSuite)
  1503  	keyPurpose := "crypting"
  1504  	keyStatus := "active"
  1505  	keyEpoch := int32(1)
  1506  	c, err := InitializeCrypter(nil, *keyType, &keyName, &keyEpoch, &keyPurpose, &keyStatus)
  1507  	if err != nil {
  1508  		return nil
  1509  	}
  1510  	return c
  1511  }
  1512  
  1513  func GenerateAnonymousDeriver() *Deriver {
  1514  	keyName := "Anonymous_deriver"
  1515  	keyType := DeriverTypeFromSuiteName(TaoCryptoSuite)
  1516  	keyPurpose := "deriving"
  1517  	keyStatus := "active"
  1518  	keyEpoch := int32(1)
  1519  	d, err := InitializeDeriver(nil, *keyType, &keyName, &keyEpoch, &keyPurpose, &keyStatus)
  1520  	if err != nil {
  1521  		return nil
  1522  	}
  1523  	return d
  1524  }
  1525  
  1526  func Protect(keys []byte, in []byte) ([]byte, error) {
  1527  	keyType := CrypterTypeFromSuiteName(TaoCryptoSuite)
  1528  	if keyType == nil {
  1529  		return nil, errors.New("Protect: Can't get key type from cipher suite")
  1530  	}
  1531  	encKeySize := SymmetricKeySizeFromAlgorithmName(*keyType)
  1532  	if encKeySize == nil {
  1533  		return nil, errors.New("Protect: Can't get symmetric key size from key type")
  1534  	}
  1535  	totalKeySize := CombinedKeySizeFromAlgorithmName(*keyType)
  1536  	if totalKeySize == nil {
  1537  		return nil, errors.New("Protect: Can't get total key size from key type")
  1538  	}
  1539  	if *totalKeySize > len(keys) {
  1540  		return nil, errors.New("Protect: Bad key size")
  1541  	}
  1542  	blkSize := SymmetricBlockSizeFromAlgorithmName(*keyType)
  1543  	if blkSize == nil {
  1544  		return nil, errors.New("Protect: Can't get block size from key type")
  1545  	}
  1546  	if in == nil {
  1547  		return nil, nil
  1548  	}
  1549  	if len(keys) < *totalKeySize {
  1550  		return nil, errors.New("Protect: Supplied key size too small")
  1551  	}
  1552  	iv := make([]byte, *blkSize, *blkSize)
  1553  	_, err := rand.Read(iv[0:*blkSize])
  1554  	if err != nil {
  1555  		return nil, errors.New("Protect: Can't generate iv")
  1556  	}
  1557  	encKey := keys[0:*encKeySize]
  1558  	macKey := keys[*encKeySize:*totalKeySize]
  1559  	crypter, err := aes.NewCipher(encKey)
  1560  	if err != nil {
  1561  		return nil, errors.New("Protect: Can't make crypter")
  1562  	}
  1563  	ctr := cipher.NewCTR(crypter, iv)
  1564  	cipheredOut := make([]byte, len(in))
  1565  	ctr.XORKeyStream(cipheredOut, in)
  1566  	ivAndCiphered := append(iv, cipheredOut...)
  1567  
  1568  	var calculatedHmac []byte
  1569  	switch *keyType {
  1570  	default:
  1571  		return nil, errors.New("unknown symmetric cipher suite")
  1572  	case "aes128-ctr-hmacsha256":
  1573  		hm := hmac.New(sha256.New, macKey)
  1574  		hm.Write(ivAndCiphered)
  1575  		calculatedHmac = hm.Sum(nil)
  1576  	case "aes256-ctr-hmacsha384":
  1577  		hm := hmac.New(sha512.New384, macKey)
  1578  		hm.Write(ivAndCiphered)
  1579  		calculatedHmac = hm.Sum(nil)
  1580  	case "aes256-ctr-hmacsha512":
  1581  		hm := hmac.New(sha512.New, macKey)
  1582  		hm.Write(ivAndCiphered)
  1583  		calculatedHmac = hm.Sum(nil)
  1584  	}
  1585  	return append(calculatedHmac, ivAndCiphered...), nil
  1586  }
  1587  
  1588  func Unprotect(keys []byte, in []byte) ([]byte, error) {
  1589  	keyType := CrypterTypeFromSuiteName(TaoCryptoSuite)
  1590  	if keyType == nil {
  1591  		return nil, errors.New("Unprotect: Can't get key type from cipher suite")
  1592  	}
  1593  	encKeySize := SymmetricKeySizeFromAlgorithmName(*keyType)
  1594  	if encKeySize == nil {
  1595  		return nil, errors.New("Unprotect: Can't get symmetric key size from key type")
  1596  	}
  1597  	hmacKeySize := HmacKeySizeFromAlgorithmName(*keyType)
  1598  	if hmacKeySize == nil {
  1599  		return nil, errors.New("Unprotect: Can't get hmac key size from key type")
  1600  	}
  1601  	hmacSize := HmacKeySizeFromAlgorithmName(*keyType)
  1602  	if hmacSize == nil {
  1603  		return nil, errors.New("Unprotect: Can't get hmac size from key type")
  1604  	}
  1605  	totalKeySize := CombinedKeySizeFromAlgorithmName(*keyType)
  1606  	if totalKeySize == nil {
  1607  		return nil, errors.New("Unprotect: Can't get total key size from key type")
  1608  	}
  1609  	if *totalKeySize > len(keys) {
  1610  		return nil, errors.New("Unprotect: Bad key size")
  1611  	}
  1612  	blkSize := SymmetricBlockSizeFromAlgorithmName(*keyType)
  1613  	if blkSize == nil {
  1614  		return nil, errors.New("Unprotect: Can't get block size from key type")
  1615  	}
  1616  	if in == nil {
  1617  		return nil, nil
  1618  	}
  1619  	out := make([]byte, len(in)-*blkSize-*hmacSize, len(in)-*blkSize-*hmacSize)
  1620  	iv := in[*hmacSize : *hmacSize+*blkSize]
  1621  	encKey := keys[0:*encKeySize]
  1622  	macKey := keys[*encKeySize:*totalKeySize]
  1623  	crypter, err := aes.NewCipher(encKey)
  1624  	if err != nil {
  1625  		return nil, errors.New("Unprotect: Can't make crypter")
  1626  	}
  1627  	ctr := cipher.NewCTR(crypter, iv)
  1628  	ctr.XORKeyStream(out, in[*hmacSize+*blkSize:])
  1629  
  1630  	var calculatedHmac []byte
  1631  	switch *keyType {
  1632  	default:
  1633  		return nil, errors.New("unknown symmetric cipher suite")
  1634  	case "aes128-ctr-hmacsha256":
  1635  		hm := hmac.New(sha256.New, macKey)
  1636  		hm.Write(in[*hmacSize:])
  1637  		calculatedHmac = hm.Sum(nil)
  1638  	case "aes256-ctr-hmacsha384":
  1639  		hm := hmac.New(sha512.New384, macKey)
  1640  		hm.Write(in[*hmacSize:])
  1641  		calculatedHmac = hm.Sum(nil)
  1642  	case "aes256-ctr-hmacsha512":
  1643  		hm := hmac.New(sha512.New, macKey)
  1644  		hm.Write(in[*hmacSize:])
  1645  		calculatedHmac = hm.Sum(nil)
  1646  	}
  1647  	if bytes.Compare(calculatedHmac, in[0:*hmacSize]) != 0 {
  1648  		return nil, errors.New("Unprotect: Bad mac")
  1649  	}
  1650  	return out, nil
  1651  }