When did the US break the japaneses code?

When did U.S. break Japanese code. I heard it was before the attack on Pearl Harbor. If this is so why was the attack a surprise.