Friday 13 February 2009

RSA explicit with encryption

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);

KeyPair keyPair = keyGen.generateKeyPair();

RSAPublicKey pubKey = (RSAPublicKey)keyPair.getPublic();
RSAPrivateKey priKey = (RSAPrivateKey)keyPair.getPrivate();

System.out.println("PUB KEY: " + pubKey.getPublicExponent() + ", " + pubKey.getModulus());
System.out.println("PRI KEY: " + priKey.getPrivateExponent());

Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);

String plainMsg = "Hello world!";

byte[] cryptedData = cipher.doFinal(plainMsg.getBytes());

cipher.init(Cipher.DECRYPT_MODE, priKey);

String clearMsg = new String(cipher.doFinal(cryptedData));

System.out.println(clearMsg);

No comments:

Blog Archive