/*
 * OpenP2M Crypt Break
 *
 * Encrypt and decrypt password for program OpenP2M.
 *
 * 06/05/2006 - frighetti AT cascavel.pm.org
 */

import java.lang.String;
import java.math.BigInteger;

class RSA
{
	private BigInteger n, d, e;

	public RSA()
	{
		n = new BigInteger("849613389756793222155926708916406526722137707856633" + 
				   "710486677120848018911369507691157686832490341300851" + 
				   "2741498700587851315525414979963642608998181269527941");
		d = new BigInteger("169922677951358644431185341783281305344427541571326" +
				   "742097335424169603782273897848542211926500549462803" +
				   "9077923965408489035118957525416966246759228390003017");
		e = new BigInteger("5");
	}

	public final String encrypt(String s) {
		return "_" + encrypt(new BigInteger(s.getBytes())).toString(36);
	}

	private BigInteger encrypt(BigInteger message)
	{
		return message.modPow(e, n);
	}

	public final String decrypt(String s) throws NumberFormatException
	{
		return s.startsWith("_") ?
			new String(decrypt(new BigInteger(s.substring(1), 36)).toByteArray()) :
			new String(decrypt(new BigInteger(s)).toByteArray());
	}

	private BigInteger decrypt(BigInteger message)
	{
		return message.modPow(d, n);
	}
}

public class openp2m_crypt
{
	private String enc = null, dec = null;
	
	public static void main(String[] args)
	{
		if (args.length <= 1)
			usage();

		System.out.println(" " + parseargs(args) + "\n");
	}

	public static void usage()
	{
		System.out.println("Usage: \n" +
				   "      java openp2m_crypt [-c <string for crypt> | -d <password crypted>]\n" +
				   "              -c : criptography password for openp2m\n" +
				   "              -d : decriptography password for openp2m\n");
		System.exit(1);
		
	}

	public static String parseargs(String[] args)
	{
		RSA rsa = new RSA();
		
		for (int i = 0; i < args.length; i++)
		{
			if (args[i].equals("-c") && i+1<args.length)
			{
				return rsa.encrypt(args[++i]);
			}
			else if (args[i].equals("-d") && i+1<args.length)
			{
				return rsa.decrypt(args[++i]);
			}
		}

		return "";
	}
}
