contract-go

Hyper Protect Contract Go Library - API Documentation

Introduction

The contract-go library provides a comprehensive API for working with IBM Hyper Protect services. This documentation covers all available functions, their parameters, return values, and usage examples.

Table of Contents

Configuration

Prerequisites

Environment Variables

OPENSSL_BIN (Optional)

Configure the path to the OpenSSL binary. This is useful on systems where OpenSSL is not in the system PATH (e.g., Windows).

Linux/macOS:

export OPENSSL_BIN=/usr/bin/openssl

Windows (PowerShell):

$env:OPENSSL_BIN="C:\Program Files\OpenSSL-Win64\bin\openssl.exe"

Windows (Command Prompt):

set OPENSSL_BIN=C:\Program Files\OpenSSL-Win64\bin\openssl.exe

Attestation Functions

HpcrGetAttestationRecords

Decrypts encrypted attestation records generated by Hyper Protect Services.

Package: github.com/ibm-hyper-protect/contract-go/v2/attestation

Signature:

func HpcrGetAttestationRecords(data, privateKey string) (string, error)

Parameters:

Parameter Type Required/Optional Description
data string Required Encrypted attestation data in the format hyper-protect-basic.<password>.<data>
privateKey string Required RSA private key (PEM format) used to decrypt the password

Returns:

Return Type Description
Attestation Records string Decrypted attestation records
Error error Error if decryption fails or parameters are invalid

Example:

package main

import (
    "fmt"
    "log"

    "github.com/ibm-hyper-protect/contract-go/v2/attestation"
)

func main() {
    // Encrypted attestation data received from HPVS
    encryptedData := "hyper-protect-basic.aBcD123..."

    // Your RSA private key
    privateKey := `-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA...
-----END RSA PRIVATE KEY-----`

    // Decrypt attestation records
    records, err := attestation.HpcrGetAttestationRecords(encryptedData, privateKey)
    if err != nil {
        log.Fatalf("Failed to decrypt attestation: %v", err)
    }

    fmt.Println("Attestation Records:", records)
}

Common Errors:


Certificate Functions

HpcrDownloadEncryptionCertificates

Downloads encryption certificates for specified HPVS versions from IBM Cloud.

Package: github.com/ibm-hyper-protect/contract-go/v2/certificate

Signature:

func HpcrDownloadEncryptionCertificates(versionList []string, formatType, certDownloadUrlTemplate string) (string, error)

Parameters:

Parameter Type Required/Optional Description
versionList []string Required List of HPCR versions to download (e.g., ["1.1.14", "1.1.15"])
formatType string Optional Output format: "json" or "yaml" (defaults to "json" if empty)
certDownloadUrlTemplate string Optional Custom URL template (uses IBM Cloud default if empty)

Default URL Template:

https://hpvsvpcubuntu.s3.us.cloud-object-storage.appdomain.cloud/s390x-{{.Patch}}/ibm-hyper-protect-container-runtime-{{.Major}}-{{.Minor}}-s390x-{{.Patch}}-encrypt.crt

Returns:

Return Type Description
Certificates string JSON or YAML formatted map of versions to certificates
Error error Error if download fails or version not found

Example:

package main

import (
    "fmt"
    "log"

    "github.com/ibm-hyper-protect/contract-go/v2/certificate"
)

func main() {
    // Download certificates for multiple versions
    versions := []string{"1.1.14", "1.1.15", "1.1.16"}

    // Get as JSON (default)
    certsJSON, err := certificate.HpcrDownloadEncryptionCertificates(versions, "json", "")
    if err != nil {
        log.Fatalf("Failed to download certificates: %v", err)
    }

    fmt.Printf("Downloaded certificates:\n%s\n", certsJSON)

    // Or get as YAML
    certsYAML, err := certificate.HpcrDownloadEncryptionCertificates(versions, "yaml", "")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("YAML format:\n%s\n", certsYAML)
}

Common Errors:


HpcrGetEncryptionCertificateFromJson

