github.com/blend/go-sdk@v1.20220411.3/crypto/create_key.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package crypto
     9  
    10  import (
    11  	cryptorand "crypto/rand"
    12  	"encoding/base64"
    13  	"encoding/hex"
    14  
    15  	"github.com/blend/go-sdk/ex"
    16  )
    17  
    18  // MustCreateKey creates a key, if an error is returned, it panics.
    19  func MustCreateKey(keySize int) []byte {
    20  	key, err := CreateKey(keySize)
    21  	if err != nil {
    22  		panic(err)
    23  	}
    24  	return key
    25  }
    26  
    27  // CreateKey creates a key of a given size by reading that much data off the crypto/rand reader.
    28  func CreateKey(keySize int) ([]byte, error) {
    29  	key := make([]byte, keySize)
    30  	_, err := cryptorand.Read(key)
    31  	if err != nil {
    32  		return nil, err
    33  	}
    34  	return key, nil
    35  }
    36  
    37  // MustCreateKeyString generates a new key and returns it as a hex string.
    38  func MustCreateKeyString(keySize int) string {
    39  	return hex.EncodeToString(MustCreateKey(keySize))
    40  }
    41  
    42  // MustCreateKeyBase64String generates a new key and returns it as a base64 std encoding string.
    43  func MustCreateKeyBase64String(keySize int) string {
    44  	return base64.StdEncoding.EncodeToString(MustCreateKey(keySize))
    45  }
    46  
    47  // CreateKeyString generates a new key and returns it as a hex string.
    48  func CreateKeyString(keySize int) (string, error) {
    49  	key, err := CreateKey(keySize)
    50  	if err != nil {
    51  		return "", err
    52  	}
    53  	return hex.EncodeToString(key), nil
    54  }
    55  
    56  // CreateKeyBase64String generates a new key and returns it as a base64 std encoding string.
    57  func CreateKeyBase64String(keySize int) (string, error) {
    58  	key, err := CreateKey(keySize)
    59  	if err != nil {
    60  		return "", err
    61  	}
    62  	return base64.StdEncoding.EncodeToString(key), nil
    63  }
    64  
    65  // ParseKey parses a key from a string.
    66  func ParseKey(key string) ([]byte, error) {
    67  	decoded, err := hex.DecodeString(key)
    68  	if err != nil {
    69  		return nil, ex.New(err)
    70  	}
    71  	if len(decoded) != DefaultKeySize {
    72  		return nil, ex.New("parse key; invalid key length")
    73  	}
    74  	return decoded, nil
    75  }