AES 加密
2021-12-15 本文已影响0人
iLeooooo
使用Swift原生进行AES加密处理:
一、导入:
import CommonCrypto
二、 使用方法:
private func aes() {
let key = "Q4yuqZJb5pYf6RkW"
let iv = "rzglMUHA7nJ3M4HG"
let content = "hello world"
let keyD = [UInt8](key.utf8)
let ivD = [UInt8](iv.utf8)
let aes = aesEncrypt(content, keyD, ivD)
let daes = aesDecrypt(aes!, keyD, ivD)
print("---aes: \(aes) --- daes: \(daes)")
}
三、打印结果:
---aes: Optional("WPNycFZsxvi12chr7SH4Ng==") --- daes: Optional("hello world")
四、加密代码
///AES 加密
public func aesEncrypt(_ text: String, _ key:[UInt8], _ iv:[UInt8]) -> String? {
guard let result = text.aesCBCEncrypt(String(data: Data.init(key), encoding: .utf8)!, iv: String(data: Data.init(iv), encoding: .utf8)!) else { return nil }
let encryptedDataText = result.base64EncodedString(options: NSData.Base64EncodingOptions())
return encryptedDataText
}
///AES 解密
public func aesDecrypt(_ aesText: String, _ key:[UInt8], _ iv:[UInt8]) -> String? {
guard let deResult = aesText.aesCBCDecryptFromBase64(String(data: Data.init(key), encoding: .utf8)!, iv: String(data: Data.init(iv), encoding: .utf8)!) else { return nil }
return deResult
}
extension Data {
// MARK: cbc
fileprivate func aesCBC(_ operation:CCOperation,key:String, iv:String? = nil) -> Data? {
guard [16,24,32].contains(key.lengthOfBytes(using: String.Encoding.utf8)) else {
return nil
}
let input_bytes = self.arrayOfBytes()
let key_bytes = key.bytes
var encrypt_length = Swift.max(input_bytes.count * 2, 16)
var encrypt_bytes = [UInt8](repeating: 0,
count: encrypt_length)
let iv_bytes = (iv != nil) ? iv?.bytes : nil
let status = CCCrypt(UInt32(operation),
UInt32(kCCAlgorithmAES128),
UInt32(kCCOptionPKCS7Padding),
key_bytes,
key.lengthOfBytes(using: String.Encoding.utf8),
iv_bytes,
input_bytes,
input_bytes.count,
&encrypt_bytes,
encrypt_bytes.count,
&encrypt_length)
if status == Int32(kCCSuccess) {
return Data(bytes: UnsafePointer<UInt8>(encrypt_bytes), count: encrypt_length)
}
return nil
}
fileprivate func aesCBCEncrypt(_ key:String,iv:String? = nil) -> Data? {
return aesCBC(UInt32(kCCEncrypt), key: key, iv: iv)
}
fileprivate func aesCBCDecrypt(_ key:String,iv:String? = nil)->Data?{
return aesCBC(UInt32(kCCDecrypt), key: key, iv: iv)
}
}
extension String {
// MARK: cbc
func aesCBCEncrypt(_ key:String,iv:String? = nil) -> Data? {
let data = self.data(using: String.Encoding.utf8)
return data?.aesCBCEncrypt(key, iv: iv)
}
func aesCBCDecryptFromHex(_ key:String,iv:String? = nil) ->String?{
let data = self.dataFromHexadecimalString()
guard let raw_data = data?.aesCBCDecrypt(key, iv: iv) else{
return nil
}
return String(data: raw_data, encoding: String.Encoding.utf8)
}
func aesCBCDecryptFromBase64(_ key:String, iv:String? = nil) ->String? {
let data = Data(base64Encoded: self, options: NSData.Base64DecodingOptions())
guard let raw_data = data?.aesCBCDecrypt(key, iv: iv) else{
return nil
}
return String(data: raw_data, encoding: String.Encoding.utf8)
}
}
extension Int {
subscript(digitIndex: Int) -> Int {
var decimalBase = 1
for _ in 1...digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
extension UInt {
subscript(digitIndex: Int) -> UInt {
var decimalBase:UInt = 1
for _ in 1...digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
extension UInt8 {
subscript(digitIndex: Int) -> UInt8 {
var decimalBase:UInt8 = 1
for _ in 1...digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
extension Data {
func hexadecimalString() -> String {
let string = NSMutableString(capacity: count * 2)
var byte: UInt8 = 0
for i in 0 ..< count {
copyBytes(to: &byte, from: i..<index(after: i))
string.appendFormat("%02x", byte)
}
return string as String
}
var hexString : String {
return self.hexadecimalString()
}
var base64String:String {
return self.base64EncodedString(options: NSData.Base64EncodingOptions())
}
func arrayOfBytes() -> [UInt8] {
let count = self.count / MemoryLayout<UInt8>.size
var bytesArray = [UInt8](repeating: 0, count: count)
(self as NSData).getBytes(&bytesArray, length:count * MemoryLayout<UInt8>.size)
return bytesArray
}
}
extension String {
/// Array of UInt8
var arrayOfBytes:[UInt8] {
let data = self.data(using: String.Encoding.utf8)!
return data.arrayOfBytes()
}
var bytes:UnsafeRawPointer{
let data = self.data(using: String.Encoding.utf8)!
return (data as NSData).bytes
}
func dataFromHexadecimalString() -> Data? {
let trimmedString = self.trimmingCharacters(in: CharacterSet(charactersIn: "<> ")).replacingOccurrences(of: " ", with: "")
guard let regex = try? NSRegularExpression(pattern: "^[0-9a-f]*$", options: NSRegularExpression.Options.caseInsensitive) else{
return nil
}
let trimmedStringLength = trimmedString.lengthOfBytes(using: String.Encoding.utf8)
let found = regex.firstMatch(in: trimmedString, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, trimmedStringLength))
if found == nil || found?.range.location == NSNotFound || trimmedStringLength % 2 != 0 {
return nil
}
var data = Data(capacity: trimmedStringLength / 2)
for index in trimmedString.indices {
let next_index = trimmedString.index(after: index)
let byteString = String(trimmedString[index ..< next_index]) //trimmedString.substring(with: )
let num = UInt8(byteString.withCString { strtoul($0, nil, 16) })
data.append(num)
}
return data
}
}