Extracts a specific version’s encryption certificate from the output of HpcrDownloadEncryptionCertificates.

Package: github.com/ibm-hyper-protect/contract-go/v2/certificate

Signature:

func HpcrGetEncryptionCertificateFromJson(encryptionCertificateJson, version string) (string, string, error)

Parameters:

Parameter Type Required/Optional Description
encryptionCertificateJson string Required JSON/YAML output from HpcrDownloadEncryptionCertificates
version string Required Specific version to extract (e.g., "1.1.15")

Returns:

Return Type Description
Version string The requested version number
Certificate string PEM-formatted encryption certificate
Error error Error if version not found or JSON invalid

Example:

package main

import (
    "fmt"
    "log"

    "github.com/ibm-hyper-protect/contract-go/v2/certificate"
)

func main() {
    // First, download certificates
    versions := []string{"1.1.14", "1.1.15"}
    certsJSON, err := certificate.HpcrDownloadEncryptionCertificates(versions, "json", "")
    if err != nil {
        log.Fatal(err)
    }

    // Extract specific version
    version, cert, err := certificate.HpcrGetEncryptionCertificateFromJson(certsJSON, "1.1.15")
    if err != nil {
        log.Fatalf("Failed to get certificate: %v", err)
    }

    fmt.Printf("Version: %s\n", version)
    fmt.Printf("Certificate:\n%s\n", cert)
}

Common Errors:


HpcrValidateEncryptionCertificate

Validates and returns expiry details of an encryption certificate.

Package: github.com/ibm-hyper-protect/contract-go/v2/certificate

Signature:

func HpcrValidateEncryptionCertificate(encryptionCert string) (string, error)

Parameters:

Parameter Type Required/Optional Description
encryptionCert string Required PEM-formatted encryption certificate

Returns:

Return Type Description
Expiry Details string Certificate expiration information
Error error Error if certificate is invalid or expired

Example:

package main

import (
    "fmt"
    "log"

    "github.com/ibm-hyper-protect/contract-go/v2/certificate"
)

func main() {
    cert := `-----BEGIN CERTIFICATE-----
MIIDXTCCAkWgAwIBAgIJAKL...
-----END CERTIFICATE-----`

    expiryInfo, err := certificate.HpcrValidateEncryptionCertificate(cert)
    if err != nil {
        log.Fatalf("Certificate validation failed: %v", err)
    }

    fmt.Printf("Certificate expiry: %s\n", expiryInfo)
}

Use Cases:

Common Errors:


Image Functions

HpcrSelectImage

Selects the latest HPCR image from IBM Cloud images based on version constraints and semantic versioning.

Package: github.com/ibm-hyper-protect/contract-go/v2/image

Signature:

func HpcrSelectImage(imageJsonData, versionSpec string) (string, string, string, string, error)

Parameters:

Parameter Type Required/Optional Description
imageJsonData string Required JSON array of IBM Cloud images
versionSpec string Optional Version constraint (e.g., ">=1.1.0", "~1.1.14") - selects latest if empty

Supported Image Sources:

  1. Terraform - Output from data.ibm_is_images.hyper_protect_images.images
  2. IBM Cloud API:
    curl -X GET "https://<region>.cloud.ibm.com/v1/images?version=2022-09-13&generation=2" \
      -H "Authorization: Bearer <token>" \
      -H "Content-Type: application/json" | jq .images
    
  3. IBM Cloud CLI:
    ibmcloud is images --json
    

Returns:

Return Type Description
Image ID string IBM Cloud image ID
Image Name string Full image name
Checksum string SHA256 checksum of the image
Version string Semantic version (e.g., "1.1.15")
Error error Error if no matching image found

Example:

package main

import (
    "fmt"
    "log"
    "os/exec"

    "github.com/ibm-hyper-protect/contract-go/v2/image"
)

