space optimized encrypt function