This code try very hard to ensure that the secret key provided to it is eradicated after it is properly saved.
This is because we try to reduce the attack vector for keeping the encryption key in memory.
However, there are at least two different ways that this code is failing in what it is trying to do. Can you find them?
For that matter, how much sense does it make to even attempt what it is doing?