func main() {
    // Get images from IBM Cloud CLI
    cmd := exec.Command("ibmcloud", "is", "images", "--json")
    output, err := cmd.Output()
    if err != nil {
        log.Fatalf("Failed to get images: %v", err)
    }

    // Select latest image version >= 1.1.0
    imageID, imageName, checksum, version, err := image.HpcrSelectImage(
        string(output),
        ">=1.1.0",
    )
    if err != nil {
        log.Fatalf("Failed to select image: %v", err)
    }

    fmt.Printf("Selected HPCR Image:\n")
    fmt.Printf("  ID:       %s\n", imageID)
    fmt.Printf("  Name:     %s\n", imageName)
    fmt.Printf("  Version:  %s\n", version)
    fmt.Printf("  Checksum: %s\n", checksum)

    // Use with specific version constraint
    imageID, _, _, version, err = image.HpcrSelectImage(string(output), "~1.1.14")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Selected version ~1.1.14: %s\n", version)
}

Version Constraint Examples:

Common Errors:

Image Selection Criteria: The function filters images based on:


Contract Functions

HpcrText

Generates Base64-encoded representation of plain text data with integrity checksums.

Package: github.com/ibm-hyper-protect/contract-go/v2/contract

Signature:

func HpcrText(plainText string) (string, string, string, error)

Parameters:

Parameter Type Required/Optional Description
plainText string Required Text data to encode

Returns:

Return Type Description
Base64 Data string Base64-encoded text
Input Checksum string SHA256 hash of original text
Output Checksum string SHA256 hash of Base64-encoded data
Error error Error if text is empty

Example:

package main

import (
    "fmt"
    "log"

    "github.com/ibm-hyper-protect/contract-go/v2/contract"
)

func main() {
    text := "Hello, Hyper Protect World!"

    encoded, inputHash, outputHash, err := contract.HpcrText(text)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Original text: %s\n", text)
    fmt.Printf("Base64 encoded: %s\n", encoded)
    fmt.Printf("Input SHA256: %s\n", inputHash)
    fmt.Printf("Output SHA256: %s\n", outputHash)
}

Use Cases:

Common Errors:


HpcrTextEncrypted

Encrypts plain text using the Hyper Protect encryption format.

Package: github.com/ibm-hyper-protect/contract-go/v2/contract

Signature:

func HpcrTextEncrypted(plainText, hyperProtectOs, encryptionCertificate string) (string, string, string, error)

Parameters:

Parameter Type Required/Optional Description
plainText string Required Text to encrypt
hyperProtectOs string Optional Platform: "hpvs", "hpcr-rhvs", or "hpcc-peerpod" (defaults to "hpvs" if empty)
encryptionCertificate string Optional PEM certificate (uses latest HPVS as default if empty)

Returns:

Return Type Description
Encrypted Data string Format: hyper-protect-basic.<password>.<data>
Input Checksum string SHA256 of original text
Output Checksum string SHA256 of encrypted output
Error error Error if encryption fails

Example:

package main

import (
    "fmt"
    "log"

    "github.com/ibm-hyper-protect/contract-go/v2/contract"
)

func main() {
    text := "sensitive data"

    // Use default certificate
    encrypted, inputHash, outputHash, err := contract.HpcrTextEncrypted(text, "hpvs", "")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Encrypted: %s\n", encrypted)
    fmt.Printf("Input checksum: %s\n", inputHash)
    fmt.Printf("Output checksum: %s\n", outputHash)
}

Common Errors:


HpcrJson

Generates Base64-encoded representation of JSON data with integrity checksums.

Package: github.com/ibm-hyper-protect/contract-go/v2/contract

Signature:

func HpcrJson(plainJson string) (string, string, string, error)

Parameters:

Parameter Type Required/Optional Description
plainJson string Required Valid JSON string

Returns:

Return Type Description
Base64 Data string Base64-encoded JSON
Input Checksum string SHA256 of original JSON
Output Checksum string SHA256 of Base64 data
Error error Error if not valid JSON

Example:

package main

import (
    "fmt"
    "log"

    "github.com/ibm-hyper-protect/contract-go/v2/contract"
)

