crypto

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 9, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

README

Turnkey Go SDK Crypto Module

GoDocs

The crypto module provides utilities for API key generation, signing, encryption, and attestation. It is used transitively by the root github.com/tkhq/go-sdk/v2 module, so most SDK users do not need to install it separately. It can also be imported directly if you only need the crypto functionality.

Installation

go get github.com/tkhq/go-sdk/crypto

import "github.com/tkhq/go-sdk/crypto"

Key Types and Functions

NewAPIKey

Generates a new Turnkey API key. It defaults to SchemeP256; pass WithScheme(SchemeSECP256K1) or WithScheme(SchemeED25519) to generate a different key type. Returns an *APIKey; use GetPublicKey() and GetPrivateKey() to access the Turnkey-encoded key material.

APIKey

The APIKey type represents a Turnkey API key, including its public key, private key, and signing scheme. It has methods for signing data and exposing key metadata used by local storage.

FromTurnkeyPrivateKey

Creates an APIKey object from a raw private key and signing scheme. This is useful for loading existing API keys from storage, and is the preferred method for doing so.

NewLocal

Creates a filesystem-backed local key store used by the examples to save and load API keys during local development.

Enclave Functions

Standalone functions for encrypting to and decrypting from Turnkey enclave bundles, used in wallet import/export, email auth, and OTP flows.

Usage Examples

See the examples directory in the root SDK for runnable code:

Contributing + License

Contributions are welcome! Please open an issue or submit a pull request with any improvements or bug fixes.

This project is licensed under the Apache License 2.0. See the LICENSE file for details.

Documentation

Overview

Package crypto manages Turnkey cryptographic primitives and key material.

Package crypto manages Turnkey encryption keys and cryptographic primitives.

Index

Constants

View Source
const (
	CurveP256      = Curve("p256")
	CurveSecp256k1 = Curve("secp256k1")
	CurveEd25519   = Curve("ed25519")

	SchemeUnsupported = SignatureScheme("")
	SchemeP256        = SignatureScheme("SIGNATURE_SCHEME_TK_API_P256")
	SchemeSECP256K1   = SignatureScheme("SIGNATURE_SCHEME_TK_API_SECP256K1")
	SchemeED25519     = SignatureScheme("SIGNATURE_SCHEME_TK_API_ED25519")
)
View Source
const (
	// ProductionNotarizerPublicKey used to verify session JWT signatures with the custom double SHA-256 scheme
	ProductionNotarizerPublicKey = "" /* 130-byte string literal not displayed */

	// ProductionLegacyVerificationTokenPublicKey used to verify OTP verification tokens with standard ES256 JWT
	ProductionLegacyVerificationTokenPublicKey = "037e1d0aecd22e33bf831bcb905d31971013b83d2b3ebb718fba4e58fa5a93019d"

	// ProductionTLSFetcherSigningPublicKey is the production TLS Fetcher enclave quorum signing key.
	// It is used to verify the encryptionTargetBundle returned by INIT_OTP before HPKE-encrypting
	// the OTP attempt to the enclave
	ProductionTLSFetcherSigningPublicKey = "" /* 130-byte string literal not displayed */

	// SignerProductionPublicKey is the enclave quorum public key.
	SignerProductionPublicKey = "" /* 130-byte string literal not displayed */
)

Production public keys used for signature verification

View Source
const (
	// Consult the rust implementations README for how these should be configured.
	// See [here](../../../rust/enclave_encrypt/README.md#hpke-configuration)
	// KemID is the KEM used by Turnkey enclave HPKE messages.
	KemID hpke.KEM = hpke.KEM_P256_HKDF_SHA256
	// KdfID is the KDF used by Turnkey enclave HPKE messages.
	KdfID hpke.KDF = hpke.KDF_HKDF_SHA256
	// AeadID is the AEAD used by Turnkey enclave HPKE messages.
	AeadID hpke.AEAD = hpke.AEAD_AES256GCM
	// TurnkeyHPKEInfo is the HPKE info value used by Turnkey enclave messages.
	TurnkeyHPKEInfo = "turnkey_hpke"
)
View Source
const (
	KeyFormatHexadecimal = "HEXADECIMAL"
	KeyFormatSolana      = "SOLANA"
)

KeyFormat values supported by EncryptPrivateKeyToBundle.

View Source
const (
	// DefaultKeyName is the name of the default API key.
	DefaultKeyName = "default"
)
View Source
const ECDSAPublicKeyBytes = 33

