Changing the engine is not illegal but make sure that when you buy the new engine you get the purchase slip from the engine seller, to make sure that it is not smuggled one or stolen, this slip you will need when you have to get the new engine number entered on the motorcycle registration book, without going through this procedure the papers are defective and can be a problem if someone gets it checked.
Good luck..