or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-operations.mdcertificate-operations.mdcontact-management.mdimport-export.mdindex.mdissuer-management.mdlisting-operations.mdoperation-management.mdpolicy-management.mdrecovery-operations.md

import-export.mddocs/

0

# Import and Export

1

2

Certificate import and export operations for working with external certificates, backing up certificates, and restoring from backups. Supports PKCS#12 and PEM formats with comprehensive metadata preservation.

3

4

## Capabilities

5

6

### Certificate Import

7

8

Import existing certificates from various formats into Azure Key Vault. Supports certificates with private keys in PKCS#12 format and certificate-only imports in PEM format.

9

10

```python { .api }

11

def import_certificate(

12

certificate_name: str,

13

certificate_bytes: bytes,

14

*,

15

enabled: Optional[bool] = None,

16

tags: Optional[Dict[str, str]] = None,

17

password: Optional[str] = None,

18

policy: Optional[CertificatePolicy] = None,

19

preserve_order: Optional[bool] = None,

20

**kwargs: Any

21

) -> KeyVaultCertificate:

22

"""

23

Import a certificate into the vault.

24

25

Parameters:

26

- certificate_name: Name for the imported certificate

27

- certificate_bytes: Certificate data in PKCS#12 or PEM format

28

- enabled: Whether the certificate should be enabled

29

- tags: Metadata tags for the certificate

30

- password: Password for PKCS#12 certificates (if encrypted)

31

- policy: Certificate policy (uses default if not specified)

32

- preserve_order: Whether to preserve certificate chain order

33

34

Returns:

35

KeyVaultCertificate: The imported certificate

36

37

Raises:

38

ValueError: If certificate data is invalid

39

HttpResponseError: For service-side errors

40

"""

41

```

42

43

Usage examples:

44

45

```python

46

# Import PKCS#12 certificate with private key

47

with open("certificate.p12", "rb") as cert_file:

48

cert_bytes = cert_file.read()

49

50

imported_cert = client.import_certificate(

51

certificate_name="imported-cert",

52

certificate_bytes=cert_bytes,

53

password="certificate-password", # Password for encrypted PKCS#12

54

enabled=True,

55

tags={"source": "external", "type": "ssl"}

56

)

57

print(f"Imported certificate: {imported_cert.name}")

58

59

# Import PEM certificate without private key

60

with open("certificate.pem", "rb") as cert_file:

61

pem_bytes = cert_file.read()

62

63

imported_cert = client.import_certificate(

64

certificate_name="pem-cert",

65

certificate_bytes=pem_bytes,

66

policy=CertificatePolicy.get_default()

67

)

68

69

# Import with custom policy

70

from azure.keyvault.certificates import CertificatePolicy, KeyType

71

72

custom_policy = CertificatePolicy.get_default()

73

custom_policy.key_type = KeyType.rsa

74

custom_policy.key_size = 4096

75

76

imported_cert = client.import_certificate(

77

certificate_name="secure-cert",

78

certificate_bytes=cert_bytes,

79

policy=custom_policy,

80

tags={"security_level": "high"}

81

)

82

```

83

84

### Certificate Backup

85

86

Create a backup of a certificate that includes all versions and can be restored to any Azure Key Vault. The backup is encrypted and can only be restored within the same geographic region (Azure geolocation).

87

88

```python { .api }

89

def backup_certificate(certificate_name: str, **kwargs: Any) -> bytes:

90

"""

91

Backup a certificate from the vault.

92

93

Parameters:

94

- certificate_name: Name of the certificate to backup

95

96

Returns:

97

bytes: Encrypted backup data containing all certificate versions

98

99

Raises:

100

ResourceNotFoundError: If the certificate doesn't exist

101

HttpResponseError: For service-side errors

102

"""

103

```

104

105

Usage examples:

106

107

```python

108

# Create backup

109

backup_data = client.backup_certificate("my-cert")

110

print(f"Backup size: {len(backup_data)} bytes")

111

112

# Save backup to file

113

with open("certificate_backup.blob", "wb") as backup_file:

114

backup_file.write(backup_data)

115

116

# Multiple certificate backup

117

certificates_to_backup = ["cert1", "cert2", "cert3"]

118

backups = {}

119

120

for cert_name in certificates_to_backup:

121

try:

122

backup_data = client.backup_certificate(cert_name)

123

backups[cert_name] = backup_data

124

print(f"Backed up {cert_name}: {len(backup_data)} bytes")

125

except Exception as e:

126

print(f"Failed to backup {cert_name}: {e}")

127

128

# Save all backups

129

import json

130

backup_manifest = {

131

"timestamp": datetime.now().isoformat(),

132

"certificates": list(backups.keys()),

133

"count": len(backups)

134

}

135

136

with open("backup_manifest.json", "w") as manifest_file:

137

json.dump(backup_manifest, manifest_file, indent=2)

138

```

