How do I use CryptoKit for hashing and encryption?

Discover how to use CryptoKit for hashing and encryption in Swift with practical examples. Learn to securely hash data and encrypt sensitive information using Apple's powerful framework.
CryptoKit, Swift, Hashing, Encryption, Secure Data, Apple Framework

    import CryptoKit

    // Example of hashing using SHA256
    let inputData = "Hello, World!"
    let inputDataBytes = Data(inputData.utf8)
    let hashed = SHA256.hash(data: inputDataBytes)

    // Converting the hashed data to its hexadecimal representation
    let hashedString = hashed.map { String(format: "%02hhx", $0) }.joined()
    print("SHA256 Hash: \(hashedString)")

    // Example of encryption using Symmetric Key
    let key = SymmetricKey(size: .bits256)
    let plaintext = "This is a secret message."
    let plaintextData = Data(plaintext.utf8)

    // Encrypting the plaintext
    let sealedBox = try AES.GCM.seal(plaintextData, using: key)

    // Decrypting the ciphertext
    let decryptedData = try AES.GCM.open(sealedBox, using: key)
    let decryptedMessage = String(data: decryptedData, encoding: .utf8)

    print("Decrypted message: \(decryptedMessage ?? "Failed to decrypt")")
    

CryptoKit Swift Hashing Encryption Secure Data Apple Framework