iOS-study
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AES.swift 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //
  2. // AES.swift
  3. // iOSFirst
  4. //
  5. // Created by 孙宇峰 on 2023/3/1.
  6. //
  7. import Foundation
  8. import CryptoSwift
  9. struct AESEncryptor {
  10. public static func aes_encrypt(_ str:String, aes_key:String) -> String{
  11. var encryptedStr = ""
  12. do {
  13. // AES encrypt
  14. let encrypted = try AES(key: Array(aes_key.utf8), blockMode: ECB(), padding: .pkcs7).encrypt(str.bytes);
  15. // let data = Data(base64Encoded: Data(encrypted), options: .ignoreUnknownCharacters)
  16. //加密结果从data转成string 转换失败 返回""
  17. encryptedStr = encrypted.toBase64()
  18. } catch {
  19. print(error.localizedDescription)
  20. }
  21. return encryptedStr
  22. }
  23. /// AES-128-CBC 加密
  24. /// - Parameter str: 加密字符串
  25. public static func encode(to str: String) -> String? {
  26. let key = "XINGHUOLIAOYUAN7"
  27. guard let aes = try? AES(key: Array(key.utf8) ,blockMode: ECB(), padding:.pkcs5) else {
  28. return nil
  29. }
  30. guard let encrypted = try? aes.encrypt(str.bytes) else {
  31. return nil
  32. }
  33. //
  34. let encryptedBase64 = encrypted.toBase64()
  35. return encryptedBase64
  36. }
  37. /// AES-128-CBC 解密
  38. /// - Parameter str: 加密字符串
  39. public static func decode(to str: String) -> String? {
  40. let key = "XINGHUOLIAOYUAN7"
  41. guard let aes = try? AES(key: Array(key.utf8), blockMode: ECB(), padding: .pkcs5) else {
  42. return nil
  43. }
  44. guard let decrypted = try? str.decryptBase64ToString(cipher: aes) else {
  45. return nil
  46. }
  47. return decrypted
  48. }
  49. }