Hi,
I am trying to extract the data from the P8 file to use it generate JWT.
I understand that it is possible using dumpasn1 and extracting the OCTET STRING section. This is great, and is definitely possible.
I was wondering if it was possible to do it on macOS using Apple's APIs (example SecItemImport), would make it simpler if it was possible all in the mac app.
I tried the following but it didn't work:
Error:
I got the OSStatus as -25257
Questions:
- Is there a way to do this using SecItemImport or any other Apple APIs as I am using it in a command line mac app ?
- Are the parameters to SecItemImport are incorrect ?
- Am down the wrong path? , any direction to the correct API would help.
What I tried with SecItemImport:
- Data extracted from the file
- Decoding the data from the file
- Some input formats
Many thanks.
import Foundation
import Security
func f1() {
do {
let fileURL = URL(fileURLWithPath: "some valid path");
let data = try Data(contentsOf: fileURL)
guard let string = String(data: data, encoding: .utf8) else {
print("Failed to convert data to string")
return
}
let b64Text = string
.replacingOccurrences(of: "-----END PRIVATE KEY-----", with: "")
.replacingOccurrences(of: "-----BEGIN PRIVATE KEY-----", with: "")
.replacingOccurrences(of: "\n", with: "")
guard let b64Data = b64Text.data(using: .utf8),
let decodedData = Data(base64Encoded: b64Data) else {
print("Was not b64 data")
return
}
print(string)
var outArray : CFArray?
let filename : CFString? = nil
var inputFormat = SecExternalFormat.formatUnknown
var itemType = SecExternalItemType.itemTypePrivateKey
let flags = SecItemImportExportFlags()
//I tried data, b64Data, decodedData all seems to return an error
let status = SecItemImport(decodedData as CFData,
filename,
&inputFormat,
&itemType,
flags,
nil,
nil,
&outArray)
//status = -25257
print("status = \(status)")
for element in (outArray as [AnyObject]?) ?? [] {
print("element = \(element)")
}
}
catch {
print("Error: \(error)")
}
}
f1()