navneet83 / Cross-platform-AES-encryption

Basic cross platform AES encryption
Apache License 2.0
320 stars 152 forks source link

iOS how to use generateRandomIV? #37

Open red010182 opened 8 years ago

red010182 commented 8 years ago

In iOS, generateRandomIV() returns NSData, not NSString. So I tried some ways to convert the NSData to NSString but fail.

I'm using Swift 2.x with Objc Bridge Headers to include CryptLib.m/h and NSData+Base64.m/h. Here's the code:

Method 1

let data = aes256encrypter.generateRandomIV(16)
let iv = data.base64EncodedStringWithOptions(.EncodingEndLineWithCarriageReturn)
print(iv)

It prints out something like Zo8sin4RHrj77WWc5LV3xw==, which is not the length I want

Method 2

let data = aes256encrypter.generateRandomIV(16)
let iv = String(data: data, encoding: NSUTF8StringEncoding) 

It becomes nil now.

So how to get a random IV in iOS? It's really easy to generate random IV in java using the same API. Why isn't generateRandomIV() in iOS returns a NSString instead of NSData?