Playing an encrypted mp3 in iOS

2019-08-26 15:00发布

问题:

I have an aes encrypted mp3 file that I need to play in iOS; I can't decrypt the file to disk for security reasons, and I likely can't decrypt it to memory because of memory constraints.

Is there a way to play an encrypted file directly, or to stream it to the player without loading it all into memory? I am really at a loss with this one, I don't even know where to begin... I'm using AVAudioPlayer to play files, but I'm guessing it's not flexible enough to do what I want.

回答1:

I don't know how AVAudioPlayer works, but the only way to solve this problem is to provide some sort of abstraction that the player can access. If the player can only access "file" objects, you are out of luck and must use another player. If the player can access an input stream of some sort (which I suspect it can), you can create a stream from the file (call it a "file stream"), and create a decryption stream from the file stream. You will have to understand AES encryption only in so far as you will need to use code that already exists (like crypto++) to create a decryption stream.

in psuedodcode, it would look something like this:

filestream fs = new filestream( path )
decryptionstream ds = decryptionstream( fs, decryptionkeydata )
AVAudioPlayer.open( ds );
AVAudioPlayer.play()

Internally, AVAudioPlayer will read chunks of data from the decryptionstream, which will pull data from the file stream, which will pull data from the file. Th data will be decrypted in the decryptionstream, one chunk at a time.



回答2:

For audio or image file encrption and decryption use RNCryptor algorithm --> https://github.com/RNCryptor/RNCryptor

Encryption:

let fileData = try NSData(contentsOf: fileURL, options: NSData.ReadingOptions.mappedIfSafe)
let encryptData = RNCryptor.encrypt(data: fileData as Data, withPassword: "password")
try encryptData.write(to: fileURL, options: Data.WritingOptions.completeFileProtection)

Decryption: (For playing audio you have to decrypt first audio then play)

let fileData = try NSData(contentsOfFile: filePath, options:NSData.ReadingOptions.mappedIfSafe)
decryptData = RNCryptor.decrypt(data: fileData as Data, withPassword: password)
try decryptData.write(to: URL.init(fileURLWithPath: filePath), options: Data.WritingOptions.completeFileProtection)


回答3:

First you need to understand how does AES encryption work.

You cannot play an encrypted file without decrypting it, because an encrypted file is just some garbage data. Until it is decrypted you cannot read it or play it.

I'm not sure how are you encrypting your file and how you will get the keys for decryption but your step one is to get the symmetric key for the decryption process.