1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
@objc public func decrypt(source: String) -> String {
guard source.count > 0 && self.privateSecKey != nil else {
return ""
}
//base64 decode
let data: Data = (NSData(base64Encoded: (source as String), options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)! as Data)
let blockLen = SecKeyGetBlockSize(self.privateSecKey!)
let outBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: blockLen)
defer {
outBuf.deallocate()
}
var outBufLen: Int = blockLen
// if #available(iOS 10.0, *) {
// var error: Unmanaged<CFError>?
// resData = SecKeyCreateDecryptedData(self.privateSecKey!, SecKeyAlgorithm.rsaEncryptionPKCS1, data as CFData, &error)
//
// print("res = \(String(describing: error?.takeUnretainedValue().localizedDescription))")
// } else {
// // Fallback on earlier versions
// //let status = SecKeyEncrypt(seckey, SecPadding.PKCS1, chunkData, chunkData.count, outBuf, &encryptedDataLength)
//
// }
var index = 0
let totalLen = data.count
let resData = NSMutableData()
while index < totalLen {
var curDataLen = totalLen - index;
if curDataLen > blockLen {
curDataLen = blockLen;
}
let curData: Data = data.subdata(in: index ..< index + curDataLen)
var status:OSStatus = noErr
curData.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) in
status = SecKeyDecrypt(self.privateSecKey!, SecPadding.PKCS1, bytes, curData.count, outBuf, &outBufLen)
}
if status == noErr {
resData.append(outBuf, length: outBufLen)
}else{
print("decrypt status = \(status)")
}
index += curDataLen
}
return String(data: (resData as Data), encoding: String.Encoding.utf8)!
}
|