Мне удалось устранить проблему. Проблема заключалась в том, что ключ был только 16 байтов и должен быть 24, поэтому я думаю, что он был заполнен случайным образом, но ожидалось, что первые 8 байтов будут возвращены в конце16 для того, чтобы сделать 24?
, как это работает:
func fillKey(keyLength: size_t, key: Data) -> Data {
let missingBytes = keyLength - key.count
if missingBytes > 0 {
let keyBytes = (key as NSData).bytes
var bytes = [UInt8](repeating: UInt8(0), count: keyLength)
memccpy(&bytes[0], keyBytes.advanced(by: 0), Int32(key.count), key.count)
memccpy(&bytes[key.count], keyBytes.advanced(by: 0), Int32(missingBytes), missingBytes)
return Data(bytes: bytes)
} else {
return key
}
}
func my3DESEncrypt(encryptData: String, key: String, iv: String) -> Data? {
var myKeyData : Data = key.hexadecimal()!
let myIvData : Data = iv.hexadecimal()!
var myRawData : Data = encryptData.hexadecimal()!
let buffer_size : size_t = myRawData.count + kCCBlockSize3DES
var buffer = [UInt8](repeating: UInt8(0), count: buffer_size)
var num_bytes_encrypted : size_t = 0
let operation: CCOperation = UInt32(kCCEncrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithm3DES)
let options: CCOptions = 0
let keyLength = size_t(kCCKeySize3DES)
myKeyData = self.fillKey(keyLength: keyLength, key: myKeyData)
let Crypto_status: CCCryptorStatus = CCCrypt(operation, algoritm, options, (myKeyData as NSData).bytes, keyLength, (myIvData as NSData).bytes, (myRawData as NSData).bytes, myRawData.count, &buffer, buffer_size, &num_bytes_encrypted)
if UInt32(Crypto_status) == UInt32(kCCSuccess) {
let data = Data(bytes: buffer, count: num_bytes_encrypted)
return data
} else{
return nil
}
}
func my3DESDecrypt(decryptData : Data, key: String, iv: String) -> Data? {
let mydata_len : Int = decryptData.count
var myKeyData : Data = key.hexadecimal()!
let myIvData : Data = iv.hexadecimal()!
let buffer_size : size_t = mydata_len+kCCBlockSize3DES
var buffer = [UInt8](repeating: UInt8(0), count: buffer_size)
var num_bytes_encrypted : size_t = 0
let operation: CCOperation = UInt32(kCCDecrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithm3DES)
let options: CCOptions = UInt32(kCCOptionPKCS7Padding)
let keyLength = size_t(kCCKeySize3DES)
myKeyData = self.fillKey(keyLength: keyLength, key: myKeyData)
let decrypt_status : CCCryptorStatus = CCCrypt(operation, algoritm, options, (myKeyData as NSData).bytes, keyLength, (myIvData as NSData).bytes, (decryptData as NSData).bytes, mydata_len, &buffer, buffer_size, &num_bytes_encrypted)
if UInt32(decrypt_status) == UInt32(kCCSuccess){
let data = Data(bytes: buffer, count: num_bytes_encrypted)
return data
} else{
return nil
}
}