or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-parsing.mdindex.mdpem-objects.mdtwisted-integration.md

twisted-integration.mddocs/

0

# Twisted Integration

1

2

Specialized helpers for the Twisted framework that convert PEM objects into Twisted TLS contexts. These functions handle certificate chains and key matching automatically, providing seamless integration with Twisted's SSL/TLS infrastructure.

3

4

**Note**: This module is only available when both OpenSSL and Twisted are installed. If either dependency is missing, `pem.twisted` will be `None`.

5

6

## Capabilities

7

8

### Certificate Options from PEM Objects

9

10

Creates a Twisted CertificateOptions instance from a collection of already-parsed PEM objects, automatically matching private keys with certificates and setting up certificate chains.

11

12

```python { .api }

13

def certificateOptionsFromPEMs(

14

pemObjects: list[AbstractPEMObject],

15

**kw: object

16

) -> ssl.CertificateOptions:

17

"""

18

Load CertificateOptions from PEM objects collection.

19

20

Args:

21

pemObjects: List of PEM objects (certificates, keys, DH parameters)

22

**kw: Additional keyword arguments passed to CertificateOptions

23

24

Returns:

25

twisted.internet.ssl.CertificateOptions: TLS context factory

26

27

Raises:

28

ValueError: If no certificate matching private key is found,

29

no certificates provided, or multiple keys/DH params found

30

TypeError: If dhParameters passed as keyword argument

31

"""

32

```

33

34

**Usage Example:**

35

36

```python

37

import pem

38

from pem.twisted import certificateOptionsFromPEMs

39

40

# Parse PEM objects from various sources

41

objects = []

42

objects.extend(pem.parse_file("server.crt")) # Server certificate

43

objects.extend(pem.parse_file("server.key")) # Private key

44

objects.extend(pem.parse_file("ca-chain.pem")) # Certificate chain

45

objects.extend(pem.parse_file("dhparams.pem")) # DH parameters

46

47

# Create Twisted TLS context

48

try:

49

ssl_context = certificateOptionsFromPEMs(objects)

50

print("TLS context created successfully")

51

except ValueError as e:

52

print(f"Configuration error: {e}")

53

54

# Use in Twisted server

55

from twisted.internet import reactor

56

from twisted.web import server, resource

57

58

class Simple(resource.Resource):

59

def render_GET(self, request):

60

return b"Hello, secure world!"

61

62

site = server.Site(Simple())

63

reactor.listenSSL(8443, site, ssl_context)

64

```

65

66

### Certificate Options from Files

67

68

Convenience function that reads multiple PEM files and creates a CertificateOptions instance by combining their contents.

69

70

```python { .api }

71

def certificateOptionsFromFiles(

72

*pemFiles: str,

73

**kw: object

74

) -> ssl.CertificateOptions:

75

"""

76

Read files and create CertificateOptions from their PEM contents.

77

78

Args:

79

*pemFiles: All positional arguments used as filenames to read

80

**kw: Additional keyword arguments passed to CertificateOptions

81

82

Returns:

83

twisted.internet.ssl.CertificateOptions: TLS context factory

84

"""

85

```

86

87

**Usage Example:**

88

89

```python

90

from pem.twisted import certificateOptionsFromFiles

91

92

# Simple case - single file with certificate and key

93

ssl_context = certificateOptionsFromFiles("server.pem")

94

95

# Multiple files

96

ssl_context = certificateOptionsFromFiles(

97

"server.crt", # Server certificate

98

"server.key", # Private key

99

"intermediate.crt", # Intermediate certificate

100

"dhparams.pem" # DH parameters

101

)

102

103

# With additional Twisted SSL options

104

ssl_context = certificateOptionsFromFiles(

105

"server.pem",

106

method=ssl.TLSv1_2_METHOD,

107

cipherSuites="ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM"

108

)

109

```

110

111

## Configuration Details

112

113

### Automatic Certificate Matching

114

115

The functions automatically handle certificate chain configuration:

116

117

1. **Key Identification**: Locates exactly one private key from the PEM objects

118

2. **Certificate Matching**: Finds the certificate that matches the private key using public key fingerprints

119

3. **Chain Building**: Uses remaining certificates as intermediate/root certificates in the chain

120

4. **DH Parameters**: Optionally includes Diffie-Hellman parameters if present

121

122

### Error Handling

123

124

Common configuration errors are detected and reported:

125

126

```python

127

import pem

128

from pem.twisted import certificateOptionsFromPEMs

129

130

# Multiple private keys - error

131

objects = [

132

pem.RSAPrivateKey("-----BEGIN RSA PRIVATE KEY-----..."),

133

pem.ECPrivateKey("-----BEGIN EC PRIVATE KEY-----..."),

134

pem.Certificate("-----BEGIN CERTIFICATE-----...")

135

]

136

137

try:

138

ssl_context = certificateOptionsFromPEMs(objects)

139

except ValueError as e:

140

print(e) # "Supplied PEM file(s) contains *more* than one key."

141

142

# No matching certificate - error

143

objects = [

144

pem.RSAPrivateKey("-----BEGIN RSA PRIVATE KEY-----..."),

145

pem.Certificate("-----BEGIN CERTIFICATE-----...") # Different key

146

]

147

148

try:

149

ssl_context = certificateOptionsFromPEMs(objects)

150

except ValueError as e:

151

print(e) # "No certificate matching <key_hash> found."

152

```

153

154

### Advanced Configuration

155

156

```python

157

from pem.twisted import certificateOptionsFromPEMs

158

import pem

159

160

# Load PEM objects

161

objects = pem.parse_file("ssl-bundle.pem")

162

163

# Create context with custom Twisted SSL options

164

ssl_context = certificateOptionsFromPEMs(

165

objects,

166

method=ssl.TLSv1_2_METHOD, # TLS version

167

cipherSuites="HIGH:!aNULL:!eNULL", # Cipher selection

168

enableSessions=True, # Session resumption

169

sessionTickets=True # Session tickets

170

)

171

172

# Use with Twisted endpoint

173

from twisted.internet.endpoints import SSL4ServerEndpoint

174

from twisted.internet import reactor

175

176

endpoint = SSL4ServerEndpoint(reactor, 8443, ssl_context)

177

```

178

179

## Integration Notes

180

181

- **Dependency Management**: Check `pem.twisted is not None` before using

182

- **Certificate Chains**: Intermediate certificates are automatically included in the chain

183

- **DH Parameters**: If multiple DH parameter sets are found, an error is raised

184

- **OpenSSL Integration**: Uses OpenSSL through Twisted's SSL abstraction

185

- **Key Formats**: Supports all key types recognized by the PEM parser