SecureMessenger.swift 783 B

1234567891011121314151617181920212223242526272829
  1. // LoopFollow
  2. // SecureMessenger.swift
  3. import CryptoKit
  4. import Foundation
  5. struct SecureMessenger {
  6. private let encryptionKey: SymmetricKey
  7. init?(sharedSecret: String) {
  8. guard let secretData = sharedSecret.data(using: .utf8) else {
  9. return nil
  10. }
  11. let hashed = SHA256.hash(data: secretData)
  12. encryptionKey = SymmetricKey(data: hashed)
  13. }
  14. func encrypt<T: Encodable>(_ object: T) throws -> String {
  15. let dataToEncrypt = try JSONEncoder().encode(object)
  16. let nonce = AES.GCM.Nonce()
  17. let sealedBox = try AES.GCM.seal(dataToEncrypt, using: encryptionKey, nonce: nonce)
  18. let combinedData = Data(nonce) + sealedBox.ciphertext + sealedBox.tag
  19. return combinedData.base64EncodedString()
  20. }
  21. }