func main() {
    jsonData := `{"name": "app", "version": "1.0"}`

    encoded, inputHash, outputHash, err := contract.HpcrJson(jsonData)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Base64 JSON: %s\n", encoded)
    fmt.Printf("Input SHA256: %s\n", inputHash)
    fmt.Printf("Output SHA256: %s\n", outputHash)
}

Common Errors:


HpcrJsonEncrypted

Encrypts JSON data using the Hyper Protect encryption format.

Package: github.com/ibm-hyper-protect/contract-go/v2/contract

Signature:

func HpcrJsonEncrypted(plainJson, hyperProtectOs, encryptionCertificate string) (string, string, string, error)

Parameters:

Parameter Type Required/Optional Description
plainJson string Required Valid JSON string to encrypt
hyperProtectOs string Optional Platform: "hpvs", "hpcr-rhvs", or "hpcc-peerpod" (defaults to "hpvs" if empty)
encryptionCertificate string Optional PEM certificate (uses latest HPVS as default if empty)

Returns:

Return Type Description
Encrypted JSON string Format: hyper-protect-basic.<password>.<data>
Input Checksum string SHA256 of original JSON
Output Checksum string SHA256 of encrypted output
Error error Error if not valid JSON or encryption fails

Example:

package main

import (
    "fmt"
    "log"

    "github.com/ibm-hyper-protect/contract-go/v2/contract"
)

func main() {
    config := `{
        "database": {
            "host": "localhost",
            "password": "secret123"
        }
    }`

    encrypted, _, _, err := contract.HpcrJsonEncrypted(config, "hpvs", "")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Encrypted config: %s\n", encrypted)
}

Common Errors:


HpcrTgz

Creates a Base64-encoded TGZ archive from a directory containing docker-compose.yaml or pods.yaml.

Package: github.com/ibm-hyper-protect/contract-go/v2/contract

Signature:

func HpcrTgz(folderPath string) (string, string, string, error)

Parameters:

Parameter Type Required/Optional Description
folderPath string Required Path to folder containing compose/pods files

Returns:

Return Type Description
TGZ Base64 string Base64-encoded tar.gz archive
Input Checksum string SHA256 of folder path
Output Checksum string SHA256 of Base64 TGZ
Error error Error if folder doesn’t exist or archive creation fails

Example:

package main

import (
    "fmt"
    "log"

    "github.com/ibm-hyper-protect/contract-go/v2/contract"
)

func main() {
    // Folder containing docker-compose.yaml
    folderPath := "./compose"

    tgzBase64, inputHash, outputHash, err := contract.HpcrTgz(folderPath)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("TGZ Base64 (first 100 chars): %s...\n", tgzBase64[:100])
    fmt.Printf("Input SHA256: %s\n", inputHash)
    fmt.Printf("Output SHA256: %s\n", outputHash)
}

Supported Files:

Common Errors:


HpcrTgzEncrypted

Creates an encrypted Base64 TGZ archive from a directory.

Package: github.com/ibm-hyper-protect/contract-go/v2/contract

Signature:

func HpcrTgzEncrypted(folderPath, hyperProtectOs, encryptionCertificate string) (string, string, string, error)

Parameters:

Parameter Type Required/Optional Description
folderPath string Required Path to folder with compose/pods files
hyperProtectOs string Optional Platform identifier (defaults to "hpvs" if empty)
encryptionCertificate string Optional PEM certificate (uses latest HPVS as default if empty)

Returns:

Return Type Description
Encrypted TGZ string Format: hyper-protect-basic.<password>.<data>
Input Checksum string SHA256 of folder path
Output Checksum string SHA256 of encrypted output
Error error Error if folder invalid or encryption fails

Example:

package main

import (
    "fmt"
    "log"

    "github.com/ibm-hyper-protect/contract-go/v2/contract"
)

func main() {
    encrypted, _, _, err := contract.HpcrTgzEncrypted("./compose", "hpvs", "")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Encrypted TGZ: %s\n", encrypted)
}