ECDSAPublicKeyBytes is the expected number of bytes for a public ECDSA key.

View Source
const (
	// SignatureSchemeEphemeralKeyP256 is the expected app proof signature scheme.
	SignatureSchemeEphemeralKeyP256 = "SIGNATURE_SCHEME_EPHEMERAL_KEY_P256"
)

Variables

This section is empty.

Functions

func AdditionalAssociatedData

func AdditionalAssociatedData(receiverPublic kem.PublicKey, senderPublic []byte) ([]byte, error)

AdditionalAssociatedData derives the AAD used by Turnkey enclave HPKE messages.

func DecodeKEMPrivateKey

func DecodeKEMPrivateKey(encodedPrivateKey string) (*kem.PrivateKey, error)

DecodeKEMPrivateKey decodes a Turnkey hex-encoded KEM private key.

func DecodeKEMPublicKey

func DecodeKEMPublicKey(encodedPublicKey string) (*kem.PublicKey, error)

DecodeKEMPublicKey decodes a Turnkey hex-encoded KEM public key.

func DecodePublicECDSAKey

func DecodePublicECDSAKey(encodedPublicKey string, scheme SignatureScheme) (*ecdsa.PublicKey, error)

DecodePublicECDSAKey takes a public key and creates an ECDSA public key.

func DecryptCredentialBundle

func DecryptCredentialBundle(credentialBundle string, kemPrivateKey kem.PrivateKey) ([]byte, error)

DecryptCredentialBundle decrypts a base58check-encoded credential bundle from the server. Used in email authentication and email recovery flows.

func DecryptExportBundle

func DecryptExportBundle(bundleBytes []byte, organizationID string, kemPrivateKey kem.PrivateKey, dangerouslyOverrideSignerKey ...*ecdsa.PublicKey) ([]byte, error)

DecryptExportBundle decrypts an export bundle (wallet or private key export flow). Verifies the enclave signature using the production signer key and validates organizationID. Pass dangerouslyOverrideSignerKey to use a custom enclave quorum public key (non-production only).

func DefaultAPIKeysDir

func DefaultAPIKeysDir() string

DefaultAPIKeysDir returns the default directory for API key storage for the user's system.

func DefaultEncryptionKeysDir

func DefaultEncryptionKeysDir() string

DefaultEncryptionKeysDir returns the default directory for encryption key storage for the user's system.

func EncodeKEMPrivateKey

func EncodeKEMPrivateKey(privateKey kem.PrivateKey) (string, error)

EncodeKEMPrivateKey encodes a KEM private key into Turnkey's hex format.

func EncodeKEMPublicKey

func EncodeKEMPublicKey(publicKey kem.PublicKey) (string, error)

EncodeKEMPublicKey encodes a KEM public key into Turnkey's hex format.

func EncodePrivateECDSAKey

func EncodePrivateECDSAKey(privateKey *ecdsa.PrivateKey) string

EncodePrivateECDSAKey encodes an ECDSA private key

func EncodePublicECDSAKey

func EncodePublicECDSAKey(publicKey *ecdsa.PublicKey) string

EncodePublicECDSAKey encodes an ECDSA public key.

func EncryptOtpCodeToBundle

func EncryptOtpCodeToBundle(otpCode, otpEncryptionTargetBundle, publicKey string, dangerouslyOverrideSignerPublicKeyHex ...string) (string, error)

EncryptOtpCodeToBundle encrypts an OTP code and a client public key to the target bundle returned by InitOtp. Verifies the enclave signature using ProductionTLSFetcherSigningPublicKey. Pass dangerouslyOverrideSignerPublicKeyHex to use a custom signer key (non-production only).

func EncryptPrivateKeyToBundle

func EncryptPrivateKeyToBundle(privateKey, keyFormat, importBundle, organizationID, userID string, dangerouslyOverrideSignerKey ...*ecdsa.PublicKey) (string, error)

EncryptPrivateKeyToBundle encrypts a private key to the given import bundle. keyFormat is "HEXADECIMAL" or "SOLANA". Verifies the enclave signature and validates organizationID and userID. Pass dangerouslyOverrideSignerKey to use a custom enclave quorum public key (non-production only).

func EncryptWalletToBundle

func EncryptWalletToBundle(mnemonic, importBundle, organizationID, userID string, dangerouslyOverrideSignerKey ...*ecdsa.PublicKey) (string, error)

