NSString* message = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.";
NSData* rawData = [message dataUsingEncoding:NSASCIIStringEncoding];
id signIdentity = nil;
id encryptCertificate = nil;
// Load signing identity
NSDictionary* signQuery = @{
(id)kSecClass:(id)kSecClassIdentity,
(id)kSecMatchTrustedOnly:@YES,
(id)kSecMatchIssuers:mySigningCAIssuer,
(id)kSecReturnRef:@YES
};
CFTypeRef item = nil;
OSStatus status = SecItemCopyMatching((CFDictionaryRef)signQuery, &item);
if (status == errSecSuccess) {
signIdentity = CFBridgingRelease(item);
}
// Load encryption certificate
NSDictionary* encryptQuery = @{
(id)kSecClass:(id)kSecClassCertificate,
(id)kSecMatchTrustedOnly:@YES,
(id)kSecMatchIssuers:myEncryptCAIssuer,
(id)kSecReturnRef:@YES
};
status = SecItemCopyMatching((CFDictionaryRef)encryptQuery, &item);
if (status == errSecSuccess) {
encryptCertificate = CFBridgingRelease(item);
}
// Export encrypted data
CFDataRef dataRef = nil;
status = CMSEncodeContent((__bridge SecIdentityRef)signIdentity, nil, nil, false, kCMSAttrSmimeEncryptionKeyPrefs, rawData.bytes, rawData.length, &dataRef);
NSData* encodedData = CFBridgingRelease(dataRef);
[encodedData writeToFile:@"/Users/Shared/test-encrypted.p7m" atomically:true];
// Import encrypted data
CMSDecoderRef cmsDecoderRef = nil;
status = CMSDecoderCreate(&cmsDecoderRef);
status = CMSDecoderUpdateMessage(cmsDecoderRef, encodedData.bytes, encodedData.length);
if (status == errSecSuccess) {
status = CMSDecoderFinalizeMessage(cmsDecoderRef); // Exception is sent here when signing + encrypting
}
// Get content
CFDataRef content = nil;
status = CMSDecoderCopyContent(cmsDecoderRef, &content); // nil is received when encrypting only - OK when signing only
CFRelease(cmsDecoderRef);