Java tutorial
//package com.java2s; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.RSAPublicKeySpec; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import android.util.Log; public class Main { private static final String TAG = "MyKeyUtils"; public static byte[] encryptMsg(String msg, RSAPublicKeySpec pubKeySpec) { if (msg != null && pubKeySpec != null && !msg.isEmpty()) { try { Log.w(TAG, "msg is: " + msg + " with length " + msg.length()); KeyFactory fact = KeyFactory.getInstance("RSA"); PublicKey pubKey = fact.generatePublic(pubKeySpec); // TODO encrypt the message and send it // Cipher cipher = Cipher.getInstance("RSA/None/NoPadding"); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); // Cipher cipher = // Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", // "BC"); cipher.init(Cipher.ENCRYPT_MODE, pubKey); Log.d(TAG, "cipher block size is " + cipher.getBlockSize()); byte[] msgByteArray = msg.getBytes(); byte[] cipherData = new byte[cipher.getOutputSize(msgByteArray.length)]; cipherData = cipher.doFinal(msgByteArray); Log.d(TAG, "output size is " + cipher.getOutputSize(msgByteArray.length)); Log.d(TAG, "is the measurement already broken into chunks here? " + (new String(cipherData))); return cipherData; } catch (NoSuchAlgorithmException e) { Log.e(TAG, "RSA algorithm not available", e); } catch (InvalidKeySpecException e) { Log.e(TAG, "", e); } catch (NoSuchPaddingException e) { Log.e(TAG, "", e); } catch (InvalidKeyException e) { Log.e(TAG, "", e); } catch (BadPaddingException e) { Log.e(TAG, "", e); } catch (IllegalBlockSizeException e) { Log.e(TAG, "", e); } catch (Exception e) { Log.e(TAG, "", e); } /* * catch (NoSuchProviderException e) { Log.e(TAG, "", e); } */ } return null; } }