139

140

### Certificate Restore

141

142

Restore a certificate from a backup. The certificate name from the backup will be used, and all versions will be restored.

143

144

```python { .api }

145

def restore_certificate_backup(backup: bytes, **kwargs: Any) -> KeyVaultCertificate:

146

"""

147

Restore a certificate from backup data.

148

149

Parameters:

150

- backup: Encrypted backup data from backup_certificate

151

152

Returns:

153

KeyVaultCertificate: The restored certificate (latest version)

154

155

Raises:

156

ValueError: If backup data is invalid or corrupted

157

ConflictError: If a certificate with the same name already exists

158

HttpResponseError: For service-side errors

159

"""

160

```

161

162

Usage examples:

163

164

```python

165

# Restore from backup data

166

with open("certificate_backup.blob", "rb") as backup_file:

167

backup_data = backup_file.read()

168

169

restored_cert = client.restore_certificate_backup(backup_data)

170

print(f"Restored certificate: {restored_cert.name}")

171

print(f"Version: {restored_cert.properties.version}")

172

173

# Restore multiple certificates

174

import os

175

import json

176

177

# Load backup manifest

178

with open("backup_manifest.json", "r") as manifest_file:

179

manifest = json.load(manifest_file)

180

181

restored_certificates = []

182

183

for cert_name in manifest["certificates"]:

184

backup_file_path = f"{cert_name}_backup.blob"

185

if os.path.exists(backup_file_path):

186

try:

187

with open(backup_file_path, "rb") as backup_file:

188

backup_data = backup_file.read()

189

190

restored_cert = client.restore_certificate_backup(backup_data)

191

restored_certificates.append(restored_cert.name)

192

print(f"Restored: {restored_cert.name}")

193

except Exception as e:

194

print(f"Failed to restore {cert_name}: {e}")

195

196

print(f"Successfully restored {len(restored_certificates)} certificates")

197

```

198

199

### Certificate Format Handling

200

201

Working with different certificate formats and extracting information.

202

203

```python

204

# Extract certificate information

205

certificate = client.get_certificate("my-cert")

206

207

# Get the certificate in DER format (binary)

208

der_cert = certificate.cer

209

print(f"DER certificate size: {len(der_cert)} bytes")

210

211

# Convert to PEM format for display/export

212

import base64

213

214

pem_cert = (

215

"-----BEGIN CERTIFICATE-----\n" +

216

base64.b64encode(der_cert).decode('ascii') +

217

"\n-----END CERTIFICATE-----"

218

)

219

print("PEM format:")

220

print(pem_cert)

221

222

# Extract certificate details using cryptography library (if available)

223

try:

224

from cryptography import x509

225

from cryptography.hazmat.backends import default_backend

226

227

cert_obj = x509.load_der_x509_certificate(der_cert, default_backend())

228

229

print(f"Subject: {cert_obj.subject.rfc4514_string()}")

230

print(f"Issuer: {cert_obj.issuer.rfc4514_string()}")

231

print(f"Serial: {cert_obj.serial_number}")

232

print(f"Not valid before: {cert_obj.not_valid_before}")

233

print(f"Not valid after: {cert_obj.not_valid_after}")

234

235

except ImportError:

236

print("cryptography library not available for certificate parsing")

237

```

238

239

### Bulk Import Operations

240

241

Efficiently import multiple certificates from a directory or collection.

242

243

```python

244

import os

245

from pathlib import Path

246

247

def import_certificates_from_directory(client, directory_path, file_extension=".p12"):

248

"""Import all certificates from a directory."""

249

imported_count = 0

250

failed_imports = []

251

252

directory = Path(directory_path)

253

254

for cert_file in directory.glob(f"*{file_extension}"):

255

try:

256

with open(cert_file, "rb") as f:

257

cert_bytes = f.read()

258

259

# Use filename (without extension) as certificate name

260

cert_name = cert_file.stem

261

262

imported_cert = client.import_certificate(

263

certificate_name=cert_name,

264

certificate_bytes=cert_bytes,

265

enabled=True,

266

tags={

267

"source": "bulk_import",

268

"original_file": cert_file.name

269

}

270

)

271

272

print(f"Imported: {imported_cert.name}")

273

imported_count += 1

274

275

except Exception as e:

276

failed_imports.append((cert_file.name, str(e)))

277

print(f"Failed to import {cert_file.name}: {e}")

278

279

print(f"\nImport summary:")

280

print(f"Successfully imported: {imported_count}")

281

print(f"Failed imports: {len(failed_imports)}")

282

283

return imported_count, failed_imports

284

285

# Usage

286

imported, failed = import_certificates_from_directory(

287

client,

288

"/path/to/certificates",

289

".p12"

290

)

291

```