EncryptWalletToBundle encrypts a wallet mnemonic to the given import bundle. Verifies the enclave signature using the production signer key and validates organizationID and userID. Pass dangerouslyOverrideSignerKey to use a custom enclave quorum public key (non-production only).

func GenerateEncryptionKeyPair

func GenerateEncryptionKeyPair() (uncompressedPublicKeyHex string, privateKey kem.PrivateKey, err error)

GenerateEncryptionKeyPair generates a new HPKE KEM keypair, returning the uncompressed public key plus the raw private key needed to decrypt enclave responses.

func GetBootProofTime

func GetBootProofTime(bootProof *BootProof) (time.Time, error)

GetBootProofTime extracts the timestamp from a boot proof.

func HPKEDecrypt

func HPKEDecrypt(encappedPublic []byte, receiverPrivate kem.PrivateKey, ciphertext []byte) ([]byte, error)

HPKEDecrypt decrypts ciphertext with receiverPrivate and Turnkey's enclave HPKE configuration.

func HPKEEncrypt

func HPKEEncrypt(receiverPublic *kem.PublicKey, plaintext []byte) (ciphertext []byte, encappedPublic []byte, err error)

HPKEEncrypt encrypts plaintext to receiverPublic with Turnkey's enclave HPKE configuration.

func P256Sign

func P256Sign(privateKey *ecdsa.PrivateKey, msg []byte) ([]byte, error)

P256Sign signs msg with ECDSA P-256 using SHA-256 and ASN.1 encoding.

func P256Verify

func P256Verify(publicKey *ecdsa.PublicKey, msg []byte, signature []byte) bool

P256Verify verifies an ASN.1 ECDSA P-256 signature over msg using SHA-256.

func ToECDSAPublic

func ToECDSAPublic(publicBytes []byte) (*ecdsa.PublicKey, error)

ToECDSAPublic parses an uncompressed P-256 ECDSA public key.

func VerifyAppProofSignature

func VerifyAppProofSignature(appProof *AppProof) error

VerifyAppProofSignature verifies the app proof's P-256 ECDSA signature.

func VerifyLegacyVerificationToken

func VerifyLegacyVerificationToken(tokenString, dangerouslyOverridePublicKey string, parserOpts ...jwt.ParserOption) error

VerifyLegacyVerificationToken verifies the signature of an OTP verification token JWT using the production OTP verification public key.

func VerifyProofs

func VerifyProofs(appProof *AppProof, bootProof *BootProof) error

VerifyProofs verifies an app proof and boot proof pair.

This establishes a cryptographic chain of trust:

  1. Verifies the app proof signature
  2. Verifies the boot proof a. Verifies the AWS Nitro attestation document signature and validity b. Verifies the QOS manifest hash matches the attestation document user_data
  3. Verifies the app proof / boot proof connection - that the app proof's ephemeral public key matches attestation document's public_key field

To learn more about verifying app proofs and boot proofs, see: https://whitepaper.turnkey.com/foundations/

func VerifySessionJwtSignature

func VerifySessionJwtSignature(jwtString string, dangerouslyOverrideNotarizerPublicKey ...string) error

VerifySessionJwtSignature verifies the signature of a Turnkey session JWT using the custom double SHA-256 scheme with the production notarizer public key.

Session JWTs use a custom signing scheme:

  • Double SHA-256 hash: hash = SHA256(SHA256(header.payload))
  • ECDSA signature with P-256 curve
  • IEEE P1363 signature format (raw R || S concatenation, 64 bytes)
  • Uncompressed public key (65 bytes, starts with 0x04)

This is different from standard ES256 JWTs which use single SHA-256 hashing.

Types

type APIKey

type APIKey struct {
	APIKeyMetadata

	TkPrivateKey string `json:"-"` // do not store the private key in the metadata file
	TkPublicKey  string `json:"public_key"`
	// contains filtered or unexported fields
}

APIKey defines a structure in which to hold both serialized and signer-friendly versions of an API key.

func FromECDSAPrivateKey

func FromECDSAPrivateKey(privateKey *ecdsa.PrivateKey, scheme SignatureScheme) (*APIKey, error)

FromECDSAPrivateKey takes an ECDSA keypair and forms an API key from it. Assumes that privateKey.PublicKey has already been derived.

func FromED25519PrivateKey

func FromED25519PrivateKey(privateKey ed25519.PrivateKey) (*APIKey, error)

FromED25519PrivateKey takes an ED25519 keypair and forms an API key from it.

