<!--
{
  "documentType" : "article",
  "framework" : "Security",
  "identifier" : "/documentation/Security/storing-a-der-encoded-x-509-certificate",
  "metadataVersion" : "0.1.0",
  "role" : "article",
  "title" : "Storing a DER-Encoded X.509 Certificate"
}
-->

# Storing a DER-Encoded X.509 Certificate

Import and export a certificate from a file.

## Discussion

Certificates are not secret and you often want to share them to disseminate a public key, but [`SecCertificate`](/documentation/Security/SecCertificate) is an opaque type that you can’t distribute directly. Instead, you create a Distinguished Encoding Rules (DER) encoded data representation of the certificate using the [`SecCertificateCopyData(_:)`](/documentation/Security/SecCertificateCopyData(_:)) function:

```objc
SecCertificateRef certificate = <# a certificate #>;
NSData* certData = (NSData*)CFBridgingRelease( // ARC takes ownership
                       SecCertificateCopyData(certificate)
                    );
```

You might send this data object over a network connection or store it in a `.cer` file:

```objc
[certData writeToURL:<# a URL #> atomically:YES];
```

When you receive such a data object, you use the [`SecCertificateCreateWithData(_:_:)`](/documentation/Security/SecCertificateCreateWithData(_:_:)) function to reverse the process:

```objc
SecCertificateRef certificate =
    SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certData);
		 
if (certificate)  { CFRelease(certificate); } // After you are done with it
```

By leaving the first argument empty, you rely on the default allocator to allocate memory for the certificate. Note that in Objective-C, you call <doc://com.apple.documentation/documentation/CoreFoundation/CFRelease> to free the certificate’s memory when you are done with it. In Swift, the system manages the object’s memory automatically.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)