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.
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.
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 |
Encrypted sections use the format: hyper-protect-basic.<encrypted-password>.<encrypted-data>
The encryption process:
hyper-protect-basic.<base64-encrypted-password>.<base64-encrypted-data>| Platform Identifier | Official Name |
|---|---|
ccrt |
IBM Confidential Computing Container Runtime (CCRT) |
ccrv |
IBM Confidential Computing Container Runtime for Red Hat Virtualization Solutions (CCRV) |
ccco |
IBM Confidential Computing Containers for Red Hat OpenShift Container Platform (CCCO) |
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
The following functions support an optional password parameter for encrypted private keys:
HpcrGetAttestationRecordsHpcrTextDecryptedHpcrContractSignHpcrContractSignedEncryptedHpcrContractSignedEncryptedContractExpiryUsage:
// 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
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 hyper-protect-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:
"required parameter is missing" - One or more parameters are empty"private key is encrypted but no password provided" - Encrypted private key detected without password"failed to decrypt password" - Invalid private key or corrupted encrypted data"failed to decrypt attestation records" - Invalid password or corrupted dataVerifies 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:
"required parameter is missing" - One or more parameters are empty or signature is nil"failed to parse PEM block from attestation certificate" - Invalid certificate format"failed to parse attestation certificate" - Corrupted certificate data"attestation certificate does not contain a valid RSA public key" - Certificate doesn’t have RSA key"signature verification failed" - signature verification fails or parameters are invalidDownloads 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:
"required parameter is missing" - Version list is empty"encryption certificate doesn't exist in <url>" - Version not available"failed to download encryption certificate" - Network or access error"invalid output format" - Format type not “json” or “yaml”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:
"required parameter is missing" - JSON or version parameter is emptyValidates 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:
"failed to parse PEM block" - Invalid certificate format"failed to parse certificate" - Corrupted or invalid certificate data"Encryption certificate has already expired on <date>" - Certificate has expiredValidates 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:
"required parameter is missing" - One or more certificate inputs are empty"CA verify failed - ..." - Root/intermediate trust chain validation failed"doc signature verify failed - ..." - Document signature check failed"date verify failed - ..." - Document certificate is expired or not yet validValidates 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:
"required parameter is missing" - One or more certificate inputs are empty"CA verify failed - ..." - Root/intermediate trust chain validation failed"doc signature verify failed - ..." - Document signature check failed"date verify failed - ..." - Document certificate is expired or not yet validValidates 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:
"required parameter is missing" - One or more certificate inputs are empty"CRL signature verify failed - ..." - CRL metadata/signature checks failed"serial revoked failed - ..." - The certificate is listed as revokedSelects 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:
data.ibm_is_images.hyper_protect_images.imagescurl -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
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:
">= 1.1.0" - Version 1.1.0 or higher"~1.1.14" - Patch versions of 1.1.x (e.g., 1.1.14, 1.1.15)"^1.1.0" - Minor versions of 1.x.x (e.g., 1.1.0, 1.2.0)"1.1.15" - Exact version match"" - Latest available versionCommon Errors:
"required parameter is empty" - Image JSON data is missing"no Confidential Computing image matching version found" - No images match the version constraint"failed to unmarshal JSON" - Invalid JSON formatImage Selection Criteria: The function filters images based on:
s390xavailablepublichyper-protect-*-s390x-hpcr patternibm-hyper-protect-container-runtime-* patternLists 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.4.1", "25.11.0", "25.8.1"],
"ccco": ["26.4.0", "25.12.0", "25.10.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:
HpcrContractSignedEncrypted - Use specific version with certVersion parameterGenerates 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:
"required parameter is empty" - plainText parameter is missing or emptyEncrypts 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 |
confidentialComputingOs |
string |
Optional | Platform: "ccrt", "ccrv", or "ccco" (defaults to "ccrt" if empty) |
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) |
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, "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:
"required parameter is empty" - plainText parameter is missing or empty"failed to generate encrypted string" - Encryption operation failed"failed to fetch encryption certificate" - Invalid confidentialComputingOs value or certificate issue"openssl not found" - OpenSSL not installed or not in PATHGenerates 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: hyper-protect-basic.fdsiufhaogdhup.idsvoijsndojvpnsv
workload: hyper-protect-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:
"private key is encrypted but no password provided" - Encrypted private key detected without password"failed to sign contract" - Signature generation failedReturns built-in contract template content for workload, env, or both as a combined YAML scaffold.
Package: github.com/ibm-hyper-protect/contract-go/v2/contract
Signature:
func HpcrContractTemplate(templateType string) (string, error)
Parameters:
| Parameter | Type | Required/Optional | Description |
|---|---|---|---|
templateType |
string |
Optional | Template selector: "workload", "env", or "" (returns combined output) |
Returns:
| Return | Type | Description |
|---|---|---|
| Template Content | string |
YAML template content from contract/template/workload.yaml, contract/template/env.yaml, or both |
| 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() {
workloadTemplate, err := contract.HpcrContractTemplate("workload")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Workload template:\n%s\n", workloadTemplate)
envTemplate, err := contract.HpcrContractTemplate("env")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Env template:\n%s\n", envTemplate)
combinedTemplate, err := contract.HpcrContractTemplate("")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Combined template:\n%s\n", combinedTemplate)
}
Combined Output Format (templateType == ""):
workload: |
...content of workload.yaml...
env: |
...content of env.yaml...
Common Errors:
"unsupported template type: <value>" - templateType is not one of "workload", "env", or """failed to read workload template" - Unable to read contract/template/workload.yaml"failed to read env template" - Unable to read contract/template/env.yamlGenerates 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:
"not a JSON data" - Invalid JSON format in plainJson parameterDecrypts 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 hyper-protect-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:
"required parameter is empty" - encryptedText or privateKey or both parameter(s) are missing or empty"private key is encrypted but no password provided" - Encrypted private key detected without password"openssl not found" - OpenSSL not installed or not in PATHfailed to decrypt text - failed to decrypt the encrypted textEncrypts 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 |
confidentialComputingOs |
string |
Optional | Platform: "ccrt", "ccrv", or "ccco" (defaults to "ccrt" if empty) |
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) |
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, "ccrt", "", "")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Encrypted config: %s\n", encrypted)
}
Common Errors:
"contract is not a JSON data" - Invalid JSON format in plainJson parameter"failed to generate encrypted JSON" - Encryption operation failed"failed to fetch encryption certificate" - Invalid confidentialComputingOs value or certificate issue"openssl not found" - OpenSSL not installed or not in PATHCreates 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:
docker-compose.yaml - Docker Compose configurationpods.yaml - Podman play configurationCommon Errors:
"required parameter is empty" - folderPath parameter is missing or empty"folder doesn't exists - <path>" - Specified folder path does not exist"failed to get files and folder under path" - Permission or access error"failed to get base64 tgz" - Archive creation failedCreates 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 |
confidentialComputingOs |
string |
Optional | Platform: "ccrt", "ccrv", or "ccco" (defaults to "ccrt" if empty) |
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) |
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", "ccrt", "", "")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Encrypted TGZ: %s\n", encrypted)
}
Common Errors:
"required parameter is empty" - folderPath parameter is missing or empty"folder doesn't exists - <path>" - Specified folder path does not exist"failed to generate encrypted tgz" - Encryption operation failed"failed to fetch encryption certificate" - Invalid confidentialComputingOs value or certificate issue"openssl not found" - OpenSSL not installed or not in PATHValidates a contract against the JSON schema for the specified Confidential Computing 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: "ccrt", "ccrv", or "ccco" (defaults to "ccrt" 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 CCRT
err := contract.HpcrVerifyContract(contractYAML, "ccrt")
if err != nil {
log.Fatalf("Contract validation failed: %v", err)
}
fmt.Println("Contract is valid!")
}
Validated Fields:
Common Errors:
"failed to convert to map" - Invalid contract YAML structure"error fetching contract schema" - Invalid version/platform specified"failed to parse schema" - Internal schema parsing error"contract validation failed" - Contract does not match the required schemaGenerates 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 |
confidentialComputingOs |
string |
Optional | Platform: "ccrt", "ccrv", or "ccco" (defaults to "ccrt" if empty) |
certVersion |
string |
Optional | Specific certificate version (e.g., "26.2.0"). Uses latest version if empty. Use HpcrListAvailableEncCertVersions to list available versions |
encryptionCertificate |
string |
Optional | PEM certificate (uses embedded certificate based on platform and version 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:
workload, env, and envWorkloadSignatureCommon Errors:
"schema verification failed" - Contract does not match required schema"required parameter is empty" - contract or privateKey parameter is missing"failed to fetch encryption certificate" - Invalid confidentialComputingOs value or certificate issue"Failed to encrypt contract" - Encryption certificate has expired or is invalid"failed to generate public key" - Invalid private key format"failed to sign and encrypt contract" - Signing or encryption operation failed"failed to unmarshal YAML" - Invalid contract YAML format"failed to encrypt workload" - Workload encryption failed"failed to inject signingKey to env" - Error injecting signing key into env section"failed to encrypt env" - Env section encryption failed"failed to sign contract" - Signature generation failedGenerates 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 |
confidentialComputingOs |
string |
Optional | Platform: "ccrt", "ccrv", or "ccco" (defaults to "ccrt" if empty) |
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) |
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:
"schema verification failed" - Contract does not match required schema"required parameter is empty" - contract, privateKey, cacert, or caKey parameter is missing"the CSR parameters and CSR PEM file are parsed together or both are nil" - Either provide csrDataStr OR csrPemData, not both or neither"failed to generate signing certificate" - Error creating signing certificate with CSR"failed to generate signed and encrypted contract" - Signing or encryption operation failedHpcrContractSignedEncrypted also applyGenerates gzipped and encoded initdata string.
Package: github.com/ibm-hyper-protect/contract-go/v2/contract
Signature:
func HpccInitdata(contract string) (string, string, string, error)
Parameters:
| Parameter | Type | Required/Optional | Description |
|---|---|---|---|
contract |
string |
Required |
Yaml contract |
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:
package main
import (
"fmt"
"log"
"os"
"github.com/ibm-hyper-protect/contract-go/v2/contract"
)
func main() {
contractYAML := `...your contract...`
encodedString, _, _, err := contract.HpccInitdata(
contractYAML
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Gzipped & Encoded initdata string is generated!\n")
}
Supported Platforms:
Common Errors:
"failed while parsing the template toml" - Error while parsing the template initdata toml file"failed while creating initdata.toml" - Failed while replacing encrypted contract in initdata.toml file"failed while gzipping initdata" - Failed while compressing the content of inidata.toml fileEncrypts 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:
RS512) and key IDEncryption Process:
Security Features:
Use Cases:
Common Errors:
"secret cannot be empty" - Secret parameter is empty"invalid secret type: must be 'workload' or 'env'" - Invalid secretType value (must be lowercase string)"failed to extract public key from encryption private key" - Invalid encryption key PEM format"failed to extract public key from signing private key" - Invalid signing key PEM format"failed to generate encryption key pair" - Key generation failed"failed to generate signing key pair" - Key generation failed"failed to encrypt secret" - Encryption operation failedValidates 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:
"Invalid schema file" - Invalid YAML format in network configuration"error unmarshelling the YAML file" - Failed to parse YAML structure"failed to parse schema" - Internal schema parsing error"network schema verification failed" - Network configuration does not match the required schemaGenerate 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)
}
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)
}
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...
}
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 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 |
result, err := contract.HpcrText("data")
if err != nil {
log.Fatalf("Operation failed: %v", err)
}
signedContract, _, _, err := contract.HpcrContractSignedEncrypted(...)
if err != nil {
return fmt.Errorf("failed to generate signed 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)
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)
)