func FromTurnkeyPrivateKey

func FromTurnkeyPrivateKey(encodedPrivateKey string, scheme SignatureScheme) (*APIKey, error)

FromTurnkeyPrivateKey takes a private key, derives a public key from it, and then returns the corresponding API key.

func NewAPIKey

func NewAPIKey(opts ...APIKeyOptionFunc) (*APIKey, error)

NewAPIKey generates a new API key.

func (APIKey) GetCurve

func (k APIKey) GetCurve() string

GetCurve returns the curve used; defaults to p256 for backwards compatibility with keys created before there were multiple supported types.

func (APIKey) GetMetadata

func (k APIKey) GetMetadata() APIKeyMetadata

GetMetadata gets the key's metadata.

func (APIKey) GetPrivateKey

func (k APIKey) GetPrivateKey() string

GetPrivateKey gets the key's private key.

func (APIKey) GetPublicKey

func (k APIKey) GetPublicKey() string

GetPublicKey gets the key's public key.

func (APIKey) GetScheme

func (k APIKey) GetScheme() SignatureScheme

GetScheme returns the signature scheme of the key.

func (*APIKey) Sign

func (k *APIKey) Sign(message []byte) (string, error)

Sign signs the given message and returns the hex-encoded signature.

type APIKeyMetadata

type APIKeyMetadata struct {
	Name          string   `json:"name"`
	Organizations []string `json:"organizations"`
	PublicKey     string   `json:"public_key"`
	Scheme        string   `json:"scheme"`
}

APIKeyMetadata stores non-secret metadata about the API key.

type APIKeyOptionFunc

type APIKeyOptionFunc func(k *APIKey)

func WithScheme

func WithScheme(scheme SignatureScheme) APIKeyOptionFunc

type AppProof

type AppProof struct {
	ProofPayload string
	PublicKey    string
	Scheme       string
	Signature    string
}

AppProof contains the app proof fields required for cryptographic verification.

type BootProof

type BootProof struct {
	AWSAttestationDocB64   string
	CreatedAt              Timestamp
	DeploymentLabel        string
	EnclaveApp             string
	EphemeralPublicKeyHex  string
	Owner                  string
	QosManifestB64         string
	QosManifestEnvelopeB64 string
}

BootProof contains the boot proof fields required for cryptographic verification.

type Bytes

type Bytes = tkencoding.HexBytes

type ClientSendMsg

type ClientSendMsg struct {
	EncappedPublic *Bytes `json:"encappedPublic,omitempty"`
	Ciphertext     *Bytes `json:"ciphertext,omitempty"`
}

ClientSendMsg is the client's encrypted message to the enclave.

type Curve

type Curve string

Curve is a wrapped abbreviated version of a signature curve.

func (Curve) ToScheme

func (c Curve) ToScheme() SignatureScheme

ToScheme returns a Curve's associated SignatureScheme.

type EncryptionKey

type EncryptionKey struct {
	EncryptionKeyMetadata

	TkPrivateKey string `json:"-"` // do not store the private key in the metadata file
	TkPublicKey  string `json:"public_key"`
	// contains filtered or unexported fields
}

EncryptionKey defines a structure in which to hold both serialized and ECDH-friendly versions of a Turnkey encryption keypair.

func FromKemPrivateKey

func FromKemPrivateKey(privateKey kem.PrivateKey) (*EncryptionKey, error)

FromKemPrivateKey takes a HPKE KEM keypair and forms a Turnkey encryption key from it. Assumes that privateKey.Public() has already been derived.

func FromTurnkeyEncryptionPrivateKey

func FromTurnkeyEncryptionPrivateKey(encodedPrivateKey string) (*EncryptionKey, error)

FromTurnkeyEncryptionPrivateKey takes a Turnkey-encoded private key, derives a public key from it, and returns the corresponding Turnkey encryption key.

func (EncryptionKey) GetCurve

func (k EncryptionKey) GetCurve() string

GetCurve returns the curve used.

func (EncryptionKey) GetMetadata

func (k EncryptionKey) GetMetadata() EncryptionKeyMetadata

GetMetadata gets the key's metadata.

func (EncryptionKey) GetPrivateKey

func (k EncryptionKey) GetPrivateKey() string

GetPrivateKey gets the key's private key.

func (EncryptionKey) GetPublicKey

func (k EncryptionKey) GetPublicKey() string

GetPublicKey gets the key's public key.

type EncryptionKeyMetadata

