contract-go

IBM Confidential Computing Contract Go Library - API Documentation

Introduction

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

What is a Contract?

A contract is a definition file in YAML format that is used to configure and deploy IBM Confidential Computing workloads. The contract specifies workload details, environment configuration, and attestation settings. When a virtual server instance boots, the bootloader decrypts and validates the contract, then brings up the workload.

Contract Sections

A contract has four valid high-level sections:

Section Required Description
workload Yes Defines the container workload, registry authentication, images, and volumes
env Yes Specifies the deployment environment, logging, and signing key
attestationPublicKey No RSA public key for encrypting attestation records
envWorkloadSignature No Signature of the workload and env sections for integrity verification

Encryption Format

Encrypted sections use one of two formats depending on the target platform:

For Confidential Computing (CCRT, CCRV): contract-basic.<encrypted-password>.<encrypted-data>

For Confidential Computing Containers and Hyper Protect Virtual Servers (CCCO, HPVS): hyper-protect-basic.<encrypted-password>.<encrypted-data>

The encryption process:

  1. Generate a random 32-byte AES password
  2. Encrypt the password with the IBM encryption certificate (RSA)
  3. Encrypt the section data with the AES password (AES-256-CBC)
  4. Combine as <format-prefix>.<base64-encrypted-password>.<base64-encrypted-data>

Supported Platforms

Platform Identifier Official Name Encryption Format
ccrt IBM Confidential Computing Container Runtime (CCRT) contract-basic
ccrv IBM Confidential Computing Container Runtime for Red Hat Virtualization Solutions (CCRV) contract-basic
ccco IBM Confidential Computing Containers for Red Hat OpenShift Container Platform (CCCO) hyper-protect-basic
hpvs IBM Hyper Protect Virtual Servers (HPVS) hyper-protect-basic

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

Password-Protected Private Keys

The following functions support an optional password parameter for encrypted private keys:

Usage:

// Unencrypted private key - pass empty string
result, err := contract.HpcrContractSignedEncrypted(contractYAML, "ccrt", "", privateKey, "")

// Encrypted private key - provide password
result, err := contract.HpcrContractSignedEncrypted(contractYAML, "ccrt", "", encryptedKey, "your-password")

Create encrypted private key:

openssl genrsa -aes256 -out private_encrypted.pem 4096

Error: If encrypted key is provided without password:

private key is encrypted but no password provided - use the password parameter to unlock the key

Attestation Functions

HpcrGetAttestationRecords

Decrypts encrypted attestation records generated by Confidential Computing Services.

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

Signature:

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

Parameters:

Parameter Type Required/Optional Description
data string Required Encrypted attestation data in the format contract-basic.<password>.<data>
privateKey string Required RSA private key (PEM format) used to decrypt the password
password string Optional Password for encrypted private key (empty string if private key is not encrypted)

Returns:

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

Example (Unencrypted Private Key):

package main

import (
    "fmt"
    "log"

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

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

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

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

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

Example (Password-Protected Private Key):

// Encrypted private key
encryptedPrivateKey := `-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,1234567890ABCDEF

MIIEpAIBAAKCAQEA...
-----END RSA PRIVATE KEY-----`

password := "your-secure-password"

// Decrypt attestation records with password-protected key
records, err := attestation.HpcrGetAttestationRecords(encryptedData, encryptedPrivateKey, password)
if err != nil {
    log.Fatalf("Failed to decrypt attestation: %v", err)
}

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

Common Errors:


HpcrVerifySignatureAttestationRecords

Verifies the signature of decrypted attestation records against an IBM attestation certificate to ensure authenticity and integrity.

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

Signature:

func HpcrVerifySignatureAttestationRecords(attestationRecords, signature, attestationCert string) error

Parameters:

Parameter Type Required/Optional Description
attestationRecords string Required Decrypted attestation records content (se-checksums.txt)
signature string Required Binary signature data (se-signature.bin content)
attestationCert string Required IBM attestation certificate in PEM format

Returns:

Return Type Description
Error error nil if signature verification succeeds, error if verification fails

Example:

package main

import (
    "fmt"
    "log"
    "os"

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

func main() {
    // First, decrypt attestation records
    encryptedData := "hyper-protect-basic.aBcD123..." // From CCRT
    privateKey := `-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA...
-----END RSA PRIVATE KEY-----`

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

    // Read signature file (se-signature.bin)
    signatureData, err := os.ReadFile("se-signature.bin")
    if err != nil {
        log.Fatalf("failed to read signature file - %v", err)
    }

    // Read IBM attestation certificate
    certData, err := os.ReadFile("ibm-attestation-cert.pem")
    if err != nil {
        log.Fatalf("failed to read attestation certificate - %v", err)
    }

    // Verify signature
    err = attestation.HpcrVerifySignatureAttestationRecords(
        records,
        signatureData,
        certData,
    )
    if err != nil {
        log.Fatalf("signature verification failed - %v", err)
    }
}

Use Cases:

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, 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
Expiry date string Expiry date of encryption certificate
Expiry Days string Expiry days of encryption certificate
Status string Status of 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, expiry_date, expiry_days, status, 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)
    fmt.Printf("Expiry date: %s\n", expiry_date)
    fmt.Printf("Expiry days: %s\n", expiry_days)
    fmt.Printf("Status: %s\n", status)
}

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:

HpcrVerifyEncryptionCertificateDocument

Validates an encryption certificate document by checking issuer chain, document signature, and validity dates.

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

Signature:

func HpcrVerifyEncryptionCertificateDocument(encryptionCert string, ibmIntermediateCert string, digicertIntermediateCert string, digicertRootCert string) (bool, string, error)

Parameters:

