There is a simple algorithm for b ^ e (mod m):
function powerMod(b, e, m)
x := 1
while e > 0
if e % 2 == 1
x := (b * x) % m
b := (b * b) % m
e := e // 2 # integer division
return x
You should not calculate b ^ e and then perform the modulo operation, as the intermediate number will be huge. I'll leave it to you to translate to your preferred language with datatypes suitable for storing the large numbers you need. I discuss this algorithm at my blog.