Common Errors:


HpcrVerifyContract

Validates a contract against the JSON schema for the specified Hyper Protect platform.

Package: github.com/ibm-hyper-protect/contract-go/v2/contract

Signature:

func HpcrVerifyContract(contract, version string) error

Parameters:

Parameter Type Required/Optional Description
contract string Required YAML contract to validate
version string Optional Platform: "hpvs", "hpcr-rhvs", or "hpcc-peerpod" (defaults to "hpvs" if empty)

Returns:

Return Type Description
Error error nil if valid, error with validation details if invalid

Example:

package main

import (
    "fmt"
    "log"

    "github.com/ibm-hyper-protect/contract-go/v2/contract"
)

func main() {
    contractYAML := `
env: |
  type: env
  logging:
    logRouter:
      hostname: 5c2d6b69-c7f0-41bd-b69b-240695369d6e.ingress.us-south.logs.cloud.ibm.com
      iamApiKey: ab00e3c09p1d4ff7fff9f04c12183413
workload: |
  type: workload
  compose:
    archive: ZGF0YQ==
`

    // Validate for HPVS
    err := contract.HpcrVerifyContract(contractYAML, "hpvs")
    if err != nil {
        log.Fatalf("Contract validation failed: %v", err)
    }

    fmt.Println("Contract is valid!")
}

Validated Fields:

Common Errors:


HpcrContractSignedEncrypted

Generates a signed and encrypted contract ready for deployment to Hyper Protect services.

Package: github.com/ibm-hyper-protect/contract-go/v2/contract

Signature:

func HpcrContractSignedEncrypted(contract, hyperProtectOs, encryptionCertificate, privateKey string) (string, string, string, error)

Parameters:

Parameter Type Required/Optional Description
contract string Required YAML contract with env and workload sections
hyperProtectOs string Optional Platform: "hpvs", "hpcr-rhvs", or "hpcc-peerpod" (defaults to "hpvs" if empty)
encryptionCertificate string Optional PEM certificate (uses latest HPVS as default if empty)
privateKey string Required RSA private key (PEM format) for signing

Returns:

Return Type Description
Signed Contract string YAML with encrypted workload, env, and envWorkloadSignature
Input Checksum string SHA256 of original contract
Output Checksum string SHA256 of final contract
Error error Error if validation or signing fails

Example:

package main

import (
    "fmt"
    "log"

    "github.com/ibm-hyper-protect/contract-go/v2/contract"
)

func main() {
    contractYAML := `
env: |
  type: env
  logging:
    logRouter:
      hostname: 5c2d6b69-c7f0-41bd-b69b-240695369d6e.ingress.us-south.logs.cloud.ibm.com
      iamApiKey: ab00e3c09p1d4ff7fff9f04c12183413
workload: |
  type: workload
  compose:
    archive: ZGF0YQ==
`

    privateKey := `-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA...
-----END RSA PRIVATE KEY-----`

    signedContract, inputHash, outputHash, err := contract.HpcrContractSignedEncrypted(
        contractYAML,
        "hpvs",
        "",         // Use default certificate
        privateKey,
    )
    if err != nil {
        log.Fatalf("Failed to generate contract: %v", err)
    }

    fmt.Printf("Signed Contract:\n%s\n", signedContract)
    fmt.Printf("Input SHA256: %s\n", inputHash)
    fmt.Printf("Output SHA256: %s\n", outputHash)
}

Process Flow:

  1. Validates contract schema
  2. Generates public key from private key
  3. Encrypts workload section
  4. Injects signing key into env section
  5. Encrypts env section
  6. Signs encrypted sections with private key
  7. Returns YAML with workload, env, and envWorkloadSignature

Common Errors:


HpcrContractSignedEncryptedContractExpiry

Generates a signed and encrypted contract with time-based expiration using certificate authorities.

Package: github.com/ibm-hyper-protect/contract-go/v2/contract

Signature:

