rsa

public class E {
	public String ALGORITHM = "RSA";
	public String public_key = "publickey";
	public String private_key = "privatekey";

	public Map<String, Object> initKey() throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM);
		kpg.initialize(512);
		KeyPair kp = kpg.generateKeyPair();
		PublicKey publicKey = kp.getPublic();
		PrivateKey privateKey = kp.getPrivate();
		result.put(public_key, publicKey);
		result.put(private_key, privateKey);
		return result;
	}

	public String getPublicKey(Map<String, Object> key) throws Exception {
		String publicKey = "";
		PublicKey pk = (PublicKey) key.get(public_key);
		publicKey = Base64.encode(pk.getEncoded());
		return publicKey;
	}

	public String getPrivateKey(Map<String, Object> key) throws Exception {
		String privateKey = "";
		PrivateKey pk = (PrivateKey) key.get(private_key);
		privateKey = Base64.encode(pk.getEncoded());
		return privateKey;
		// return pk.getEncoded();
	}

	public byte[] enc(byte[] date, String key) throws Exception {
		X509EncodedKeySpec x509 = new X509EncodedKeySpec(Base64.decode(key));
		KeyFactory kf = KeyFactory.getInstance(ALGORITHM);
		Key k = kf.generatePublic(x509);
		Cipher c = Cipher.getInstance(ALGORITHM);
		c.init(c.ENCRYPT_MODE, k);
		return c.doFinal(date);

	}

	public byte[] den(byte[] date, String key) throws Exception {
		PKCS8EncodedKeySpec pek = new PKCS8EncodedKeySpec(Base64.decode(key));
		KeyFactory kf = KeyFactory.getInstance(ALGORITHM);
		Key k = kf.generatePrivate(pek);
		Cipher c = Cipher.getInstance(ALGORITHM);
		c.init(c.DECRYPT_MODE, k);
		return c.doFinal(date);
	}

	public void test() throws Exception {
		Map<String, Object> key = initKey();
		String testContent = "aaa";
		String privateKey = getPrivateKey(key);
		String publicKey = getPublicKey(key);
		System.out.println(new String(privateKey));
		System.out.println(new String(publicKey));
		byte[] input = enc(testContent.getBytes(), publicKey);
		System.out.println(new String(input));
		byte[] output = den(input, privateKey);
		System.out.println(new String(output));
	}

	public static void main(String[] args) {
		E e = new E();
		try {
			e.test();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
}

你可能感兴趣的:(C++,c,C#)