292

293

## Error Handling

294

295

Common error scenarios when importing and exporting certificates:

296

297

```python

298

from azure.core.exceptions import ResourceNotFoundError, ConflictError, HttpResponseError

299

300

# Import error handling

301

try:

302

with open("certificate.p12", "rb") as f:

303

cert_bytes = f.read()

304

305

imported_cert = client.import_certificate(

306

certificate_name="my-cert",

307

certificate_bytes=cert_bytes

308

)

309

except ValueError as e:

310

print(f"Invalid certificate data: {e}")

311

except ConflictError:

312

print("Certificate with this name already exists")

313

except HttpResponseError as e:

314

print(f"Service error: {e.status_code} - {e.message}")

315

except FileNotFoundError:

316

print("Certificate file not found")

317

318

# Backup error handling

319

try:

320

backup_data = client.backup_certificate("non-existent-cert")

321

except ResourceNotFoundError:

322

print("Certificate not found for backup")

323

except HttpResponseError as e:

324

if e.status_code == 403:

325

print("Insufficient permissions for backup operation")

326

else:

327

print(f"Backup failed: {e.message}")

328

329

# Restore error handling

330

try:

331

with open("corrupted_backup.blob", "rb") as f:

332

backup_data = f.read()

333

334

restored_cert = client.restore_certificate_backup(backup_data)

335

except ValueError:

336

print("Invalid or corrupted backup data")

337

except ConflictError:

338

print("Cannot restore - certificate with same name exists")

339

except HttpResponseError as e:

340

if e.status_code == 400:

341

print("Backup data is invalid or from different region")

342

else:

343

print(f"Restore failed: {e.message}")

344

```

345

346

## Best Practices

347

348

### Backup and Restore Strategy

349

350

```python

351

import datetime

352

import json

353

from pathlib import Path

354

355

class CertificateBackupManager:

356

"""Manages certificate backups with metadata and validation."""

357

358

def __init__(self, client, backup_directory="./cert_backups"):

359

self.client = client

360

self.backup_dir = Path(backup_directory)

361

self.backup_dir.mkdir(exist_ok=True)

362

363

def backup_all_certificates(self):

364

"""Backup all certificates in the vault."""

365

timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")

366

backup_session_dir = self.backup_dir / f"backup_{timestamp}"

367

backup_session_dir.mkdir()

368

369

successful_backups = []

370

failed_backups = []

371

372

# Get all certificates

373

for cert_props in self.client.list_properties_of_certificates():

374

cert_name = cert_props.name

375

376

try:

377

# Create backup

378

backup_data = self.client.backup_certificate(cert_name)

379

380

# Save backup file

381

backup_file = backup_session_dir / f"{cert_name}.backup"

382

with open(backup_file, "wb") as f:

383

f.write(backup_data)

384

385

successful_backups.append({

386

"name": cert_name,

387

"file": str(backup_file),

388

"size": len(backup_data),

389

"expires_on": cert_props.expires_on.isoformat() if cert_props.expires_on else None

390

})

391

392

except Exception as e:

393

failed_backups.append({

394

"name": cert_name,

395

"error": str(e)

396

})

397

398

# Create manifest

399

manifest = {

400

"backup_timestamp": timestamp,

401

"vault_url": str(self.client.vault_url),

402

"successful_backups": successful_backups,

403

"failed_backups": failed_backups,

404

"total_certificates": len(successful_backups) + len(failed_backups)

405

}

406

407

manifest_file = backup_session_dir / "manifest.json"

408

with open(manifest_file, "w") as f:

409

json.dump(manifest, f, indent=2)

410

411

print(f"Backup completed: {len(successful_backups)} successful, {len(failed_backups)} failed")

412

return manifest

413

414

# Usage

415

backup_manager = CertificateBackupManager(client)

416

backup_manifest = backup_manager.backup_all_certificates()

417

```