Reading Files
To make file access easier, the security transforms API provides read transforms that return the contents of a file in a CFData
object. By chaining this transform with other transforms, you can effectively use a readable file stream as input to any other transform.
If you do not already have a read stream, create or obtain a
CFURLRef
object for the source file.For example, to read the file
encrypt2_key
in the current working directory, you could write code like the following:CFURLRef url = CFURLCreateFromFileSystemRepresentation (
kCFAllocatorDefault,
"encrypt2_key",
12,
false);
If you do not already have a read stream, create a
CFReadStreamRef
object from thatCFURLRef
.For example:
CFReadStreamRef cfrs = CFReadStreamCreateWithFile(
kCFAllocatorDefault,
url);
Call
SecTransformCreateReadTransformWithReadStream
to create the read transform.For example:
SecTransformRef readTransform = SecTransformCreateReadTransformWithReadStream(cfrs);
If your encryption key is a series of raw bytes, you can now get the contents of a file as a CFData
object by calling SecTransformExecute
or SecTransformExecuteAsync
on the transform object as follows:
CFDataRef cfdatacryptokey = SecTransformExecute(readTransform, &error); |
If your encryption key is in Base64 encoding, you may find it useful to group this transform with a Base64 decoder object. For example:
/* Create the Base64 encoder object. */ |
SecTransformRef decoder = SecDecodeTransformCreate(kSecBase64Encoding, &error); |
if (error) { CFShow(error); exit(-1); } |
/* Create the group transform object. */ |
SecGroupTransformRef group = SecTransformCreateGroupTransform(); |
/* Connect the output of the read transform |
to the input of the decoder using the |
group transform object. */ |
SecTransformConnectTransforms(readTransform, kSecTransformOutputAttributeName, |
decoder, kSecTransformInputAttributeName, group, &error); |
/* Perform the group transform. */ |
CFDataRef cfdatacryptokey = SecTransformExecute(group, &error); |
Copyright © 2018 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2018-06-04