I'm using the following code to encrypt data using AES algorithm with key as system serial and a string as iv
This is the write
function
func writeStringToFile()
{
do{
let path = URL(fileURLWithPath: "/Users/Shared")
let folderurl = path.appendingPathComponent("MYPATH")
let systemserial=self.getsystemserial();
let paddedserial = systemserial.padding(toLength: 16, withPad: "X", startingAt: 0)
let aes1 = try AES(key: paddedserial, iv: "mystrongpasscode") // aes128
let sdata = try aes1.encrypt(Array(mystring.utf8))
let writedata1 = Data(bytes: sdata)
try FileManager.default.createDirectory(at: folderurl, withIntermediateDirectories: true)
let filepath = folderurl.appendingPathComponent("MYFILE")
try writedata1.write(to: filepath)
}
catch
{
}
}
This is the read function
func readStringfromFile() -> String
{
do{
let path = URL(fileURLWithPath: "/Users/Shared")
let folderurl = path.appendingPathComponent("MYPATH")
let filepath = folderurl.appendingPathComponent("MYFILE")
let text1 = try Data(contentsOf: filepath)
let systemserial=self.getsystemserial();
let paddedserial = systemserial.padding(toLength: 16, withPad: "X", startingAt: 0)
let aes1 = try AES(key: paddedserial, iv: "mystrongpasscode") // aes128
let decrypted = try aes1.decrypt(Array(text1))
return String(bytes: decrypted, encoding: .utf8)!
}
catch
{
return " "
}
}
The function i use to get the system serial is the following
func getsystemserial() -> String {
guard case let platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice") ), platformExpert > 0, let serialNumber = IORegistryEntryCreateCFProperty(platformExpert, kIOPlatformSerialNumberKey as CFString, kCFAllocatorDefault, 0).takeUnretainedValue() as? String else { return "" }; IOObjectRelease(platformExpert);
return serialNumber
}
But the read and written strings are not matching. What am i doing wrong ?