github.com/adnan-c/fabric_e2e_couchdb@v0.6.1-preview.0.20170228180935-21ce6b23cf91/accesscontrol/crypto/ecdsa/hash.go (about)

     1  /*
     2  Copyright IBM Corp. 2016 All Rights Reserved.
     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 ecdsa
    18  
    19  import (
    20  	"crypto/sha256"
    21  	"crypto/sha512"
    22  	"fmt"
    23  	"hash"
    24  
    25  	"golang.org/x/crypto/sha3"
    26  
    27  	"github.com/hyperledger/fabric/core/crypto/primitives"
    28  )
    29  
    30  func getHashSHA2(bitsize int) (hash.Hash, error) {
    31  	switch bitsize {
    32  	case 224:
    33  		return sha256.New224(), nil
    34  	case 256:
    35  		return sha256.New(), nil
    36  	case 384:
    37  		return sha512.New384(), nil
    38  	case 512:
    39  		return sha512.New(), nil
    40  	case 521:
    41  		return sha512.New(), nil
    42  	default:
    43  		return nil, fmt.Errorf("Invalid bitsize. It was [%d]. Expected [224, 256, 384, 512, 521]", bitsize)
    44  	}
    45  }
    46  
    47  func getHashSHA3(bitsize int) (hash.Hash, error) {
    48  	switch bitsize {
    49  	case 224:
    50  		return sha3.New224(), nil
    51  	case 256:
    52  		return sha3.New256(), nil
    53  	case 384:
    54  		return sha3.New384(), nil
    55  	case 512:
    56  		return sha3.New512(), nil
    57  	case 521:
    58  		return sha3.New512(), nil
    59  	default:
    60  		return nil, fmt.Errorf("Invalid bitsize. It was [%d]. Expected [224, 256, 384, 512, 521]", bitsize)
    61  	}
    62  }
    63  
    64  func computeHash(msg []byte, bitsize int) ([]byte, error) {
    65  	var hash hash.Hash
    66  	var err error
    67  	switch primitives.GetHashAlgorithm() {
    68  	case "SHA2":
    69  		hash, err = getHashSHA2(bitsize)
    70  	case "SHA3":
    71  		hash, err = getHashSHA3(bitsize)
    72  	default:
    73  		return nil, fmt.Errorf("Invalid hash algorithm %s", primitives.GetHashAlgorithm())
    74  	}
    75  
    76  	if err != nil {
    77  		return nil, err
    78  	}
    79  
    80  	hash.Write(msg)
    81  	return hash.Sum(nil), nil
    82  }