github.com/adnan-c/fabric_e2e_couchdb@v0.6.1-preview.0.20170228180935-21ce6b23cf91/core/crypto/primitives/init.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 primitives
    18  
    19  import (
    20  	"crypto/elliptic"
    21  	"crypto/sha256"
    22  	"crypto/sha512"
    23  	"fmt"
    24  	"sync"
    25  
    26  	"golang.org/x/crypto/sha3"
    27  )
    28  
    29  var (
    30  	initOnce sync.Once
    31  )
    32  
    33  // Init SHA2
    34  func initSHA2(level int) (err error) {
    35  	switch level {
    36  	case 256:
    37  		defaultCurve = elliptic.P256()
    38  		defaultHash = sha256.New
    39  	case 384:
    40  		defaultCurve = elliptic.P384()
    41  		defaultHash = sha512.New384
    42  	default:
    43  		err = fmt.Errorf("Security level not supported [%d]", level)
    44  	}
    45  	return
    46  }
    47  
    48  // Init SHA3
    49  func initSHA3(level int) (err error) {
    50  	switch level {
    51  	case 256:
    52  		defaultCurve = elliptic.P256()
    53  		defaultHash = sha3.New256
    54  	case 384:
    55  		defaultCurve = elliptic.P384()
    56  		defaultHash = sha3.New384
    57  	default:
    58  		err = fmt.Errorf("Security level not supported [%d]", level)
    59  	}
    60  	return
    61  }
    62  
    63  // SetSecurityLevel sets the security configuration with the hash length and the algorithm
    64  func SetSecurityLevel(algorithm string, level int) (err error) {
    65  	switch algorithm {
    66  	case "SHA2":
    67  		err = initSHA2(level)
    68  	case "SHA3":
    69  		err = initSHA3(level)
    70  	default:
    71  		err = fmt.Errorf("Algorithm not supported [%s]", algorithm)
    72  	}
    73  	if err == nil {
    74  		// TODO: what's this
    75  		defaultHashAlgorithm = algorithm
    76  		//hashLength = level
    77  	}
    78  	return
    79  }
    80  
    81  // InitSecurityLevel initialize the crypto layer at the given security level
    82  func InitSecurityLevel(algorithm string, level int) (err error) {
    83  	initOnce.Do(func() {
    84  		err = SetSecurityLevel(algorithm, level)
    85  	})
    86  	return
    87  }