Skip to content

Go SDK

pkg.go.dev →

pkg/cipher is the public Go SDK. It reads and writes the same .mdstn files as the CLI, so a file made by one opens in the other.

go get github.com/madstone-tech/cipher-core@v0.5.1
go mod tidy
The SDK is v0: breaking changes are allowed until 1.0 and are listed in the changelog. Only the symbols listed under Stable surface are covered.

Example

Encrypt and decrypt a stream with a file password, with no key database on disk:

package main

import (
    "bytes"
    "context"
    "errors"
    "fmt"
    "log"

    "github.com/madstone-tech/cipher-core/pkg/cipher"
)

func main() {
    ctx := context.Background()

    client, err := cipher.New(cipher.Config{DBPath: cipher.InMemory})
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    var sealed bytes.Buffer
    err = client.EncryptStream(ctx, bytes.NewReader([]byte("quarterly numbers")), &sealed,
        cipher.EncryptStreamInput{Passphrase: "correct horse battery staple", OriginalFilename: "q3.txt"})
    if err != nil {
        log.Fatal(err)
    }

    var plain bytes.Buffer
    res, err := client.DecryptStream(ctx, &sealed, &plain,
        cipher.DecryptStreamInput{Passphrase: "correct horse battery staple"})
    if err != nil {
        plain.Reset() // discard any partial plaintext
        if errors.Is(err, cipher.ErrWrongPassword) {
            log.Fatal("wrong password")
        }
        log.Fatal(err)
    }
    fmt.Println(res.OriginalFilename, plain.String())
}

Creating a client

ConstructorUse
cipher.NewLocal(dbPath)The embedded SQLite key store. "" uses ~/.mdstn/cipher.db
cipher.New(cipher.Config{...})Full control: database path, directory URLs, token, logger, progress, session TTL
Config{DBPath: cipher.InMemory}A key database with no file, for encrypting to public keys only

Config also takes CKDDirectoryURL and PublishServerURL (both default to https://keys.mdstn.dev), PublishToken (falls back to KD_TOKEN), PublishFingerprint for key rotation, Logger, Progress and SessionTTL. The client has no global state, and every method takes a context.Context.

Encrypting and decrypting

  • Files: Encrypt(ctx, EncryptInput{...}) and Decrypt(ctx, DecryptInput{...}). The default output paths follow the CLI’s rules: <file>.mdstn when encrypting, and the path without .mdstn when decrypting. Neither replaces an existing file unless you set Overwrite. An explicit OutputPath replaces an existing file, but never the input.
  • Streams: EncryptStream and DecryptStream take an io.Reader and an io.Writer and create no files.
  • Who can open it: set Passphrase for a file password, Recipients (raw 32-byte X25519 public keys) or RecipientEmail (looked up through CKD), or KeyPassphrase to encrypt to your own default key.
DecryptStream checks each chunk before writing it, but if it returns an error, dst can already hold the plaintext of earlier chunks. Always discard dst on error.

Keys and the directory

CreateKey, ListKeys, GetKey, DeleteKey, AliasKey and ExportKey manage local keys. RecoverFromMnemonic rebuilds a key from its 24 words, and DeriveFromMnemonic derives one without storing it. Unlock, Lock and LockAll manage an in-memory session that caches an unwrapped key for SessionTTL. LookupKey, PublishKey, UnpublishKey and KeyStatus work with the key directory.

Errors

Match errors with errors.Is:

ErrorMeaningCLI exit code
ErrHeaderAuthFailedThe file was tampered with or damaged2
ErrNotARecipientNone of your keys can open the file3
ErrWrongPasswordWrong file password, or a damaged header4
ErrInvalidRecipientKeyA recipient key isn’t a usable X25519 public key
ErrKDConflictThe directory rejected a publish on binding grounds5
ErrKDIntegrityA directory answer failed its signature or key-type check6

Stable surface

Client, Config, New, NewLocal, InMemory; Encrypt, Decrypt, EncryptStream, DecryptStream and their input types; CreateKey, ListKeys, GetKey, DeleteKey, AliasKey, ExportKey; LookupKey, PublishKey; RecoverFromMnemonic, DeriveFromMnemonic; the result types EncryptFileResult, DecryptFileResult, DecryptStreamResult, KeyResult and KeyInfo; and the errors ErrHeaderAuthFailed, ErrNotARecipient, ErrWrongPassword and ErrInvalidRecipientKey.

Port interfaces for building your own stores or services live in pkg/cipherports.