CryptoSwift - Converting a UInt8 array to String resolved as nil

(Xcode 8, Swift 3)

Using the CryptoSwift library, I want to encrypt the string and save it in coredata, for some reason the result of cipherstring is zero, despite the fact that the encrypted text has 128 values:

let aes = try AES(key: pw, iv: nil, blockMode: .CBC, padding: PKCS7())
let ciphertext = try aes.encrypt(token.utf8.map({$0}))
let cipherstring = String(bytes:ciphertext, encoding: String.Encoding.utf8) // always nil

I also tried using data: line overloading, converting a byte array to a data object. This also leads to zero.

EDITING / SOLUTION (to Robapierre's answer)

// encode/convert to string
let aes = try AES(key: pw, iv: nil, blockMode: .CBC, padding: PKCS7())
let ciphertext = try aes.encrypt(token.utf8.map({$0}))
let cipherstring = Data(bytes: ciphertext).base64EncodedString()
// decode
let aes = try AES(key: pw, iv: nil, blockMode: .CBC, padding: PKCS7())
let cipherdata = Data(base64Encoded: cipherstring)
let ciphertext = try aes.decrypt(cipherdata!.bytes)
let token = String(bytes:ciphertext, encoding:String.Encoding.utf8)
+4
source share
1 answer

AES . , UTF-8. , - . - Base-64. . Data.base64EncodedString() . Data(base64Encoded:), Data String.

+5

Source: https://habr.com/ru/post/1661482/


All Articles