借着上一篇,由于我的项目中目前使用的是 AES128/ CBC/PKCS7Padding的形式进行加解密,所以本文也是仅仅实现了这种形式的。RSA、AES、MD5整合github地址。如果想要完整的请移步到SecrecySwift,我的实现也是根据他的这篇来实现的。
目录
1.头文件
2.具体的代码实现
3.外部具体调用
一、 需要导入的头文件
import CommonCrypto
二、 具体的实现代码
1. 添加一个需要的扩展
internal extension Int {
subscript(digitIndex: Int) -> Int {
var decimalBase = 1
for _ in 1...digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
internal extension UInt {
subscript(digitIndex: Int) -> UInt {
var decimalBase:UInt = 1
for _ in 1...digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
internal extension UInt8 {
subscript(digitIndex: Int) -> UInt8 {
var decimalBase:UInt8 = 1
for _ in 1...digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
internal 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
}
}
internal 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
}
}
2. Data的Extension实现加解密
internal 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)
}
}
2. String的Extension实现加解密
internal 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)
}
}
三、 外部使用
AES加密
///AES 加密
open class func zz_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解密
///AES 解密
open class func zz_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
}
网友评论