func HpcrContractSignedEncryptedContractExpiry(contract, hyperProtectOs, encryptionCertificate, privateKey, cacert, caKey, csrDataStr, csrPemData string, expiryDays int) (string, string, string, error)

Parameters:

Parameter Type Required/Optional Description
contract string Required YAML contract
hyperProtectOs string Optional Platform identifier (defaults to "hpvs" if empty)
encryptionCertificate string Optional PEM certificate (uses latest HPVS as default if empty)
privateKey string Required RSA private key for signing
cacert string Required CA certificate (PEM format)
caKey string Required CA private key (PEM format)
csrDataStr string Conditionally Required* CSR parameters as JSON (use if not providing PEM)
csrPemData string Conditionally Required* CSR in PEM format (use if not providing JSON)
expiryDays int Required Number of days until contract expires

Note: Either csrDataStr OR csrPemData must be provided, not both.

CSR Parameters JSON Format:

{
  "country": "US",
  "state": "California",
  "location": "San Francisco",
  "org": "MyOrganization",
  "unit": "Engineering",
  "domain": "example.com",
  "mail": "admin@example.com"
}

Returns:

Return Type Description
Signed Contract string Contract with time-limited signature
Input Checksum string SHA256 of original contract
Output Checksum string SHA256 of final contract
Error error Error if validation or signing fails

Example - Using CSR Parameters:

package main

import (
    "encoding/json"
    "fmt"
    "log"

    "github.com/ibm-hyper-protect/contract-go/v2/contract"
)

func main() {
    contractYAML := `...your contract...`
    privateKey := `...your RSA private key...`
    caCert := `...your CA certificate...`
    caKey := `...your CA private key...`

    // Define CSR parameters
    csrParams := map[string]interface{}{
        "country":  "US",
        "state":    "California",
        "location": "San Francisco",
        "org":      "MyOrg",
        "unit":     "DevOps",
        "domain":   "myapp.example.com",
        "mail":     "admin@example.com",
    }

    csrJSON, err := json.Marshal(csrParams)
    if err != nil {
        log.Fatal(err)
    }

    // Generate contract that expires in 90 days
    signedContract, _, _, err := contract.HpcrContractSignedEncryptedContractExpiry(
        contractYAML,
        "hpvs",
        "",                // Default encryption cert
        privateKey,
        caCert,
        caKey,
        string(csrJSON),   // CSR parameters
        "",                // No CSR PEM file
        90,                // Expires in 90 days
    )
    if err != nil {
        log.Fatalf("Contract generation failed: %v", err)
    }

    fmt.Printf("Contract with 90-day expiry generated!\n")
    fmt.Printf("%s\n", signedContract)
}

Example - Using CSR PEM:

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/ibm-hyper-protect/contract-go/v2/contract"
)

func main() {
    // Read CSR PEM file
    csrPEM, err := os.ReadFile("request.csr")
    if err != nil {
        log.Fatal(err)
    }

    contractYAML := `...your contract...`
    privateKey := `...your private key...`
    caCert := `...your CA cert...`
    caKey := `...your CA key...`

    signedContract, _, _, err := contract.HpcrContractSignedEncryptedContractExpiry(
        contractYAML,
        "hpvs",
        "",
        privateKey,
        caCert,
        caKey,
        "",                 // No CSR parameters
        string(csrPEM),     // CSR PEM file
        365,                // 1 year expiry
    )
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Contract generated with 1-year expiry!\n")
}

Use Cases:

Security Considerations:

Common Errors:

HpcrVerifyNetworkConfig

Validates network configuration schema for on-premise deployments of HPVS and HPCR RHVS.

Package: github.com/ibm-hyper-protect/contract-go/v2/network

Signature:

func HpcrVerifyNetworkConfig(networkConfig string) error

Parameters:

Parameter Type Required/Optional Description
networkConfig string Required Network configuration in YAML format

Returns:

Return Type Description
Error error nil if valid, error with details if invalid

Example:

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/ibm-hyper-protect/contract-go/v2/network"
)

