from: github.com/remko/age-plugin-se

This commit is contained in:
2023-03-09 22:52:40 +08:00
parent 57fac2893c
commit 71927745a8
22 changed files with 2720 additions and 2 deletions

78
Sources/Crypto.swift Normal file
View File

@@ -0,0 +1,78 @@
import Foundation
#if !os(Linux) && !os(Windows)
import CryptoKit
import LocalAuthentication
#else
import Crypto
struct SecAccessControl {}
#endif
/// Abstraction for random/unpredictable/system-specific crypto operations
protocol Crypto {
var isSecureEnclaveAvailable: Bool { get }
func newSecureEnclavePrivateKey(dataRepresentation: Data) throws -> SecureEnclavePrivateKey
func newSecureEnclavePrivateKey(accessControl: SecAccessControl) throws -> SecureEnclavePrivateKey
func newEphemeralPrivateKey() -> P256.KeyAgreement.PrivateKey
}
protocol SecureEnclavePrivateKey {
var publicKey: P256.KeyAgreement.PublicKey { get }
var dataRepresentation: Data { get }
func sharedSecretFromKeyAgreement(with publicKeyShare: P256.KeyAgreement.PublicKey) throws
-> SharedSecret
}
#if !os(Linux) && !os(Windows)
class CryptoKitCrypto: Crypto {
let context = LAContext()
var isSecureEnclaveAvailable: Bool {
return SecureEnclave.isAvailable
}
func newSecureEnclavePrivateKey(dataRepresentation: Data) throws -> SecureEnclavePrivateKey {
return try SecureEnclave.P256.KeyAgreement.PrivateKey(
dataRepresentation: dataRepresentation, authenticationContext: context)
}
func newSecureEnclavePrivateKey(accessControl: SecAccessControl) throws
-> SecureEnclavePrivateKey
{
return try SecureEnclave.P256.KeyAgreement.PrivateKey(
accessControl: accessControl, authenticationContext: context)
}
func newEphemeralPrivateKey() -> P256.KeyAgreement.PrivateKey {
return P256.KeyAgreement.PrivateKey()
}
}
extension SecureEnclave.P256.KeyAgreement.PrivateKey: SecureEnclavePrivateKey {
}
#else
class CryptoKitCrypto: Crypto {
var isSecureEnclaveAvailable: Bool {
return false
}
func newSecureEnclavePrivateKey(dataRepresentation: Data) throws -> SecureEnclavePrivateKey {
throw Plugin.Error.seUnsupported
}
func newSecureEnclavePrivateKey(accessControl: SecAccessControl) throws
-> SecureEnclavePrivateKey
{
throw Plugin.Error.seUnsupported
}
func newEphemeralPrivateKey() -> P256.KeyAgreement.PrivateKey {
return P256.KeyAgreement.PrivateKey()
}
}
#endif