Don't bother trying to write your own if you can find one that already exists and has been tested - IT WILL BE STRONGER.
Try looking at
Bouncy Castle/[
^]. I have not gone too deep but it appears to be compatible between the two environments.
Enjoy.