i am writing an extension to decrypt my NSMutableData ,
extension NSMutableData {
func decrypt() -> NSData {
let decryptMethod = (User.sharedInstance.data?.encrypt_method)!
let key = User.sharedInstance.defaultKey()
return decrypt(methodNumber:decryptMethod , key:key )
}
func decrypt( methodNumber: Decrypter.DecryptType, key: String) -> NSData {
....
}
}
the decrypt method work is fine when i decrypt NSMutableData , but failed to decrypt Data even i cast it to NSMutableData
func xxx() -> Data {
Var encryptedData:Data = getEncData()
let dataToDecrypt = encryptedData as! NSMutableData
let data = dataToDecrypt.decrypt()
return data as Data
}
the code crash at
let data = dataToDecrypt.decrypt()
and tell me "unrecognized selector", here is the crash log
[OS_dispatch_data decrypt]: unrecognized selector sent to instance 0x157fbf0b0
seems my NSMutableData has been cast to OS_dispatch_data so cause "unrecognized selector" , what should i do to cast my Data to NSMutableData correctly ?
The key is:
encryptedData.withUnsafeBytes {encryptedBytes in ... }.Example from sunsetted documentation section:
AES encryption in CBC mode with a random IV (Swift 3+)
The iv is prefixed to the encrypted data
aesCBC128Encryptwill create a random IV and prefixed to the encrypted code.aesCBC128Decryptwill use the prefixed IV during decryption.Inputs are the data and key are Data objects. If an encoded form such as Base64 if required convert to and/or from in the calling method.
The key should be exactly 128-bits (16-bytes), 192-bits (24-bytes) or 256-bits (32-bytes) in length. If another key size is used an error will be thrown.
PKCS#7 padding is set by default.
This example requires Common Crypto
It is necessary to have a bridging header to the project:
#import <CommonCrypto/CommonCrypto.h>Add the
Security.frameworkto the project.This is example, not production code.
Example usage:
Example Output:
Notes:
One typical problem with CBC mode example code is that it leaves the creation and sharing of the random IV to the user. This example includes generation of the IV, prefixed the encrypted data and uses the prefixed IV during decryption. This frees the casual user from the details that are necessary for CBC mode.
For security the encrypted data also should have authentication, this example code does not provide that in order to be small and allow better interoperability for other platforms.
Also missing is key derivation of the key from a password, it is suggested that PBKDF2 be used is text passwords are used as keying material.
For robust production ready multi-platform encryption code see RNCryptor.
Apple documentation: withUnsafeBytes.