Bug fixes the encryption code

Fixes MOBILE-1301, MOBILE-1380, MOBILE-1381, MOBILE-1383 along with
other improvements and fixes to the encryption code.