Last active
October 12, 2015 00:55
-
-
Save armadsen/eb78563ef0d94d2f6267 to your computer and use it in GitHub Desktop.
Demonstrates the use of CSSM for decrypting using a public key, which is not supported by the Security Transforms API on Mac OS X.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NSData *ORSDecryptDataWithPublicKey(NSData *dataToDecrypt, SecKeyRef publicKey) | |
{ | |
const CSSM_KEY *cssmPubKey = NULL; | |
SecKeyGetCSSMKey(publicKey, &cssmPubKey); | |
CSSM_CSP_HANDLE handle; | |
SecKeyGetCSPHandle(publicKey, &handle); | |
CSSM_DATA inputData = { | |
.Data = (uint8_t *)[dataToDecrypt bytes], | |
.Length = [dataToDecrypt length], | |
}; | |
CSSM_DATA outputData = { | |
.Data = NULL, | |
.Length = 0, | |
}; | |
CSSM_ACCESS_CREDENTIALS credentials; | |
memset(&credentials, 0, sizeof(CSSM_ACCESS_CREDENTIALS)); | |
CSSM_CC_HANDLE contextHandle; | |
CSSM_RETURN result = CSSM_CSP_CreateAsymmetricContext(handle, cssmPubKey->KeyHeader.AlgorithmId, &credentials, cssmPubKey, CSSM_PADDING_PKCS1, &contextHandle); | |
if (result) { NSLog(@"Error creating CSSM context: %i", result); return NO; } | |
CSSM_CONTEXT_ATTRIBUTE modeAttribute = { | |
.AttributeType = CSSM_ATTRIBUTE_MODE, | |
.AttributeLength = sizeof(UInt32), | |
.Attribute.Uint32 = CSSM_ALGMODE_PUBLIC_KEY, | |
}; | |
result = CSSM_UpdateContextAttributes(contextHandle, 1, &modeAttribute); | |
if (result) { NSLog(@"Error setting CSSM context mode: %i", result); return NO; } | |
CSSM_SIZE numBytesDecrypted = 0; | |
CSSM_DATA remData = { | |
.Data = NULL, | |
.Length = 0, | |
}; | |
result = CSSM_DecryptData(contextHandle, &inputData, 1, &outputData, 1, &numBytesDecrypted, &remData); | |
if (result) { NSLog(@"Error decrypting data using CSSM: %i", result); return NO; } | |
CSSM_DeleteContext(contextHandle); | |
outputData.Length = numBytesDecrypted; | |
return [NSData dataWithBytesNoCopy:outputData.Data length:outputData.Length freeWhenDone:YES]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment