← Back to list

iCredential: Managing and Securing Credentials with Core Data and Encryption

In today’s digital world, managing credentials securely is crucial. The iCredential app, designed with Swift and CoreData, offers a robust…

Aswanth K · 2024-08-27 11:36 · 2 claps · 2.9 min read
#core-data-swift #swiftui #mvvm #cryptokit #local-authentication
Open on Medium ↗
Wiki topics: CRY · Crypto & Web3 📱 · Mobile Development 🔒 · Cybersecurity

iCredential: Managing and Securing Credentials with Core Data and Encryption

In today’s digital world, managing credentials securely is crucial. The iCredential app, designed with Swift and CoreData, offers a robust solution for storing and managing your credentials safely. This article dives into the core features and operations of iCredential, showcasing its capabilities and how it ensures secure handling of your sensitive information.

Key Features of iCredential

  1. Authentication Handling: Automatically triggers authentication when the app becomes active.
  2. Secure Storage: Uses Core Data for storing credentials, ensuring data persistence.
  3. Encryption & Decryption: Encrypts passwords before storing them and decrypts them when needed.
  4. Credential Management: Supports adding, updating, and deleting credentials.

Authentication Handling

iCredential starts with a secure authentication mechanism. The app uses biometric authentication (Face ID or Touch ID) to ensure that only authorized users can access their credentials. The authentication process is triggered whenever the app moves from the background to the foreground, providing an added layer of security.

class AppState: ObservableObject {
    @Published var isAuthenticationTriggered = false
}

@main
struct iCredentialApp: App {
    @StateObject var viewModel = ViewModel()
    @StateObject var appState = AppState()
    @Environment(\.scenePhase) var scenePhase

    var body: some Scene {
        WindowGroup {
            Group {
                switch viewModel.currentView {
                case .lockScreen:
                    LockView()
                case .homeView:
                    ContentView()
                }
            }
            .environmentObject(viewModel)
            .environmentObject(appState)
            .onChange(of: scenePhase) { newPhase in
                handleScenePhaseChange(newPhase)
            }
        }
    }

    private func handleScenePhaseChange(_ newPhase: ScenePhase) {
        switch newPhase {
        case .active:
            if !appState.isAuthenticationTriggered {
                viewModel.currentView = .lockScreen
                triggerAuthentication()
            }
        case .background:
            appState.isAuthenticationTriggered = false
        default:
            break
        }
    }

    private func triggerAuthentication() {
        debugPrint("Triggering authentication...")
        NotificationCenter.default.post(name: NSNotification.Name("TriggerAuthentication"), object: nil)
        appState.isAuthenticationTriggered = true
    }
}

Secure Storage

Credentials are securely stored using CoreData, ensuring that sensitive information is encrypted at rest. The app leverages CoreData’s features for efficient storage and retrieval while maintaining high security standards.

class ViewModel: ObservableObject {
    @Published var savedPasswords: [Cridentials] = []
    var coreDataContainer: NSPersistentContainer

    init() {
        coreDataContainer = NSPersistentContainer(name: "PasswordCridentialContainer")
        coreDataContainer.loadPersistentStores { (description, error) in
            if let error = error as NSError? {
                self.handleError("Error loading Core Data: \(error.localizedDescription)")
            }
        }
        fetchPasswordCridentials()
    }

    func fetchPasswordCridentials() {
        coreDataContainer = NSPersistentContainer(name: "PasswordCridentialContainer")
        coreDataContainer.loadPersistentStores { (description, error) in
            if let error = error as NSError? {
                self.handleError("Error loading Core Data: \(error.localizedDescription)")
            }
        }
        let request = NSFetchRequest<Cridentials>(entityName: "Cridentials")        coreDataContainer.viewContext.perform {
            do {
                let fetchedPasswords = try self.coreDataContainer.viewContext.fetch(request)
                DispatchQueue.main.async {
                    self.savedPasswords = fetchedPasswords
                }
            } catch let error as NSError {
                self.handleError("Error fetching data: \(error.localizedDescription)")
            }
        }
    }
}

Encryption & Decryption

The app employs encryption and decryption mechanisms to protect sensitive data. It uses AES-GCM for encryption, ensuring that stored passwords remain secure even if the data is compromised.

class CryptoHelper {
    static let key = SymmetricKey(size: .bits256)

    static func encrypt(_ string: String) -> String? {
        guard let data = string.data(using: .utf8) else { return nil }
        do {
            let sealedBox = try AES.GCM.seal(data, using: key)
            return sealedBox.combined?.base64EncodedString()
        } catch {
            print("Error encrypting: \(error)")
            return nil
        }
    }

    static func decrypt(_ base64EncodedString: String) -> String? {
        guard let data = Data(base64Encoded: base64EncodedString) else { return nil }
        do {
            let sealedBox = try AES.GCM.SealedBox(combined: data)
            let decryptedData = try AES.GCM.open(sealedBox, using: key)
            return String(data: decryptedData, encoding: .utf8)
        } catch {
            print("Error decrypting: \(error)")
            return nil
        }
    }
}

Credential Management

iCredential provides comprehensive features for managing credentials. Users can add, edit, move, save, fetch, and delete credentials with ease. The user interface is designed to be intuitive and user-friendly, enabling seamless interaction with the credential data.

func addNewCridential(accountName: String, userName: String, password: String) {
    coreDataContainer.performBackgroundTask { [weak self] context in
        guard let self = self else { return }
        let newPasswordCridential = Cridentials(context: context)
        newPasswordCridential.accountName = accountName
        newPasswordCridential.userName = userName
        if let encryptedPassword = CryptoHelper.encrypt(password) {
            newPasswordCridential.password = encryptedPassword
        } else {
            self.handleError("Error encrypting password")
            return
        }
        do {
            try context.save()
            DispatchQueue.main.async {
                self.fetchPasswordCridentials()
            }
        } catch let error as NSError {
            self.handleError("Error saving cridential: \(error.localizedDescription)")
        }
    }
}

Conclusion

The iCredential app offers a comprehensive solution for managing credentials with a strong emphasis on security and user experience. With its secure authentication, encrypted storage, and robust credential management features, iCredential ensures that your sensitive information is protected at all times. Whether you’re looking to securely store personal passwords or manage business credentials, iCredential provides a reliable and secure solution.

Explore the source code and contribute to the project on GitHub.


메타데이터
post_id
dd9dad53cf2f
slug
icredential-managing-and-securing-credentials-with-core-data-and-encryption-dd9dad53cf2f
url
https://medium.com/@aswanthas124/icredential-managing-and-securing-credentials-with-core-data-and-encryption-dd9dad53cf2f
canonical_url
https://medium.com/@aswanthas124/icredential-managing-and-securing-credentials-with-core-data-and-encryption-dd9dad53cf2f
author_url
https://medium.com/@aswanthas124
status
ok
fetched_at
2026-07-22 05:07:27