PlatformCrypto.swift 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import Foundation
  2. import CryptoKit
  3. import CommonCrypto
  4. import Security
  5. enum PlatformCrypto {
  6. enum CryptoError: Error { case invalidEnvelope, invalidCiphertext, invalidText, randomFailed, cryptFailed }
  7. private static let key = Data(SHA256.hash(data: Data("ios-platform-api-v2".utf8)))
  8. static func encrypt(_ text: String) throws -> String {
  9. var iv = Data(count: kCCBlockSizeAES128)
  10. let status = iv.withUnsafeMutableBytes { SecRandomCopyBytes(kSecRandomDefault, $0.count, $0.baseAddress!) }
  11. guard status == errSecSuccess else { throw CryptoError.randomFailed }
  12. return try encrypt(text, iv: iv)
  13. }
  14. // Injectable IV for interoperability tests. Production callers use encrypt(_:).
  15. static func encrypt(_ text: String, iv: Data) throws -> String {
  16. guard iv.count == kCCBlockSizeAES128 else { throw CryptoError.invalidEnvelope }
  17. let ciphertext = try crypt(Data(text.utf8), iv: iv, operation: CCOperation(kCCEncrypt))
  18. return "v2:" + (iv + ciphertext).base64EncodedString()
  19. .replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")
  20. }
  21. static func decrypt(_ envelope: String, maximumEnvelopeBytes: Int = 350_000) throws -> String {
  22. guard envelope.hasPrefix("v2:"), envelope.utf8.count <= maximumEnvelopeBytes else { throw CryptoError.invalidEnvelope }
  23. let encoded = String(envelope.dropFirst(3))
  24. guard !encoded.isEmpty, encoded.utf8.allSatisfy({ (65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0) || $0 == 45 || $0 == 95 }), encoded.count % 4 != 1 else {
  25. throw CryptoError.invalidEnvelope
  26. }
  27. var base64 = encoded.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
  28. base64 += String(repeating: "=", count: (4 - base64.count % 4) % 4)
  29. guard let bytes = Data(base64Encoded: base64), bytes.count >= 32, (bytes.count - 16) % 16 == 0 else {
  30. throw CryptoError.invalidCiphertext
  31. }
  32. let plaintext = try crypt(Data(bytes.dropFirst(16)), iv: Data(bytes.prefix(16)), operation: CCOperation(kCCDecrypt))
  33. guard let result = String(data: plaintext, encoding: .utf8) else { throw CryptoError.invalidText }
  34. return result
  35. }
  36. private static func crypt(_ data: Data, iv: Data, operation: CCOperation) throws -> Data {
  37. var output = Data(count: data.count + kCCBlockSizeAES128)
  38. var outputLength = 0
  39. let capacity = output.count
  40. let status = output.withUnsafeMutableBytes { outputBytes in
  41. data.withUnsafeBytes { inputBytes in
  42. key.withUnsafeBytes { keyBytes in
  43. iv.withUnsafeBytes { ivBytes in
  44. CCCrypt(operation, CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionPKCS7Padding),
  45. keyBytes.baseAddress, key.count, ivBytes.baseAddress,
  46. inputBytes.baseAddress, data.count, outputBytes.baseAddress, capacity, &outputLength)
  47. }
  48. }
  49. }
  50. }
  51. guard status == kCCSuccess else { throw CryptoError.cryptFailed }
  52. return Data(output.prefix(outputLength))
  53. }
  54. }