func main() {
    // Read network config file
    configData, err := os.ReadFile("network-config.yaml")
    if err != nil {
        log.Fatal(err)
    }

    // Validate schema
    err = network.HpcrVerifyNetworkConfig(string(configData))
    if err != nil {
        log.Fatalf("Invalid network config: %v", err)
    }

    fmt.Println("Network configuration is valid!")
}

Supported Platforms:

Common Errors:


Common Patterns

Pattern 1: Complete Contract Workflow

Generate and deploy a signed, encrypted contract for HPVS:

package main

import (
    "fmt"
    "log"

    "github.com/ibm-hyper-protect/contract-go/v2/certificate"
    "github.com/ibm-hyper-protect/contract-go/v2/contract"
)

func main() {
    // 1. Download encryption certificates
    versions := []string{"1.1.14", "1.1.15"}
    certsJSON, err := certificate.HpcrDownloadEncryptionCertificates(versions, "json", "")
    if err != nil {
        log.Fatal(err)
    }

    // 2. Get specific version certificate
    version, cert, err := certificate.HpcrGetEncryptionCertificateFromJson(certsJSON, "1.1.15")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Using certificate version: %s\n", version)

    // 3. Define your contract
    contractYAML := `
env: |
  type: env
  logging:
    logRouter:
      hostname: 5c2d6b69-c7f0-41bd-b69b-240695369d6e.ingress.us-south.logs.cloud.ibm.com
      iamApiKey: ab00e3c09p1d4ff7fff9f04c12183413
workload: |
  type: workload
  compose:
    archive: your-archive
`

    // 4. Validate contract
    err = contract.HpcrVerifyContract(contractYAML, "hpvs")
    if err != nil {
        log.Fatalf("Contract validation failed: %v", err)
    }

    // 5. Generate signed and encrypted contract
    privateKey := `-----BEGIN RSA PRIVATE KEY-----
...your private key...
-----END RSA PRIVATE KEY-----`

    signedContract, inputHash, outputHash, err := contract.HpcrContractSignedEncrypted(
        contractYAML,
        "hpvs",
        cert,
        privateKey,
    )
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Contract generated successfully!\n")
    fmt.Printf("Input SHA256: %s\n", inputHash)
    fmt.Printf("Output SHA256: %s\n", outputHash)
    fmt.Printf("Signed Contract: %s\n", signedContract)
}

Pattern 2: Image Selection with Version Constraints

Select the latest compatible HPCR image:

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "os/exec"

    "github.com/ibm-hyper-protect/contract-go/v2/image"
)

func main() {
    // Get images from IBM Cloud CLI
    cmd := exec.Command("ibmcloud", "is", "images", "--json")
    output, err := cmd.Output()
    if err != nil {
        log.Fatal(err)
    }

    // Select latest image with version >= 1.1.0
    imageID, imageName, checksum, version, err := image.HpcrSelectImage(
        string(output),
        ">=1.1.0",
    )
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Selected Image:\n")
    fmt.Printf("  ID: %s\n", imageID)
    fmt.Printf("  Name: %s\n", imageName)
    fmt.Printf("  Version: %s\n", version)
    fmt.Printf("  Checksum: %s\n", checksum)
}

Pattern 3: Working with Contract Expiry

Generate a contract with expiration:

package main

import (
    "encoding/json"
    "log"

    "github.com/ibm-hyper-protect/contract-go/v2/contract"
)

func main() {
    contractYAML := `...your contract...`
    privateKey := `...your private key...`
    caCert := `...your CA certificate...`
    caKey := `...your CA key...`

    // CSR parameters
    csrParams := map[string]interface{}{
        "country":  "US",
        "state":    "California",
        "location": "San Francisco",
        "org":      "MyOrg",
        "unit":     "Engineering",
        "domain":   "example.com",
        "mail":     "admin@example.com",
    }

    csrJSON, _ := json.Marshal(csrParams)

    // Generate contract with 90-day expiry
    signedContract, inputHash, outputHash, err := contract.HpcrContractSignedEncryptedContractExpiry(
        contractYAML,
        "hpvs",
        "",           // Use default encryption cert
        privateKey,
        caCert,
        caKey,
        string(csrJSON),
        "",           // Not using CSR PEM file
        90,           // Expire in 90 days
    )
    if err != nil {
        log.Fatal(err)
    }

    // Use the contract...
}

