Reputation: 41
I have a string of data that I want to encrypt in AES 128 and the encrypted data should be in binary. I have tried using CryptoSwith to do so. But the issue I am getting is that the encryption code that I found from an online help converts in into HexString. I tried looking for the conversion to binary but couldn't find a working solution. The code I am using is below :
func encrypt(data: String) -> String? {
if let aes = try? AES(key: "0101010101010101", iv: "0000000000000000"),
let encrypted = try? aes.encrypt(Array(data.utf8)) {
return encrypted.toHexString()
}
return
}
Would really appreciate the help.
Upvotes: 1
Views: 795
Reputation: 11435
Assuming you meant something like this?:
let binary = encrypted.map {
let binary = String($0, radix: 2)
let padding = String(repeating: "0", count: 8 - binary.count)
return padding + binary
}.joined()
Which prints the whole Byte array as a sequence of zeros (0) and ones (1):
100101010101011010101010101010100011010101010101
Your method would then look like:
func encrypt(data: String) -> String? {
if let aes = try? AES(key: "0101010101010101", iv: "0000000000000000"),
let encrypted = try? aes.encrypt(Array(data.utf8)) {
let binary = encrypted.map {
let binary = String($0, radix: 2)
let padding = String(repeating: "0", count: 8 - binary.count)
return padding + binary
}.joined()
return binary
}
return nil
}
Upvotes: 1