最近接触的这个项目由于以前服务器上用的是DES/CBC/PKCS5Padding加密方式,为了让在iOS上的加密结果与服务器端保持一致,我做了很多尝试,现在分享给大家。PS:现在不推荐用DES了,只是服务器端不能随便改,别的项目平台有依赖。
首先是在Swift中,建一个bridge-Header文件用来调用OC的方法,这一步还是蛮简单的。
贴上我的实现代码:
代码语言:javascript复制class CrypTools: NSObject {
internal func cryptoOperation() -> String {
// Validation checks.
let jm = "fjdkasljfkls"
let jmData = jm.data(using: String.Encoding.utf8)!
let key = "nu{0014}u{001E}(2<FP" //这里是java端对应的key byte[]的字符串表现形式 btye[] key = {10, 20, 30, 40, 50, 60 ,70, 80}
var t:String = ""
// Prepare data parameters
let keyData: Data! = key.data(using: String.Encoding.utf8, allowLossyConversion: false)!
let keyBytes = keyData.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> UnsafePointer<UInt8> in
return bytes
}
//let keyBytes = keyData.bytes.bindMemory(to: Void.self, capacity: keyData.count)
let dataLength = Int(jmData.count)
let dataBytes = jmData.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> UnsafePointer<UInt8> in
return bytes
}
var bufferData = Data(count: Int(dataLength) 8)
let bufferPointer = bufferData.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) -> UnsafeMutablePointer<UInt8> in
return bytes
}
let bufferLength = size_t(bufferData.count)
let ivStr = "u{000B}u{0016}!,7BMU" //这里是java端对应的iv变量字符串
let iv = ivStr.data(using: String.Encoding.utf8)!
let ivBuffer: UnsafePointer<UInt8>? = iv.withUnsafeBytes({ (bytes: UnsafePointer<UInt8>) -> UnsafePointer<UInt8> in
return bytes
})
var bytesDecrypted = Int(0)
// Perform operation
let cryptStatus = CCCrypt(
0, // Operation 这里代表DES加密而非解密
1, // Algorithm 这里代表DES算法(其他数字可以是别的算法,如AES),研究一下OC的自带的方法就行了
1, // Options 这里代表PKCS7Padding
keyBytes, // key data
8, // key length
ivBuffer, // IV buffer
dataBytes, // input data
dataLength, // input length
bufferPointer, // output buffer
bufferLength, // output buffer length
&bytesDecrypted) // output bytes decrypted real length
if Int32(cryptStatus) == Int32(kCCSuccess) {
bufferData.count = bytesDecrypted // Adjust buffer size to real bytes
print(bufferData)
let a = bufferData.withUnsafeBytes{
[UInt8](UnsafeBufferPointer(start: $0, count: bufferData.count))
}
print(a)
t = bufferData.base64EncodedString()
}
return t
}
}
可以看到cryptStatus下对应的几个参数我都做了注释,其中option那一栏1对应PKCS7Padding,实测这和服务器端的PKCS7Padding填充没有任何区别,之前没有得出一致的加密结果时我一直以为是这个填充参数的问题,但实际上是iv和key的设置问题(这是重点)
在java端iv和key多半以byte[] = {}来表示,我们要做的就是将这个byte[]转换成字符串,最后再将这个字符串放在iOS代码中(字符串可能要用Unicode编码表示)。
其实在Swift下,第三方库CryptoSwift非常好用,大家可以上GitHub上检索研究一下。只不过不支持老旧的DES加密,这里只是针对有DES加密需求的人给出解决方案。