type EncryptionKeyMetadata struct {
	Name         string `json:"name"`
	Organization string `json:"organization"`
	User         string `json:"user"`
	PublicKey    string `json:"public_key"`
}

EncryptionKeyMetadata stores non-secret metadata about the encryption key.

type Key

type Key[M Metadata] interface {
	GetPublicKey() string
	GetPrivateKey() string
	GetCurve() string
	GetMetadata() M
}

Key defines an interface for API keys and Encryption keys.

type KeyFactory

type KeyFactory[T Key[M], M Metadata] struct{}

KeyFactory generic struct to select the correct FromTurnkeyPrivateKey function.

func (KeyFactory[T, M]) FromTurnkeyPrivateKey

func (kf KeyFactory[T, M]) FromTurnkeyPrivateKey(data string) (T, error)

FromTurnkeyPrivateKey converts a Turnkey-encoded private key string to a key.

type LocalStore

type LocalStore[T Key[M], M Metadata] struct {
	// DefaultKeyName is the name of the key to use when none is specified.
	DefaultKeyName string

	// KeyDirectory is the directory in which all the keys and metadata are stored.
	KeyDirectory string
}

LocalStore defines an API key Store using the local filesystem.

func NewLocal

func NewLocal[T Key[M], M Metadata]() *LocalStore[T, M]

NewLocal provides a new local API key store.

func (*LocalStore[T, M]) Load

func (s *LocalStore[T, M]) Load(name string) (T, error)

Load pulls a key from the local filesystem.

func (*LocalStore[T, M]) PrivateKeyFile

func (s *LocalStore[T, M]) PrivateKeyFile(name string) string

PrivateKeyFile returns the filename for the private key of the given name.

func (*LocalStore[T, M]) PublicKeyFile

func (s *LocalStore[T, M]) PublicKeyFile(name string) string

PublicKeyFile returns the filename for the public key of the given name.

func (*LocalStore[T, M]) SetAPIKeysDirectory

func (s *LocalStore[T, M]) SetAPIKeysDirectory(keysPath string) (err error)

SetAPIKeysDirectory sets the store's key directory, ensuring its existence and writability.

func (*LocalStore[T, M]) SetEncryptionKeysDirectory

func (s *LocalStore[T, M]) SetEncryptionKeysDirectory(keysPath string) (err error)

SetEncryptionKeysDirectory sets the store's key directory, ensuring its existence and writability.

func (*LocalStore[T, M]) Store

func (s *LocalStore[T, M]) Store(name string, keypair T) error

Store saves the key to the local filesystem.

type Metadata

type Metadata interface{}

Metadata defines an interface for the metadata on keys.

type ServerSendData

type ServerSendData struct {
	EncappedPublic Bytes  `json:"encappedPublic"`
	Ciphertext     Bytes  `json:"ciphertext"`
	OrganizationID string `json:"organizationId"`
}

ServerSendData is the signed data payload inside a ServerSendMsgV1.

type ServerSendMsgV1

type ServerSendMsgV1 struct {
	Version             string `json:"version"`
	Data                Bytes  `json:"data"`
	DataSignature       Bytes  `json:"dataSignature"`
	EnclaveQuorumPublic Bytes  `json:"enclaveQuorumPublic"`
}

ServerSendMsgV1 is the server send message format with enclave quorum key and signature.

type ServerTargetData

type ServerTargetData struct {
	TargetPublic   Bytes  `json:"targetPublic"`
	OrganizationID string `json:"organizationId"`
	UserID         string `json:"userId"`
}

ServerTargetData is the signed data payload inside a ServerTargetMsgV1.

type ServerTargetMsgV1

type ServerTargetMsgV1 struct {
	Version             string `json:"version"`
	Data                Bytes  `json:"data"`
	DataSignature       Bytes  `json:"dataSignature"`
	EnclaveQuorumPublic Bytes  `json:"enclaveQuorumPublic"`
}

ServerTargetMsgV1 is the server target message format with enclave quorum key and signature.

type SignatureScheme

type SignatureScheme string

type Store

type Store[T Key[M], M Metadata] interface {
	// Load pulls a key from the store.
	Load(name string) (T, error)

	// Store saves the key to the store.
	Store(name string, key T) error
}

Store provides an interface in which API or Encryption keys may be stored and retrieved.

type Timestamp

type Timestamp struct {
	Seconds string
	Nanos   string
}

Timestamp represents a protobuf-style timestamp returned by Turnkey APIs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL