Skip to content

Instantly share code, notes, and snippets.

View cardosoedgar's full-sized avatar

Edgar Cardoso cardosoedgar

View GitHub Profile
let algorithm: SecKeyAlgorithm = .eciesEncryptionStandardX963SHA1AESGCM
func decrypt(string: String) -> String? {
let attributes: [String: Any] = [
kSecClass as String: kSecClassKey,
kSecAttrApplicationTag as String: "com.cardosoedgar.key",
kSecReturnRef as String: true]
var key: CFTypeRef?
let status = SecItemCopyMatching(attributes as CFDictionary, &key)
let algorithm: SecKeyAlgorithm = .eciesEncryptionStandardX963SHA1AESGCM
func encrypt(with key: String, string: String) -> String? {
var error: Unmanaged<CFError>?
let attributes: [String: Any] = [
kSecAttrKeyClass as String: kSecAttrKeyClassPublic,
kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
kSecAttrKeySizeInBits as String: 256]
// if you already have the private key
let publicKey = SecKeyCopyPublicKey(privateKey)
// if you don't have the private key
func getPublicKey() -> SecKey? {
let query: [String: Any] = [
kSecClass as String: kSecClassKey,
kSecAttrApplicationTag as String: "com.cardosoedgar.key",
kSecReturnRef as String: true]
let ellipticCurveHeader = [UInt8]([0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2A, 0x86, 0x48,
0xCE, 0x3D, 0x02, 0x01, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03,
0x01, 0x07, 0x03, 0x42, 0x00])
let begin = "-----BEGIN PUBLIC KEY-----\n"
let end = "\n-----END PUBLIC KEY-----"
func retrivePublicKey() -> String? {
var error: Unmanaged<CFError>?
if let publicKey = getPublicKey(),
let keyRef = SecKeyCopyExternalRepresentation(publicKey, &error) {
func getRawPubKey() ->String? {
var error: Unmanaged<CFError>?
guard let pubkey = getPublicKey(),
let keyData = SecKeyCopyExternalRepresentation(pubkey, &error) else { return nil }
let data = keyData as Data
return data.base64EncodedString()
}
func generateSecureEnclaveKey() -> SecKey? {
let attributes: [String: Any] = [
// key id
kSecAttrApplicationTag as String: "com.cardosoedgar.key",
// key size
kSecAttrKeySizeInBits as String: 256,
// key type
kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
// attribute to specify this key should be stored on Secure Enclave
kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave