63 lines
2.2 KiB
Swift
63 lines
2.2 KiB
Swift
// Reference:
|
|
// - https://developer.apple.com/documentation/swift/commandline/arguments
|
|
// - https://git.hatter.ink/hatter/card-cli/src/branch/master/swift-lib/src/lib.swift
|
|
|
|
import CryptoKit
|
|
import LocalAuthentication
|
|
|
|
func isSupportSecureEnclave() -> Bool {
|
|
return SecureEnclave.isAvailable
|
|
}
|
|
|
|
func generateSecureEnclaveP256KeyPair(sign: Bool) -> String {
|
|
var error: Unmanaged<CFError>? = nil;
|
|
guard let accessCtrl = SecAccessControlCreateWithFlags(
|
|
nil,
|
|
kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
|
|
[.privateKeyUsage, .biometryCurrentSet],
|
|
&error
|
|
) else {
|
|
return "err:\(error.debugDescription)"
|
|
}
|
|
do {
|
|
if (sign) {
|
|
let privateKeyReference = try SecureEnclave.P256.Signing.PrivateKey.init(
|
|
accessControl: accessCtrl
|
|
);
|
|
let publicKeyBase64 = privateKeyReference.publicKey.x963Representation.base64EncodedString()
|
|
let publicKeyPem = privateKeyReference.publicKey.derRepresentation.base64EncodedString()
|
|
let dataRepresentationBase64 = privateKeyReference.dataRepresentation.base64EncodedString()
|
|
return "ok:\(publicKeyBase64),\(publicKeyPem),\(dataRepresentationBase64)"
|
|
} else {
|
|
let privateKeyReference = try SecureEnclave.P256.KeyAgreement.PrivateKey.init(
|
|
accessControl: accessCtrl
|
|
);
|
|
let publicKeyBase64 = privateKeyReference.publicKey.x963Representation.base64EncodedString()
|
|
let publicKeyPem = privateKeyReference.publicKey.derRepresentation.base64EncodedString()
|
|
let dataRepresentationBase64 = privateKeyReference.dataRepresentation.base64EncodedString()
|
|
return "ok:\(publicKeyBase64),\(publicKeyPem),\(dataRepresentationBase64)"
|
|
}
|
|
} catch {
|
|
return "err:\(error)"
|
|
}
|
|
}
|
|
|
|
if (CommandLine.arguments.count == 1) {
|
|
print("err:requireArguments")
|
|
exit(1)
|
|
}
|
|
|
|
let action = CommandLine.arguments[1];
|
|
|
|
if (action == "checkSecureEnclaveEnabled") {
|
|
print("ok:\(isSupportSecureEnclave())")
|
|
exit(0);
|
|
}
|
|
|
|
if (action == "generateSecureEnclaveP256SingingKeyPair") {
|
|
print(generateSecureEnclaveP256KeyPair(sign: true))
|
|
exit(0);
|
|
}
|
|
|
|
print("err:unknownAction")
|
|
exit(1) |