Creating TDF's
Encrypting / Decrypting zTDF
- Go
- Java
- Typescript
package main
import (
"bytes"
"log"
"strings"
"github.com/opentdf/platform/sdk"
)
func main() {
log.Println("🚀 Starting OpenTDF example...")
platformEndpoint := "http://localhost:8080"
log.Printf("📡 Connecting to platform: %s", platformEndpoint)
// Create a new client
log.Println("🔐 Initializing new SDK client...")
client, err := sdk.New(
platformEndpoint,
sdk.WithClientCredentials("opentdf", "secret", nil),
)
if err != nil {
log.Fatalf("❌ Client initialization failed: %v", err)
}
// Encrypt ztdf
log.Println("📝 Preparing sensitive data for encryption...")
str := strings.NewReader("Sensitive data!")
buf := &bytes.Buffer{}
log.Println("🔒 Encrypting data...")
manifest, err := client.CreateTDF(buf, str,
//sdk.WithDataAttributes("https://opentdf.io/attr/role/value/developer"),
sdk.WithKasInformation(
sdk.KASInfo{
URL: platformEndpoint,
},
),
)
if err != nil {
log.Fatalf("❌ Encryption failed: %v", err)
}
log.Println("✅ Data successfully encrypted")
log.Printf("📋 TDF Manifest details:\n\n%v\n\n", manifest)
// Decrypt ZTDF
log.Println("🔓 Decrypting data...")
tdfReader, err := client.LoadTDF(bytes.NewReader(buf.Bytes()))
if err != nil {
log.Fatalf("❌ Decryption failed: %v", err)
}
// Create a buffer to capture the decrypted data
var decryptedBuf bytes.Buffer
if _, err = tdfReader.WriteTo(&decryptedBuf); err != nil {
log.Fatalf("❌ Failed to write decrypted data: %v", err)
}
log.Printf("📤 Decrypted content: \n\n%s\n\n", decryptedBuf.String())
log.Println("✅ Example complete!")
}
package io.opentdf.platform;
import io.opentdf.platform.sdk.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.io.IOException;
import java.nio.file.StandardOpenOption;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
public class EncryptExample {
public static void main(String[] args) {
try {
System.out.println("🚀 Starting OpenTDF example...");
String clientId = "opentdf";
String clientSecret = "secret";
String platformEndpoint = "http://localhost:8080";
System.out.println("📡 Connecting to platform: " + platformEndpoint);
// Create a new client
System.out.println("🔐 Initializing new SDK client...");
SDKBuilder builder = SDKBuilder.newBuilder();
SDK sdk = builder.platformEndpoint(platformEndpoint)
.clientSecret(clientId, clientSecret)
.useInsecurePlaintextConnection(true) // Set to true for http:// connections
.build();
// Encrypt TDF
System.out.println("📝 Preparing sensitive data for encryption...");
String sensitiveData = "Sensitive data!";
var kasInfo = new Config.KASInfo();
kasInfo.URL = platformEndpoint + "/kas";
var tdfConfig = Config.newTDFConfig(Config.withKasInformation(kasInfo));
var inputStream = new ByteArrayInputStream(sensitiveData.getBytes(StandardCharsets.UTF_8));
var outputStream = new ByteArrayOutputStream();
System.out.println("🔒 Encrypting data...");
sdk.createTDF(inputStream, outputStream, tdfConfig);
System.out.println("✅ Data successfully encrypted");
System.out.println("📋 TDF created with " + outputStream.size() + " bytes");
// Decrypt ZTDF
System.out.println("🔓 Decrypting data...");
var encryptedData = outputStream.toByteArray();
// Save to temporary file for decryption
Path tempFile = Files.createTempFile("encrypted", ".tdf");
try {
Files.write(tempFile, encryptedData);
try (var fileChannel = FileChannel.open(tempFile, StandardOpenOption.READ)) {
var readerConfig = Config.newTDFReaderConfig();
var reader = sdk.loadTDF(fileChannel, readerConfig);
var decryptedOutput = new ByteArrayOutputStream();
reader.readPayload(decryptedOutput);
String decryptedContent = new String(decryptedOutput.toByteArray(), StandardCharsets.UTF_8);
System.out.println("📤 Decrypted content: \n\n" + decryptedContent + "\n");
}
} catch (Exception e) {
// Clean up
Files.deleteIfExists(tempFile);
}
System.out.println("✅ Example complete!");
} catch (IOException | AutoConfigureException e) {
System.err.println("❌ Error occurred: " + e.getMessage());
e.printStackTrace();
}
}
}
import { AuthProviders, OpenTDF, CreateZTDFOptions, DecoratedStream, ReadOptions } from '@opentdf/sdk';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
// Configuration Options
const platformEndpoint = "http://localhost:8080";
const oidcOrigin = "http://localhost:8888/realms/opentdf";
const clientId = "opentdf";
const clientSecret = "secret";
async function main() {
try {
console.log("🚀 Starting OpenTDF example...");
// Authentication options (vary by middleware)
// For client credentials flow
console.log("🔑 Setting up authentication...");
const authProvider = await AuthProviders.clientSecretAuthProvider({
clientId,
clientSecret,
oidcOrigin,
exchange: 'client',
});
console.log("✅ Authentication provider created");
// Create OpenTDF client
console.log("🔧 Creating OpenTDF client...");
const client = new OpenTDF({
authProvider: authProvider,
platformUrl: platformEndpoint,
});
console.log("✅ Client created");
// ABAC - Attribute-Based Access Control
// Option 1: No attributes (simplest for demonstration)
const attributes: string[] = [];
// Option 2: With attributes (requires proper attribute configuration on platform)
// const attributes = ["http://example.com/attr/classification/value/secret"];
// Create temporary files
const tempDir = os.tmpdir();
const inputFile = path.join(tempDir, 'opentdf-input.txt');
const encryptedFile = path.join(tempDir, 'opentdf-encrypted.tdf');
const decryptedFile = path.join(tempDir, 'opentdf-decrypted.txt');
console.log(`📁 Using temp files:`);
console.log(` Input: ${inputFile}`);
console.log(` Encrypted: ${encryptedFile}`);
console.log(` Decrypted: ${decryptedFile}`);
// Write input data to temporary file
const inputData = "This is sensitive data that will be encrypted with OpenTDF!";
console.log("📝 Preparing sensitive data for encryption...");
fs.writeFileSync(inputFile, inputData, 'utf8');
console.log(`✅ Input file written: ${inputData}`);
// Encrypt using OpenTDF client
console.log("🔒 Starting encryption...");
console.log("📖 Reading input file for encryption...");
// Read the file and create a Web ReadableStream
console.log("📡 Calling client.encrypt...");
let opts: CreateZTDFOptions = {
source: { type: 'buffer', location: new TextEncoder().encode(fs.readFileSync(inputFile).toString()) },
}
let tdf = await client.createZTDF(opts);
// Save encrypted stream to file
console.log(`💾 Saving encrypted data to temp file ${encryptedFile}`);
const encrypted = await new Response(tdf).bytes()
fs.writeFileSync(encryptedFile, encrypted);
console.log('✅ Data encrypted and saved to file!');
// Decrypt ZTDF
console.log("🔓 Decrypting data...");
const fileBuffer: Buffer = fs.readFileSync(encryptedFile);
const byteArray: Uint8Array = new Uint8Array(fileBuffer);
const decoratedStream: DecoratedStream = await client.read({
source: { type: 'buffer', location: byteArray },
} as ReadOptions);
const decrypted = await new Response(decoratedStream).text();
// Save decrypted stream to file
console.log("💾 Saving decrypted data to temp file...");
fs.writeFileSync(decryptedFile, decrypted);
// Read and display the decrypted content
const decryptedContent = fs.readFileSync(decryptedFile, 'utf8');
console.log('✅ Data decrypted and saved to file!');
console.log(`📤 Decrypted content: \n\n"${decryptedContent}"\n\n`);
process.exit(0);
} catch (error) {
console.error("❌ Error occurred:", error);
process.exit(1);
}
}
main();