github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/crypto/keys/armor/armor_unsafe.go (about)

     1  package armor
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/gnolang/gno/tm2/pkg/crypto"
     7  	"github.com/gnolang/gno/tm2/pkg/crypto/armor"
     8  	"github.com/gnolang/gno/tm2/pkg/errors"
     9  )
    10  
    11  var emptyArmorHeader = map[string]string{}
    12  
    13  // ArmorPrivateKey generates unencrypted armor for the
    14  // given private key
    15  func ArmorPrivateKey(privKey crypto.PrivKey) string {
    16  	return armor.EncodeArmor(blockTypePrivKey, emptyArmorHeader, privKey.Bytes())
    17  }
    18  
    19  // UnarmorPrivateKey extracts the private key from the raw
    20  // unencrypted armor
    21  func UnarmorPrivateKey(armorStr string) (crypto.PrivKey, error) {
    22  	// Decode the raw armor
    23  	blockType, header, privKeyBytes, err := armor.DecodeArmor(armorStr)
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  
    28  	// Make sure it's a private key block
    29  	if blockType != blockTypePrivKey {
    30  		return nil, fmt.Errorf("unrecognized armor type: %v", blockType)
    31  	}
    32  
    33  	// Make sure the header is empty
    34  	if len(header) > 0 {
    35  		return nil, errors.New("non-empty private key header")
    36  	}
    37  
    38  	return crypto.PrivKeyFromBytes(privKeyBytes)
    39  }