Code, JavaEE

Encryption / Decryption using Java Core

</pre>
public String encrypt(String plainText, PublicKey publicKey) {
 Cipher cipher = null;
 byte[] enc = null;
 String encStr = null;
 try {
 cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
 cipher.init(Cipher.ENCRYPT_MODE, publicKey);
 enc = new Base64().encode(cipher.doFinal(plainText.getBytes(Constants.DefaultEncoding)));
 } catch (NoSuchAlgorithmException ex) {
 LOG.error("NoSuchAlgorithmException, encrypt", ex);
 } catch (NoSuchPaddingException ex) {
 LOG.error("NoSuchPaddingException, encrypt", ex);
 } catch (InvalidKeyException ex) {
 LOG.error("InvalidKeyException, encrypt", ex);
 } catch (UnsupportedEncodingException ex) {
 LOG.error("UnsupportedEncodingException, encrypt", ex);
 } catch (IllegalBlockSizeException ex) {
 LOG.error("IllegalBlockSizeException, encrypt", ex);
 } catch (BadPaddingException ex) {
 LOG.error("BadPaddingException , encrypt", ex);
 }

if (enc != null) {
 encStr = new String(enc);
 }

return encStr;
 }

 public String decrypt(String cipherText, PrivateKey privateKey) {
 Cipher cipher = null;
 byte[] dec = null;
 String decStr = null;

try {
 cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
 cipher.init(Cipher.DECRYPT_MODE, privateKey);
 dec = cipher.doFinal(new Base64().decode(cipherText.getBytes(Constants.DefaultEncoding)));
 } catch (UnsupportedEncodingException ex) {
 LOG.error("UnsupportedEncodingException, decrypt", ex);
 } catch (NoSuchAlgorithmException ex) {
 LOG.error("NoSuchAlgorithmException, decrypt", ex);
 } catch (NoSuchPaddingException ex) {
 LOG.error("NoSuchPaddingException, decrypt", ex);
 } catch (InvalidKeyException ex) {
 LOG.error("InvalidKeyException, decrypt", ex);
 } catch (IllegalBlockSizeException ex) {
 LOG.error("IllegalBlockSizeException, decrypt", ex);
 } catch (BadPaddingException ex) {
 LOG.error("BadPaddingException , decrypt", ex);
 }

if (dec != null) {
 decStr = new String(dec);
 }

return decStr;
 }
<pre>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s