Rewrite encryption code to improve performance