12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- //
- // AES.swift
- // iOSFirst
- //
- // Created by 孙宇峰 on 2023/3/1.
- //
-
- import Foundation
- import CryptoSwift
-
- struct AESEncryptor {
-
-
- public static func aes_encrypt(_ str:String, aes_key:String) -> String{
-
- var encryptedStr = ""
- do {
- // AES encrypt
- let encrypted = try AES(key: Array(aes_key.utf8), blockMode: ECB(), padding: .pkcs7).encrypt(str.bytes);
- // let data = Data(base64Encoded: Data(encrypted), options: .ignoreUnknownCharacters)
- //加密结果从data转成string 转换失败 返回""
- encryptedStr = encrypted.toBase64()
- } catch {
- print(error.localizedDescription)
- }
- return encryptedStr
- }
-
-
- /// AES-128-CBC 加密
- /// - Parameter str: 加密字符串
- public static func encode(to str: String) -> String? {
- let key = "XINGHUOLIAOYUAN7"
- guard let aes = try? AES(key: Array(key.utf8) ,blockMode: ECB(), padding:.pkcs5) else {
- return nil
- }
-
- guard let encrypted = try? aes.encrypt(str.bytes) else {
- return nil
- }
- //
- let encryptedBase64 = encrypted.toBase64()
- return encryptedBase64
- }
-
-
- /// AES-128-CBC 解密
- /// - Parameter str: 加密字符串
- public static func decode(to str: String) -> String? {
- let key = "XINGHUOLIAOYUAN7"
- guard let aes = try? AES(key: Array(key.utf8), blockMode: ECB(), padding: .pkcs5) else {
- return nil
- }
- guard let decrypted = try? str.decryptBase64ToString(cipher: aes) else {
- return nil
- }
- return decrypted
- }
-
-
-
-
- }
|