Fast ASN.1 parser and serializer with definitions for private keys, public keys, certificates, CRL, OCSP, CMS, PKCS#3, PKCS#7, PKCS#8, PKCS#12, PKCS#5, X.509 and TSP
npx @tessl/cli install tessl/pypi-asn1crypto@1.5.00
# ASN1Crypto
1
2
A fast, pure Python library for parsing and serializing ASN.1 structures with comprehensive support for cryptographic standards. ASN1Crypto provides a pythonic API for handling X.509 certificates, private keys, CRLs, OCSP, CMS, PKCS standards, and other cryptographic ASN.1 structures without requiring any C extensions.
3
4
## Package Information
5
6
- **Package Name**: asn1crypto
7
- **Language**: Python
8
- **Installation**: `pip install asn1crypto`
9
- **License**: MIT
10
- **Python Support**: 2.6, 2.7, 3.2-3.10, PyPy
11
12
## Core Imports
13
14
```python
15
import asn1crypto
16
```
17
18
For specific functionality:
19
20
```python
21
from asn1crypto import core, x509, keys, cms, pem
22
```
23
24
Common pattern for loading encoded data:
25
26
```python
27
from asn1crypto.x509 import Certificate
28
from asn1crypto.keys import PrivateKeyInfo
29
```
30
31
## Basic Usage
32
33
```python
34
import asn1crypto.x509
35
import asn1crypto.keys
36
import asn1crypto.pem
37
38
# Load a PEM-encoded certificate
39
with open('cert.pem', 'rb') as f:
40
cert_pem = f.read()
41
42
# Convert PEM to DER
43
if asn1crypto.pem.detect(cert_pem):
44
_, _, cert_der = asn1crypto.pem.unarmor(cert_pem)
45
else:
46
cert_der = cert_pem
47
48
# Parse the certificate
49
cert = asn1crypto.x509.Certificate.load(cert_der)
50
51
# Access certificate information
52
print(f"Subject: {cert.subject.human_friendly}")
53
print(f"Issuer: {cert.issuer.human_friendly}")
54
print(f"Serial Number: {cert.serial_number}")
55
print(f"Valid From: {cert.not_valid_before}")
56
print(f"Valid Until: {cert.not_valid_after}")
57
58
# Load and parse a private key
59
with open('key.pem', 'rb') as f:
60
key_pem = f.read()
61
62
_, _, key_der = asn1crypto.pem.unarmor(key_pem)
63
private_key = asn1crypto.keys.PrivateKeyInfo.load(key_der)
64
65
print(f"Key Algorithm: {private_key.algorithm}")
66
print(f"Key Size: {private_key.bit_size}")
67
```
68
69
## Architecture
70
71
ASN1Crypto follows a layered architecture built around the ASN.1 standard:
72
73
- **Core Layer**: Universal ASN.1 types (`Sequence`, `OctetString`, `Integer`, etc.) providing the foundation for all ASN.1 structures
74
- **Algorithm Layer**: Cryptographic algorithm identifiers and parameters for various standards (RSA, DSA, ECDSA, etc.)
75
- **Key Layer**: Public and private key structures supporting multiple algorithms and encodings
76
- **Certificate Layer**: X.509 certificate structures with comprehensive extension support
77
- **Message Layer**: High-level cryptographic message formats (CMS, PKCS#7, PKCS#12, TSP)
78
- **Utility Layer**: PEM encoding/decoding, parsing utilities, and cross-platform compatibility helpers
79
80
This design enables efficient parsing through lazy loading, delayed parsing, and preservation of original encoded data for performance optimization, especially with large cryptographic structures.
81
82
## Capabilities
83
84
### Core ASN.1 Types and Parsing
85
86
Universal ASN.1 data types and low-level parsing functionality. Includes primitive types (Boolean, Integer, OctetString), container types (Sequence, Set, Choice), string types, and time types. Provides the foundation for all higher-level cryptographic structures.
87
88
```python { .api }
89
class Asn1Value:
90
@classmethod
91
def load(cls, encoded_data, strict=False): ...
92
def dump(self, force=False): ...
93
@property
94
def native(self): ...
95
96
def load(encoded_data, strict=False): ...
97
```
98
99
[Core ASN.1 Types](./core-types.md)
100
101
### Cryptographic Algorithms
102
103
Algorithm identifier structures and parameters for cryptographic operations. Covers digest algorithms (MD5, SHA family), signature algorithms (RSA, DSA, ECDSA), encryption algorithms, key derivation functions, and MAC algorithms with their associated parameters.
104
105
```python { .api }
106
class AlgorithmIdentifier(core.Sequence): ...
107
class DigestAlgorithm(core.Choice): ...
108
class SignedDigestAlgorithm(core.Choice): ...
109
class EncryptionAlgorithm(core.Choice): ...
110
```
111
112
[Cryptographic Algorithms](./cryptographic-algorithms.md)
113
114
### Keys and X.509 Certificates
115
116
Public and private key structures for RSA, DSA, and elliptic curve algorithms, along with comprehensive X.509 certificate support. Includes certificate parsing, validation helpers, distinguished names, and extensive certificate extension support.
117
118
```python { .api }
119
class Certificate(core.Sequence): ...
120
class PublicKeyInfo(core.Sequence): ...
121
class PrivateKeyInfo(core.Sequence): ...
122
class Name(core.Sequence): ...
123
```
124
125
[Keys and Certificates](./keys-and-certificates.md)
126
127
### Certificate Infrastructure
128
129
Certificate revocation lists (CRLs), Online Certificate Status Protocol (OCSP) structures, and Certificate Signing Requests (CSRs). Essential components for PKI certificate lifecycle management and validation.
130
131
```python { .api }
132
class CertificateList(core.Sequence): ...
133
class OCSPRequest(core.Sequence): ...
134
class OCSPResponse(core.Sequence): ...
135
class CertificationRequest(core.Sequence): ...
136
```
137
138
[Certificate Infrastructure](./certificate-infrastructure.md)
139
140
### Cryptographic Message Formats
141
142
High-level cryptographic message formats including CMS/PKCS#7 (signed data, enveloped data, etc.), PKCS#12 key/certificate storage, Time Stamp Protocol (TSP), and PDF signature structures for comprehensive cryptographic messaging support.
143
144
```python { .api }
145
class ContentInfo(core.Sequence): ...
146
class SignedData(core.Sequence): ...
147
class EnvelopedData(core.Sequence): ...
148
class Pfx(core.Sequence): ...
149
class TimeStampReq(core.Sequence): ...
150
```
151
152
[Message Formats](./message-formats.md)
153
154
### Utilities and Helpers
155
156
PEM encoding/decoding, low-level parsing utilities, cross-platform compatibility helpers, and version information. Includes functions for integer/byte conversion, network address handling, and timezone support.
157
158
```python { .api }
159
def detect(byte_string): ...
160
def armor(type_name, der_bytes, headers=None): ...
161
def unarmor(pem_bytes, multiple=False): ...
162
def parse(contents, strict=False): ...
163
```
164
165
[Utilities](./utilities.md)
166
167
## Common Patterns
168
169
### Loading and Parsing Data
170
171
All ASN.1 structures follow a consistent loading pattern:
172
173
```python
174
from asn1crypto.x509 import Certificate
175
176
# Load from DER-encoded bytes
177
cert = Certificate.load(der_bytes)
178
179
# Access parsed data via .native property
180
cert_data = cert.native
181
182
# Access original encoded data via .dump()
183
original_der = cert.dump()
184
```
185
186
### PEM Handling
187
188
Standard pattern for handling PEM-encoded data:
189
190
```python
191
from asn1crypto import pem
192
193
# Detect PEM format
194
if pem.detect(data):
195
type_name, headers, der_bytes = pem.unarmor(data)
196
else:
197
der_bytes = data
198
199
# Convert DER back to PEM
200
pem_bytes = pem.armor('CERTIFICATE', der_bytes)
201
```
202
203
### Error Handling
204
205
The library uses specific exception types for different error conditions:
206
207
- `ValueError`: Invalid ASN.1 structure or encoding
208
- `TypeError`: Incorrect parameter types
209
- `OSError`: File I/O related errors (when applicable)
210
211
## Type Definitions
212
213
```python { .api }
214
class Asn1Value:
215
"""Base class for all ASN.1 values"""
216
def __init__(self, value=None, default=None): ...
217
@classmethod
218
def load(cls, encoded_data, strict=False): ...
219
def copy(self): ...
220
def retag(self, tagging, tag=None): ...
221
def untag(self): ...
222
def debug(self, nest_level=1): ...
223
def dump(self, force=False): ...
224
def cast(self, other_class): ...
225
@property
226
def native(self): ...
227
@property
228
def parsed(self): ...
229
```