Exponentiating big numbers for RSA operation I am following the book "Network security private communication in a public world - 2nd edition. Section 6.3.4.1 Exponentiating big numbers.

base = 123, exponent = 54, mod = 678

What I understand is that, first I need to convert 54 into binary, i.e. 110110. Then I should do (base^exponent)%mod only at those exponent where the exponent bits are set. For example:

123^2 = 123 * 123 = 15129 % 678 = 213

123^4 = (123^2)*(123^2) = (213^2) mod 678 = 621

123^16 = (123^4)(123^4)(123^4)*(123^4) = (621*621*621*621) mod 678 = 219

123^32 = (123^16)*(123^16) mod 678 = 501

If I do this, I am not getting the right answer which is (87). Can someone point out my mistake and help me understand the scenario.
The basic algorithm is square and optionally multiply.
start with 1 as your accumulator and then for each bit of exponent from MSB to LSB you square your result and if the bit is set multiply by base and appy modulus after each operation.
For any leading zeros you are just squaring 1 which doesn't do anything, just like we want. Then after the first set bit you get your base. After a 10 for example you get your base squared and so forth.

Edit: following fgrieu's comment I will add a second Right to Left method.
When looking at the exponent in binary we see it is the sum of powers of 2, and the result of the exponentiation is the product of the exponent by these powers. The resulting algorithm is: 


Initialize acc=1, power=base //123 
For each bit b from right to left do:

2.1. If bit is set: acc = acc * power % mod

2.2. power = power * power % mod


result is in acc