Java's java.math.BigInteger
class has a modPow
method to perform modular exponentiation. Does that do what you want?
If you want to do it yourself, here is pseudocode for the "square-and-multiply" algorithm, which I will leave to you to translate into Java with appropriate datatypes:
function modPow(base, exp, mod)
x := 1
while exp > 0
if exp % 2 == 1
x := (x * base) % mod
base := (base * base) % mod
exp := exp // 2 # integer division
return x