Pattern 4: Encrypting Workload Data

Encrypt different types of data for contracts:

package main

import (
    "fmt"
    "log"

    "github.com/ibm-hyper-protect/contract-go/v2/contract"
)

func main() {
    // Encrypt plain text
    text := "Hello, Hyper Protect!"
    encText, _, _, err := contract.HpcrTextEncrypted(text, "hpvs", "")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Encrypted text: %s\n", encText)

    // Encrypt JSON
    jsonData := `{"key": "value", "number": 42}`
    encJSON, _, _, err := contract.HpcrJsonEncrypted(jsonData, "hpvs", "")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Encrypted JSON: %s\n", encJSON)

    // Encrypt TGZ archive
    encTGZ, _, _, err := contract.HpcrTgzEncrypted("/path/to/compose/folder", "hpvs", "")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Encrypted TGZ: %s\n", encTGZ)
}

Error Handling

Common Error Messages

Error Message Cause Solution
"required parameter is empty" Missing required parameter Ensure all required parameters are provided
"required parameter is missing" Missing required parameter Ensure all required parameters are provided
"not a JSON data" Invalid JSON format Verify JSON syntax
"contract is not a JSON data" Contract is not valid JSON Check contract format
"openssl not found" OpenSSL not installed or not in PATH Install OpenSSL or set OPENSSL_BIN
"schema verification failed" Contract doesn’t match schema Review contract structure against schema
"failed to decrypt password" Invalid private key or corrupted data Verify private key matches public key
"failed to encrypt key" Encryption operation failed Check certificate validity
"folder doesn't exists" Path not found Verify folder path exists
"no Hyper Protect image matching version found" No images match version constraint Adjust version constraint or check available images

Best Practices for Error Handling

  1. Always Check Errors:
    result, err := contract.HpcrText("data")
    if err != nil {
     log.Fatalf("Operation failed: %v", err)
    }
    
  2. Wrap Errors with Context:
    signedContract, _, _, err := contract.HpcrContractSignedEncrypted(...)
    if err != nil {
     return fmt.Errorf("failed to generate signed contract: %w", err)
    }
    
  3. Validate Input Before Processing: ```go // Validate contract schema before encryption err := contract.HpcrVerifyContract(contractYAML, “hpvs”) if err != nil { return fmt.Errorf(“invalid contract: %w”, err) }

// Now proceed with encryption signedContract, _, _, err := contract.HpcrContractSignedEncrypted(…)


4. **Use Checksums for Verification:**
```go
encrypted, inputHash, outputHash, err := contract.HpcrTextEncrypted(data, "hpvs", "")
if err != nil {
    return err
}

// Store checksums for later verification
fmt.Printf("Input checksum: %s\n", inputHash)
fmt.Printf("Output checksum: %s\n", outputHash)

Platform-Specific Constants

The library supports three Hyper Protect platforms:

const (
    HyperProtectOsHpvs     = "hpvs"         // Hyper Protect Virtual Servers
    HyperProtectOsHpcrRhvs = "hpcr-rhvs"    // HPCR for Red Hat Virtualization
    HyperProtectConfidentialContainerPeerPods = "hpcc-peerpod" // HPCC Peer Pods
)

Use these constants when calling functions that require a platform specification:

import "github.com/ibm-hyper-protect/contract-go/v2/common/general"

// Example usage
contract.HpcrContractSignedEncrypted(
    contractYAML,
    general.HyperProtectOsHpvs,  // or "hpvs"
    cert,
    privateKey,
)

Additional Resources

IBM Hyper Protect Documentation