Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 

53 righe
1.9 KiB

  1. //
  2. // File.swift
  3. //
  4. //
  5. // Created by Michiel Carman on 4/2/24.
  6. //
  7. import Foundation
  8. import Vapor
  9. import Crypto
  10. enum CryptoError: Error{
  11. case badRequest
  12. }
  13. struct CustomCrypto{
  14. public static func DecryptString(input: String) throws -> String{
  15. let apikey = Environment.get("API_KEY") ?? "rv0ywT7Ygwh01jP1dQWBP39ogjq5ladO+EoNUGcBVq0="
  16. print(apikey)
  17. let base64Key = apikey // Replace with your actual key
  18. guard let keyData = Data(base64Encoded: base64Key) else {
  19. fatalError("Invalid Base64 key data")
  20. }
  21. let data = Data(base64Encoded: input)
  22. let encryptionKey = SymmetricKey(data: keyData)
  23. let sealedBox = try! AES.GCM.SealedBox(combined: data!)
  24. let decryptedData = try! AES.GCM.open(sealedBox, using: encryptionKey)
  25. guard let decryptedString = String(data: decryptedData, encoding: .utf8) else{
  26. throw CryptoError.badRequest
  27. }
  28. return decryptedString
  29. }
  30. public static func EncryptString(input: String) throws -> String{
  31. let apikey = Environment.get("API_KEY") ?? "rv0ywT7Ygwh01jP1dQWBP39ogjq5ladO+EoNUGcBVq0="
  32. print(apikey)
  33. guard let keyData = Data(base64Encoded: apikey) else{
  34. fatalError("Invalid Base64 key data")
  35. }
  36. let encryptionKey = SymmetricKey(data: keyData)
  37. guard let datatoEncrypt = input.data(using: .utf8) else{ fatalError("Invalid Data")}
  38. do{
  39. let sealedBox = try AES.GCM.seal(datatoEncrypt, using: encryptionKey)
  40. guard let combined = sealedBox.combined else{ fatalError("Can't combine")}
  41. let base64EncodedString = combined.base64EncodedString()
  42. let urlEncodedString = base64EncodedString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
  43. return urlEncodedString!
  44. }
  45. }
  46. }