Parameter Type Required/Optional Description
encryptionCert string Required Encryption certificate document content
ibmIntermediateCert string Required IBM intermediate certificate content
digicertIntermediateCert string Required DigiCert intermediate certificate content
digicertRootCert string Required DigiCert root certificate content

Returns:

Return Type Description
Valid bool true if validation succeeds, false otherwise
Message string Validation result details
Error error Error with stage-specific reason on failure

Example:

package main

import (
    "fmt"
    "log"
    "os"

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

func mustRead(path string) string {
    b, err := os.ReadFile(path)
    if err != nil {
        log.Fatal(err)
    }
    return string(b)
}

func main() {
    valid, msg, err := certificate.HpcrVerifyEncryptionCertificateDocument(
        mustRead("ibm-hyper-protect-container-runtime-*-encrypt.crt"),
        mustRead("ibm-hyper-protect-container-runtime-*-intermediate.crt"),
        mustRead("DigiCertTrustedG4CodeSigningRSA4096SHA3842021CA1.crt.pem"),
        mustRead("DigiCertTrustedRootG4.crt.pem"),
    )
    if err != nil || !valid {
        log.Fatalf("Encryption certificate document validation failed: %v", err)
    }

    fmt.Println(msg)
}

Common Errors:


HpcrVerifyAttestationCertificateDocument

Validates an attestation certificate document by checking issuer chain, document signature, and validity dates.

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

Signature:

func HpcrVerifyAttestationCertificateDocument(attestationCert string, ibmIntermediateCert string, digicertIntermediateCert string, digicertRootCert string) (bool, string, error)

Parameters:

Parameter Type Required/Optional Description
attestationCert string Required Attestation certificate document content
ibmIntermediateCert string Required IBM intermediate certificate content
digicertIntermediateCert string Required DigiCert intermediate certificate content
digicertRootCert string Required DigiCert root certificate content

Returns:

Return Type Description
Valid bool true if validation succeeds, false otherwise
Message string Validation result details
Error error Error with stage-specific reason on failure

Example:

package main

import (
    "fmt"
    "log"
    "os"

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

func mustRead(path string) string {
    b, err := os.ReadFile(path)
    if err != nil {
        log.Fatal(err)
    }
    return string(b)
}

func main() {
    valid, msg, err := certificate.HpcrVerifyAttestationCertificateDocument(
        mustRead("ibm-hyper-protect-container-runtime-*-attestation.crt"),
        mustRead("ibm-hyper-protect-container-runtime-*-intermediate.crt"),
        mustRead("DigiCertTrustedG4CodeSigningRSA4096SHA3842021CA1.crt.pem"),
        mustRead("DigiCertTrustedRootG4.crt.pem"),
    )
    if err != nil || !valid {
        log.Fatalf("Attestation certificate document validation failed: %v", err)
    }

    fmt.Println(msg)
}

Common Errors:


HpcrValidateCertificateRevocationList

Validates the CRL (metadata + signature) and ensures the provided certificate serial is not revoked.

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

Signature:

func HpcrValidateCertificateRevocationList(certificateDocument string, ibmIntermediateCert string) (bool, string, error)

Parameters:

Parameter Type Required/Optional Description
certificateDocument string Required Certificate document content (encryption or attestation)
ibmIntermediateCert string Required IBM intermediate certificate content used for CRL signature verification

Returns:

Return Type Description
Valid bool true if CRL validation succeeds and the certificate is not revoked
Message string CRL validation and revocation result details
Error error Error with stage-specific reason on failure

Example:

package main

import (
    "fmt"
    "log"
    "os"

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

func mustRead(path string) string {
    b, err := os.ReadFile(path)
    if err != nil {
        log.Fatal(err)
    }
    return string(b)
}

func main() {
    encryptionCert := mustRead("ibm-hyper-protect-container-runtime-*-encrypt.crt")
    intermediateCert := mustRead("ibm-hyper-protect-container-runtime-*-intermediate.crt")

    valid, msg, err := certificate.HpcrValidateCertificateRevocationList(
        encryptionCert,
        intermediateCert,
    )
    if err != nil || !valid {
        log.Fatalf("CRL validation failed: %v", err)
    }

    fmt.Println(msg)
}

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:

HpcrListAvailableEncCertVersions

Lists available embedded encryption certificate versions for IBM Confidential Computing platforms. Returns certificate versions in JSON or YAML format for all platforms or a specific platform.

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

Signature:

func HpcrListAvailableEncCertVersions(osType, formatType string) (string, error)

Parameters:

Parameter Type Required/Optional Description
osType string Optional Platform identifier: "ccrt", "ccrv", "ccco", or "hpvs" (case-insensitive). Empty string returns all platforms. Note: "hpvs" is an alias for "ccrt"
formatType string Optional Output format: "json" or "yaml" (defaults to "json" if empty)

Returns:

Return Type Description
Certificates string JSON or YAML string containing map of platform to version arrays
Error error Error if marshaling fails, invalid format, or invalid OS type specified

Output Formats:

JSON format (all platforms):

{
  "ccrt": ["26.2.0", "25.11.0", "25.8.1"],
  "ccrv": ["26.5.0", "26.7.1", "26.9.0"],
  "ccco": ["26.7.1", "26.4.0", "25.12.0",]
}

YAML format (specific platform):

ccrt:
  - 26.2.0
  - 25.11.0
  - 25.8.1

Examples:

package main

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

    "github.com/ibm-hyper-protect/contract-go/v2/certificate"
    "gopkg.in/yaml.v3"
)

func main() {
    // Example 1: Get all platforms in JSON format (default)
    allCertsJSON, err := certificate.HpcrListAvailableEncCertVersions("", "json")
    if err != nil {
        log.Fatalf("Failed to list certificates: %v", err)
    }

    var allCerts map[string][]string
    if err := json.Unmarshal([]byte(allCertsJSON), &allCerts); err != nil {
        log.Fatal(err)
    }

    for platform, versions := range allCerts {
        fmt.Printf("Platform %s has %d versions:\n", platform, len(versions))
        for _, version := range versions {
            fmt.Printf("  - %s\n", version)
        }
    }

    // Example 2: Get specific platform in JSON format
    ccrtJSON, err := certificate.HpcrListAvailableEncCertVersions("ccrt", "json")
    if err != nil {
        log.Fatalf("Failed to get CCRT versions: %v", err)
    }

    var ccrtCerts map[string][]string
    json.Unmarshal([]byte(ccrtJSON), &ccrtCerts)
    fmt.Printf("CCRT versions: %v\n", ccrtCerts["ccrt"])
    // Output: CCRT versions: [26.2.0 25.11.0 25.8.1]

    // Example 3: Get all platforms in YAML format
    allCertsYAML, err := certificate.HpcrListAvailableEncCertVersions("", "yaml")
    if err != nil {
        log.Fatalf("Failed to get YAML: %v", err)
    }
    fmt.Println("YAML output:")
    fmt.Println(allCertsYAML)

    // Example 4: Get specific platform in YAML format
    ccrtYAML, err := certificate.HpcrListAvailableEncCertVersions("ccrt", "yaml")
    if err != nil {
        log.Fatalf("Failed to get CCRT YAML: %v", err)
    }
    
    var yamlCerts map[string][]string
    yaml.Unmarshal([]byte(ccrtYAML), &yamlCerts)
    fmt.Printf("CCRT versions from YAML: %v\n", yamlCerts["ccrt"])

    // Example 5: Default to JSON when format is empty
    defaultFormat, err := certificate.HpcrListAvailableEncCertVersions("ccrt", "")
    if err != nil {
        log.Fatalf("Failed: %v", err)
    }
    fmt.Println("Default format (JSON):", defaultFormat)

    // Example 6: Case-insensitive platform names
    upperJSON, err := certificate.HpcrListAvailableEncCertVersions("CCRT", "json")
    if err != nil {
        log.Fatalf("Failed: %v", err)
    }
    fmt.Println("Uppercase CCRT:", upperJSON)

    // Example 7: Invalid platform returns error
    _, err = certificate.HpcrListAvailableEncCertVersions("invalid", "json")
    if err != nil {
        fmt.Printf("Expected error: %v\n", err)
        // Output: Expected error: invalid OS type: invalid. Valid types are: ccrt, ccrv, ccco
    }
}

Use Cases:

Related Functions:


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, Confidential Computing 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 Confidential Computing encryption format.

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

Signature:

func HpcrTextEncrypted(plainText, confidentialComputingOs, certVersion, encryptionCertificate string) (string, string, string, error)

Parameters:

Parameter Type Required/Optional Description
plainText string Required Text to encrypt
certVersion string Optional Certificate version (e.g., "26.2.0", "25.11.0"). Uses latest if empty
encryptionCertificate string Optional PEM certificate (uses default for platform if empty)
confidentialComputingOs string Optional Platform: "ccrt", "ccrv", "ccco", or "hpvs" (defaults to "ccrt" if empty)

Returns:

Return Type Description
Encrypted Data string Format: contract-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, "ccrt", "", "")
    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:


HpcrContractSign

Generates Signed contract from the input contract

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

Signature:

func HpcrContractSign(contract, privateKey, password string) (string, string, string, error)

Parameters:

Parameter Type Required/Optional Description
contract string Required Contract to sign
privateKey string Required RSA private key (PEM format) for signing
password string Optional Password for encrypted private key (empty string if private key is not encrypted)

Returns:

Return Type Description
Signed Contract string YAML with workload, env, and envWorkloadSignature
Input Checksum string SHA256 of original contract
Output Checksum string SHA256 of final contract
Error error Error if text is empty

Example:

package main

import (
    "fmt"
    "log"

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

func main() {
    contractYAML := `
env: contract-basic.fdsiufhaogdhup.idsvoijsndojvpnsv
workload: contract-basic.jriewcbdpoiew.diewuphfwhfep
`
    privateKey := `-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA...
-----END RSA PRIVATE KEY-----`

    // Generates signed contract (no password for unencrypted key)
    signedContract, inputHash, outputHash, err := contract.HpcrContractSign(contractYAML, privateKey, "")
    if err != nil {
        log.Fatalf("Contract Signature creation failed: %v", err)
    }

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

Validated Fields:

Common Errors:


HpcrContractTemplate

Returns built-in contract template content for workload, env, or both as a combined YAML scaffold.

The workload and env template both vary by platform:

os value Workload template Env template
"" / "hpvs" / "ccrt" Standard (compose + play + volumes) Standard (syslog, env vars, volumes)
"ccrv" Podman play only (no compose) Standard
"ccco-peerpod" confidential-containers (no volumes) logRouter + syslog
"ccco-bmtl" confidential-containers + volumes logRouter + syslog + volumes + host-attestation

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

Signature:

func HpcrContractTemplate(templateType, os string) (string, error)

Parameters:

Parameter Type Required/Optional Description
templateType string Optional Template selector: "workload", "env", or "" (returns combined output)
os string Optional Target platform: "ccrv" (play-only workload), "ccco-peerpod" (confidential-containers, no volumes), "ccco-bmtl" (confidential-containers + volumes + host-attestation), "hpvs", "ccrt", or "" (standard compose+play workload)

Returns:

Return Type Description
Template Content string YAML template from the resolved workload file (workload_ccrt.yaml, workload_ccrv.yaml, workload_ccco_peerpod.yaml, or workload_ccco_bmtl.yaml) and/or the resolved env file (env.yaml, env_ccco_peerpod.yaml, or env_ccco_bmtl.yaml)
Error error Error if template type is invalid or template files cannot be read

Example:

package main

import (
    "fmt"
    "log"

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

func main() {
    // Standard workload template
    workloadTemplate, err := contract.HpcrContractTemplate("workload", "ccrt")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Workload template (CCRT):\n%s\n", workloadTemplate)

    // CCRV-specific workload template
    workloadCcrvTemplate, err := contract.HpcrContractTemplate("workload", "ccrv")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Workload template (CCRV):\n%s\n", workloadCcrvTemplate)

    // CCCO Peer Pod workload template
    workloadPeerpodTemplate, err := contract.HpcrContractTemplate("workload", "ccco-peerpod")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Workload template (CCCO Peer Pod):\n%s\n", workloadPeerpodTemplate)

    // CCCO Baremetal workload template
    workloadBmtlTemplate, err := contract.HpcrContractTemplate("workload", "ccco-bmtl")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Workload template (CCCO Baremetal):\n%s\n", workloadBmtlTemplate)

    // Standard env template (hpvs/ccrt/ccrv)
    envTemplate, err := contract.HpcrContractTemplate("env", "")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Env template (standard):\n%s\n", envTemplate)

    // CCCO Peer Pod env template
    envPeerpodTemplate, err := contract.HpcrContractTemplate("env", "ccco-peerpod")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Env template (CCCO Peer Pod):\n%s\n", envPeerpodTemplate)

    // CCCO Baremetal env template
    envBmtlTemplate, err := contract.HpcrContractTemplate("env", "ccco-bmtl")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Env template (CCCO Baremetal):\n%s\n", envBmtlTemplate)

    // Combined template with standard workload (CCRT)
    combinedTemplate, err := contract.HpcrContractTemplate("", "ccrt")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Combined template (CCRT):\n%s\n", combinedTemplate)

    // Combined template with CCRV workload
    combinedCcrvTemplate, err := contract.HpcrContractTemplate("", "ccrv")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Combined template (CCRV):\n%s\n", combinedCcrvTemplate)

    // Combined CCCO Baremetal template
    combinedBmtlTemplate, err := contract.HpcrContractTemplate("", "ccco-bmtl")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Combined template (CCCO Baremetal):\n%s\n", combinedBmtlTemplate)
}

Combined Output Format (templateType == ""):

workload: |
  ...content of the resolved workload template for the given os...
env: |
  ...content of the resolved env template for the given os...

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:


HpcrTextDecrypted

Decrypts the data encrypted using Confidential Computing encrypted format

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

Signature:

func HpcrTextDecrypted(encryptedText, privateKey, password string) (string, string, string, error)

Parameters:

Parameter Type Required/Optional Description
encryptedText string Required Text to decrypt
privateKey string Required Private key to decrypt the text
password string Optional Password for encrypted private key (empty string if private key is not encrypted)

Returns:

Return Type Description
decrypted Data string Decrypt text in format contract-basic.<password>.<data>
Input Checksum string SHA256 of encrypted text
Output Checksum string SHA256 of decrypted output
Error error Error if decryption fails

Example:

package main

import (
    "fmt"
    "log"

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

func main() {
    text := "sensitive data"
    cert := "....your certificate..."
    privateKey := "...your private key..."

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

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

    // Decrypt with unencrypted private key
    decrypted, inputHash, outputHash, err := contract.HpcrTextDecrypted(encrypted, privateKey, "")
    if err != nil {
        log.Fatal(err)
    }

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

Common Errors:


HpcrJsonEncrypted

Encrypts JSON data using the Confidential Computing encryption format.

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

Signature:

func HpcrJsonEncrypted(plainJson, confidentialComputingOs, certVersion, encryptionCertificate string) (string, string, string, error)

Parameters:

Parameter Type Required/Optional Description
plainJson string Required Valid JSON string to encrypt
certVersion string Optional Certificate version (e.g., "26.2.0", "25.11.0"). Uses latest if empty
confidentialComputingOs string Optional Platform: "ccrt", "ccrv", "ccco", or "hpvs" (defaults to "hpvs" if empty)
encryptionCertificate string Optional PEM certificate (uses latest certificate for platform if empty)

Returns:

Return Type Description
Encrypted JSON string Format: contract-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, "ccrt", "", "")
    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, confidentialComputingOs, certVersion, encryptionCertificate string) (string, string, string, error)

Parameters:

Parameter Type Required/Optional Description
folderPath string Required Path to folder with compose/pods files
certVersion string Optional Certificate version (e.g., "26.2.0", "25.11.0"). Uses latest if empty
confidentialComputingOs string Optional Platform: "ccrt", "ccrv", "ccco", or "hpvs" (defaults to "hpvs" if empty)
encryptionCertificate string Optional PEM certificate (uses latest certificate for platform if empty)

Returns:

Return Type Description
Encrypted TGZ string Format: contract-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", "ccrt", "", "")
    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 Confidential Computing platform. Supports validating a complete contract (both workload and env sections together) or an individual section independently — useful for multi-persona workflows where different teams author each section separately.

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

Signature:

func HpcrVerifyContract(contract, version, section string) error

Parameters:

Parameter Type Required/Optional Description
contract string Required YAML contract to validate
version string Optional Platform: "ccrt", "ccrv", or "ccco" (defaults to "ccrt" if empty)
section string Optional Section to validate — use constants SectionBoth (default), SectionWorkload, or SectionEnv

Section validation modes:

Constant Value Input format What is validated
contract.SectionBoth "" Complete contract with workload: and env: wrapper keys Both sections together (default)
contract.SectionWorkload "workload" Raw content starting with type: workload (no wrapper) Workload section only
contract.SectionEnv "env" Raw content starting with type: env (no wrapper) Env section only

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() {
    // Mode 1: Validate a complete contract (both sections with wrapper keys)
    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==
`
    err := contract.HpcrVerifyContract(contractYAML, "ccrt", contract.SectionBoth)
    if err != nil {
        log.Fatalf("Contract validation failed: %v", err)
    }
    fmt.Println("Contract is valid!")

    // Mode 2: Validate only the workload section (raw format, no wrapper key)
    workloadOnly := `
type: workload
compose:
  archive: ZGF0YQ==
`
    err = contract.HpcrVerifyContract(workloadOnly, "ccrt", contract.SectionWorkload)
    if err != nil {
        log.Fatalf("Workload section validation failed: %v", err)
    }
    fmt.Println("Workload section is valid!")

    // Mode 3: Validate only the env section (raw format, no wrapper key)
    envOnly := `
type: env
logging:
  logRouter:
    hostname: 5c2d6b69-c7f0-41bd-b69b-240695369d6e.ingress.us-south.logs.cloud.ibm.com
    iamApiKey: ab00e3c09p1d4ff7fff9f04c12183413
`
    err = contract.HpcrVerifyContract(envOnly, "ccrt", contract.SectionEnv)
    if err != nil {
        log.Fatalf("Env section validation failed: %v", err)
    }
    fmt.Println("Env section is valid!")
}

Validated Fields:

Common Errors:


HpcrContractSignedEncrypted

Generates a signed and encrypted contract ready for deployment to Confidential Computing services.

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

Signature:

func HpcrContractSignedEncrypted(contract, confidentialComputingOs, certVersion, encryptionCertificate, privateKey, password string) (string, string, string, error)

Parameters:

Parameter Type Required/Optional Description
contract string Required YAML contract with env and workload sections
certVersion string Optional Specific certificate version (e.g., "26.2.0"). Uses latest version if empty. Use HpcrListAvailableEncCertVersions to list available versions
confidentialComputingOs string Optional Platform: "ccrt", "ccrv", "ccco", or "hpvs" (defaults to "hpvs" if empty)
encryptionCertificate string Optional PEM certificate (uses latest certificate for platform if empty)
privateKey string Required RSA private key (PEM format) for signing
password string Optional Password for encrypted private key (empty string if private key is not encrypted)

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,
        "ccrt",
        "",         // Use latest certificate version
        "",         // Use embedded certificate
        privateKey,
        "",         // No password for unencrypted key
    )
    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)
}

Example - with specific certificate version:

package main

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

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

func main() {
    // First, check available versions
    certsJSON, err := certificate.HpcrListAvailableEncCertVersions("ccrt", "json")
    if err != nil {
        log.Fatalf("Failed to get versions: %v", err)
    }
    
    var certs map[string][]string
    json.Unmarshal([]byte(certsJSON), &certs)
    fmt.Printf("Available CCRT versions: %v\n", certs["ccrt"])

    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-----`

    // Use specific certificate version
    signedContract, inputHash, outputHash, err := contract.HpcrContractSignedEncrypted(
        contractYAML,
        "ccrt",
        "26.2.0",    // Specify certificate version
        "",          // Use embedded certificate
        privateKey,
        "",          // No password
    )
    if err != nil {
        log.Fatalf("Failed to generate contract: %v", err)
    }

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

Example - with attestation public key

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==
attestationPublicKey: LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQ0lqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FnOEFNSUlDQ2dLQ0FnRUF4cklNT3RvSktWRTZQbGhvVlJ1dgorb3YxaW1jOEZRZUdQZ3VoVFBpQUFrNDVqRStJSnVKTHZtVHFkOE8yVlZwT05iZEhiN3ZpWGEydUwxeFBOcUp2ClVpVmZNTDUyN1B4V25TU3drcitKNDYwamZvZCtaMkJOQ0k1eVV6dVYxQVhvNHV3YmVLVzNYbVM2b2FIT1YrNmsKU1YwWCt3cFE5a3J5QnJ2NWVJc2tsSTBtS3JnaXBOc2N4b3hvNG4rRDlPMWRDVU5XRzZ4MmlpVnVLeXp4VzZZTgordW9wNHZxb3VMM2pGQ1crVkRGVHgycGViNzNqL2V6WnRUVVhEbStPZTc1V21zVkxjUUg4RXZYbVFsRVAvbEduCnZZMWQ1RXI1ZjlBSU5yOEdRWjM1OHNrWENvdCtseDZiMmQveTZwWEFOTFpBR2ZoRmZLSUMxSVdHOTQrRVdqMG4KUFB6Y1NpeHhHUk53bHZjV3BDY3hKTHFEb1VCaDF0NVA4OGJTVVJUVnpuZUVydDVYbUtjRVdDd3JsSGRrSWdGYgp1azFpbWlEOHl4S2RtZmNKdzZzRm5NeDlTb3FxSFFqNk9FUFZrV3E3Y1VYQUVMN05PSzlWTnZzZUxlNnEwRkRVClNLOSt5Ty9PdEdtSEFMcFJtY2dzNGlKOVJmRTlZQUt0a1JQRlRETUdYR0lFUGdnQkIyMHRlblk0ZTRyaXE1UWgKYWp1Y2txd3psRkhjbEZLWk9jMXNMR3NCRmhHSERIZm1taWNnWkhBdVN5YVpaM29QM3czbmhNK2IwT2grSjFSMwpWQUVWWUlDMzArVUZVR1dyTU40Q3ZDLzZaVk5YVkZ4ZkZMcU8raGFnNnI4Q3VqVEtLQ3NiaE5kaVNoNlRvdWhUCjZNY2N3OVg2bkpPdFBhK0E3L0ZVV3BVQ0F3RUFBUT09Ci0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQo=
`

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

    signedContract, inputHash, outputHash, err := contract.HpcrContractSignedEncrypted(
        contractYAML,
        "ccrt",
        "",          // Use default certificate version
        "",          // Use embedded certificate
        privateKey,
        "",          // No password
    )
    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, confidentialComputingOs, certVersion, encryptionCertificate, privateKey, password, cacert, caKey, csrDataStr, csrPemData string, expiryDays int) (string, string, string, error)

Parameters:

Parameter Type Required/Optional Description
contract string Required YAML contract
certVersion string Optional Certificate version (e.g., "26.2.0", "25.11.0"). Uses latest if empty
encryptionCertificate string Optional PEM certificate (uses default for platform if empty)
confidentialComputingOs string Optional Platform: "ccrt", "ccrv", "ccco", or "hpvs" (defaults to "ccrt" if empty)
privateKey string Required RSA private key for signing
password string Optional Password for encrypted private key (empty string if private key is not encrypted)
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,
        "ccrt",
        "",                // Default cert version
        "",                // Default encryption cert
        privateKey,
        "",                // No password for unencrypted key
        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,
        "ccrt",
        "",                // Default cert version
        "",                // Default encryption cert
        privateKey,
        "",                 // No password for unencrypted key
        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:

HpccInitdata

Generates gzipped and encoded initdata string. Supports for both peerpod and baremetal solution Package: github.com/ibm-hyper-protect/contract-go/v2/contract

Signature:

func HpccInitdata(contract, encodedHdrBin string) (string, string, string, error)

Parameters:

Parameter Type Required/Optional Description
contract string Required Signed and encrypted YAML contract
encodedHdrBin string Optional Base64-encoded SE header for baremetal solution. Pass empty string "" for peerpod solution

Returns:

Return Type Description
Gzipped & Encoded String string Initdata String gzipped and encoded
Input Checksum string SHA256 of original contract
Output Checksum string SHA256 of gzipped & encoded initdata string
Error error Error if validation, zipping or encoding fails

Example 1: Peerpod Solution (Without SE Header)

package main

import (
    "fmt"
    "log"

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

func main() {
    contractYAML := `...your signed and encrypted contract...`

    // Pass empty string for encodedHdrBin for standard deployments
    encodedString, inputHash, outputHash, err := contract.HpccInitdata(
        contractYAML,
        "", // No SE header for standard deployment
    )
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Gzipped & Encoded initdata string is generated!\n")
    fmt.Printf("Input SHA256: %s\n", inputHash)
    fmt.Printf("Output SHA256: %s\n", outputHash)
}

Example 2: Baremetal Solution (With SE Header)

package main

import (
    "fmt"
    "log"

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

func main() {
    contractYAML := `...your signed and encrypted contract...`
    
    // Base64-encoded SE header for baremetal deployment
    encodedHdrBin := "VGVzdCBiYXNlNjQgaGVkZXIgb2YgaW1hZ2UgZ2V0dGluZyB1c2VkCg=="

    encodedString, inputHash, outputHash, err := contract.HpccInitdata(
        contractYAML,
        encodedHdrBin, // Provide base64-encoded SE header for baremetal deployment
    )
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Gzipped & Encoded initdata string with SE header is generated!\n")
    fmt.Printf("Input SHA256: %s\n", inputHash)
    fmt.Printf("Output SHA256: %s\n", outputHash)
}

Supported Platforms:

Template Selection:

Common Errors:


Rego Policy Functions

GenerateRegoPolicy

Generates an OPA v1 Rego policy from a Kubernetes pod YAML. Extracts container images and commands from the pod spec and inserts allow_image() and allow_command() rules at the marker position in the template. An OCP baseline rule for Kata pause/infra containers is included automatically.

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

Signature:

func GenerateRegoPolicy(podYAML, templatePath string) (policy, podYAMLBase64, policyBase64 string, err error)

Parameters:

Parameter Type Required/Optional Description
podYAML string Required Kubernetes pod spec in YAML format. Supports Pod kind directly.
templatePath string Optional Path to a custom Rego template file. Pass "" to use the embedded default OPA v1 template.

Returns:

Return Type Description
policy string The generated Rego policy as a plain string
podYAMLBase64 string Standard Base64 encoding of the input pod YAML
policyBase64 string Standard Base64 encoding of the generated policy
err error Non-nil if podYAML is empty, unparseable, or the template cannot be read

Rule Generation Logic:

Container spec allow_image() allow_command()
No command / args anchored regex for image permissive (image-only, no arg constraint)
Has command and/or args (single-line) anchored regex for image strict: count(args) == N + per-index args[i] == "..."
Has command and/or args (multiline script) anchored regex for image strict: named validator function extracted for the script arg

Insertion order in generated policy:

  1. CreateContainerRequest wiring rule — links allow_image + allow_command to OCI input
  2. OCP baseline allow_image — admits Kata pause/infra containers (digest-pinned)
  3. Pod allow_image rules — one per unique image (deduplicated)
  4. OCP baseline allow_command — permissive for pause/infra containers
  5. Pod allow_command rules — strict or permissive per container
  6. Script validators — one named function per multiline script arg

Example 1: Generate a policy from a pod YAML file:

package main

import (
    "fmt"
    "log"
    "os"

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

func main() {
    podYAML, err := os.ReadFile("pod.yaml")
    if err != nil {
        log.Fatal(err)
    }

    policy, podYAMLBase64, policyBase64, err := rego.GenerateRegoPolicy(string(podYAML), "")
    if err != nil {
        log.Fatalf("Failed to generate policy: %v", err)
    }

    fmt.Println("Generated Policy ", policy)
    fmt.Println("Pod YAML (Base64): ", podYAMLBase64)
    fmt.Println("Policy (Base64):  ", policyBase64)
}

Example 2: Save policy to a file:

package main

import (
    "log"
    "os"

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

func main() {
    podYAML, err := os.ReadFile("pod.yaml")
    if err != nil {
        log.Fatal(err)
    }

    policy, _, _, err := rego.GenerateRegoPolicy(string(podYAML), "")
    if err != nil {
        log.Fatalf("Failed to generate policy: %v", err)
    }

}

Example 3: Use a custom Rego template:

policy, _, _, err := rego.GenerateRegoPolicy(string(podYAML), "/path/to/custom-template.rego")
if err != nil {
    log.Fatal(err)
}

The custom template must contain the generator marker at the insertion point:

# --- generator inserts CreateContainerRequest, allow_image, and allow_command rules here ---

Example 4: Use Base64 outputs for contract embedding:

package main

import (
    "fmt"
    "log"
    "os"

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

func main() {
    podYAML, err := os.ReadFile("pod.yaml")
    if err != nil {
        log.Fatal(err)
    }

    // All three return values are useful for contract workflows
    policy, podYAMLBase64, policyBase64, err := rego.GenerateRegoPolicy(string(podYAML), "")
    if err != nil {
        log.Fatalf("Failed to generate policy: %v", err)
    }

    // policyBase64 can be embedded directly in a contract YAML
    fmt.Println("Embed this in your contract:")
    fmt.Printf("  regoPolicy: %s\n", policyBase64)

    // podYAMLBase64 is the audit record of what input produced this policy
    fmt.Println("Input audit record (pod YAML Base64):", podYAMLBase64)

    _ = policy
}

Sealed Secret Functions

HpccSealedSecret

Encrypts a secret using AES-256-GCM with RSA key wrapping and RSA-SHA512 signing for CCCO workload or environment configurations.

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

Signature:

func HpccSealedSecret(secret, secretType, encryptionKey, signingKey string) (string, string, string, string, string, error)

Parameters:

Parameter Type Required/Optional Description
secret string Required The plaintext secret to encrypt
secretType string Required Either "workload" or "env" - determines key IDs used in the sealed secret
encryptionKey string Optional RSA private key for encryption in PEM format string. If empty string "", generates new 2048-bit RSA key
signingKey string Optional RSA private key for signing in PEM format string. If empty string "", generates new 2048-bit RSA key

Secret Types:

Value Key IDs Used
"workload" workload_decrypt, workload_verify
"env" env_decrypt, env_verify

Returns:

Return Type Description
Sealed Secret string The encrypted secret in JWS compact serialization format (sealed.<header>.<payload>.<signature>)
Decryption Private Key string RSA private key for decryption in PEM format. IMPORTANT: Store securely - needed to decrypt the secret
Verification Public Key string RSA public key for signature verification in PEM format
Input Checksum string SHA-256 hash of the input plaintext secret
Output Checksum string SHA-256 hash of the sealed secret output
Error error Error if encryption fails or inputs are invalid

Example 1: Generate New Keys (Recommended for New Secrets):

package main

import (
    "fmt"
    "log"
    "os"

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

func main() {
    // Secret to encrypt
    secret := "my-database-password"

    // Seal the secret - generates new keys automatically
    sealedSecret, decryptionKey, verificationKey, inputHash, encryptedHash, err := secrets.HpccSealedSecret(
        secret,
        "workload",
        "",  // Empty string to auto-generate encryption key
        "",  // Empty string to auto-generate signing key
    )
    if err != nil {
        log.Fatalf("Failed to seal secret: %v", err)
    }

    fmt.Printf("Sealed Secret:\n%s\n\n", sealedSecret)
    fmt.Printf("Input SHA256: %s\n", inputHash)
    fmt.Printf("Output SHA256: %s\n\n", encryptedHash)
    
    // IMPORTANT: Save the decryption key securely
    err = os.WriteFile("decryption-key.pem", []byte(decryptionKey), 0600)
    if err != nil {
        log.Fatalf("Failed to save decryption key: %v", err)
    }
    
    // Save verification key (can be shared publicly)
    err = os.WriteFile("verification-key.pem", []byte(verificationKey), 0644)
    if err != nil {
        log.Fatalf("Failed to save verification key: %v", err)
    }

    fmt.Println("Keys saved successfully!")
    fmt.Println("Use the sealed secret in your contract")
}

Example 2: Use Existing Key Strings (PEM Format):

package main

import (
    "fmt"
    "log"

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

func main() {
    // Provide keys as PEM format strings
    encryptionKeyPEM := `-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN
... (your encryption key content) ...
-----END RSA PRIVATE KEY-----`

    signingKeyPEM := `-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAabcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMN
... (your signing key content) ...
-----END RSA PRIVATE KEY-----`

    // Seal secret with provided key strings
    secret := "my-api-token"
    sealedSecret, _, _, inputHash, encryptedHash, err := secrets.HpccSealedSecret(
        secret,
        "env",
        encryptionKeyPEM,  // Provide encryption key as PEM string
        signingKeyPEM,     // Provide signing key as PEM string
    )
    if err != nil {
        log.Fatalf("Failed to seal secret: %v", err)
    }

    fmt.Printf("Sealed Secret:\n%s\n", sealedSecret)
    fmt.Printf("Input SHA256: %s\n", inputHash)
    fmt.Printf("Output SHA256: %s\n", encryptedHash)
}

Example 3: Seal Multiple Secrets with Same Keys:

package main

import (
    "fmt"
    "log"

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

func main() {
    // Generate keys once
    firstSealed, decryptKey, signKey, _, _, err := secrets.HpccSealedSecret(
        "first-secret",
        "workload",
        "",  // Auto-generate
        "",  // Auto-generate
    )
    if err != nil {
        log.Fatal(err)
    }

    // Reuse the same keys (as strings) for additional secrets
    secondSealed, _, _, _, _, err := secrets.HpccSealedSecret(
        "second-secret",
        "workload",
        decryptKey,  // Reuse encryption key string
        signKey,     // Reuse signing key string (can use same key for both)
    )
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("First Sealed Secret:\n%s\n\n", firstSealed)
    fmt.Printf("Second Sealed Secret:\n%s\n", secondSealed)
}

Example 4: Using Sealed Secrets in Contracts:

package main

import (
    "fmt"
    "log"

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

func main() {
    // Seal database password for workload
    dbPassword := "super-secret-db-password"
    workloadSealed, _, _, _, _, err := secrets.HpccSealedSecret(
        dbPassword,
        "workload",
        "",
        "",
    )
    if err != nil {
        log.Fatal(err)
    }

    // Seal API key for environment
    apiKey := "my-api-key-12345"
    envSealed, _, _, _, _, err := secrets.HpccSealedSecret(
        apiKey,
        "env",
        "",
        "",
    )
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Workload Sealed Secret:\n%s\n\n", workloadSealed)
    fmt.Printf("Environment Sealed Secret:\n%s\n", envSealed)
}

Sealed Secret Format:

The sealed secret uses JWS (JSON Web Signature) compact serialization format:

sealed.<header>.<payload>.<signature>

Where:

Encryption Process:

  1. Generate random 32-byte AES-256 key
  2. Generate random 12-byte initialization vector (IV)
  3. Encrypt secret with AES-256-GCM using key and IV
  4. Encrypt AES key with RSA-PKCS1v15 using public key
  5. Create JSON envelope with encrypted data and key
  6. Sign envelope with RSA-SHA512 using private key
  7. Construct JWS format with header, payload, and signature

Security Features:

Use Cases:

Common Errors:


Image Spec Functions

HpccGenerateImageSpec

Fetches the OCI image config from a container registry and generates a Kubernetes pod YAML snippet in a single call. Designed for use with the registryMapping feature of confidential-containers workload contracts.

The generated YAML includes a # image user: <value> comment at the top that identifies the user declared by the image. The imageUser return value carries the same information programmatically.

Image USER field imageUser returned securityContext generated
"26" "26" runAsUser: 26
"26:26" "26:26" runAsUser: 26, runAsGroup: 26
"postgres" "postgres" (none — named users cannot be represented as a UID)
(empty) "no user specified" (none)

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

Signature:

func HpccGenerateImageSpec(imageRef, containerName, username, password string) (string, string, string, string, error)

Parameters:

Parameter Type Required Description
imageRef string Required Fully-qualified OCI image reference (e.g. quay.io/fedora/fedora:38 or digest ref)
containerName string Optional Name for the container in the generated pod spec; auto-derived from the image name when empty
username string Optional Registry username for private image access; pass "" for public images
password string Optional Registry password / API key for private image access; pass "" for public images

Returns:

Value Type Description
yaml string Kubernetes pod YAML snippet (spec.containers[...]) with a leading # image user: comment
imageUser string Raw USER value from the image config, or "no user specified" when unset
inputSHA string SHA256 hex of imageRef
outputSHA string SHA256 hex of the generated YAML
error error Non-nil if the image cannot be fetched or reference is malformed

Example:

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

// Public image — postgres uses numeric UID 26
yaml, imageUser, inputSHA, outputSHA, err := imagespec.HpccGenerateImageSpec(
    "quay.io/sclorg/postgresql-15-c9s:latest",
    "",  // auto-derive name → "postgresql-15-c9s"
    "",  // no credentials needed
    "",
)
// imageUser == "26"
// yaml starts with: # image user: 26

// Image with a named user (e.g. "postgres")
yaml, imageUser, _, _, err = imagespec.HpccGenerateImageSpec(
    "docker.io/library/postgres:16",
    "postgres",
    "",
    "",
)
// imageUser == "postgres"
// yaml starts with: # image user: postgres
// NOTE: no securityContext.runAsUser is emitted for named users.

// Private registry
yaml, imageUser, _, _, err = imagespec.HpccGenerateImageSpec(
    "us.icr.io/my-ns/my-app:latest",
    "my-app",
    "iamapikey",
    "<API_KEY>",
)

Error Messages:


HpcrVerifyNetworkConfig

Validates network configuration schema for on-premise deployments of CCRT and CCRV.

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, "ccrt")
    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,
        "ccrt",
        "",           // Default cert version
        cert,
        privateKey,
        "",           // No password for unencrypted key
    )
    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,
        "ccrt",
        "",           // Default cert version
        "",           // Use default encryption cert
        privateKey,
        "",           // No password for unencrypted key
        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, Confidential Computing!"
    encText, _, _, err := contract.HpcrTextEncrypted(text, "ccrt", "", "")
    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, "ccrt", "", "")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Encrypted JSON: %s\n", encJSON)

    // Encrypt TGZ archive
    encTGZ, _, _, err := contract.HpcrTgzEncrypted("/path/to/compose/folder", "ccrt", "", "")
    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, “ccrt”) 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, "ccrt", "", "")
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 IBM Confidential Computing platforms:

const (
    ConfidentialComputingOsCcrt     = "ccrt"         // IBM Confidential Computing Container Runtime (CCRT)
    ConfidentialComputingOsCcrv = "ccrv"    // IBM Confidential Computing Container Runtime for Red Hat Virtualization Solutions (CCRV)
    ConfidentialComputingOsCcco = "ccco" // IBM Confidential Computing Containers for Red Hat OpenShift Container Platform (CCCO)
)

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.ConfidentialComputingOsCcrt,  // or "ccrt"
    "",                                    // certVersion (empty for default)
    "",                                    // encryptionCertificate (empty for embedded)
    privateKey,
    "",                                    // password (empty if no password)
)

Additional Resources

IBM Confidential Computing Documentation