title: java encrypt and decrypt using key pair?
body: <p>does anyone know how to encrypt and decrypt a string object using RSA public and private keys?</p>
  
  <p>i have created private and public keys below using KeyPair generator but i now want to use the public key to encrypt data, and a private key to decrypt it.</p>
  
  <pre><code>public class Keys {
  
      private static KeyPairGenerator generator;
  
      private static KeyPair keyPair;
  
      private static PrivateKey mPrivateKey;
  
      private static PublicKey mPublicKey;
  
      private static SecureRandom secureRandom;
  
      private static final String SHA1PRNG = "SHA1PRNG";
  
      public static final String RSA = "RSA";
  
      private Keys() throws NoSuchAlgorithmException {
          generator = KeyPairGenerator.getInstance("RSA");
      }
  
      /**
       * Generate private and public key pairs
       * 
       * @throws NoSuchAlgorithmException
       */
      private static void generateKeyPair() throws NoSuchAlgorithmException {
          // create SecureRandom object used to generate key pairs
  
          secureRandom = SecureRandom.getInstance(SHA1PRNG);
  
          // initialise generator
          generator = KeyPairGenerator.getInstance(RSA);
          generator.initialize(1024, secureRandom);
  
          // generate keypair using generator
          keyPair = generator.generateKeyPair();
  
          // asssign private and public keys
          setPrivateKey(keyPair.getPrivate());
          setPublicKey(keyPair.getPublic());
  
      }
  
      /**
       * Get private key from key generated
       * @return
       * @throws NoSuchAlgorithmException
       */
      public static PrivateKey getPrivateKey() throws NoSuchAlgorithmException {
  
          if (mPrivateKey == null) {
              generateKeyPair();
          }
          return mPrivateKey;
      }
  
      private static void setPrivateKey(PrivateKey privateKey) {
          mPrivateKey = privateKey;
      }
  
      /**
       * Get public key from key pair generated
       * 
       * @return
       * @throws NoSuchAlgorithmException
       */
      public PublicKey getPublicKey() throws NoSuchAlgorithmException {
          if (mPublicKey == null) {
              generateKeyPair();
          }
          return mPublicKey;
      }
  
      private static void setPublicKey(PublicKey publicKey) {
          mPublicKey = publicKey;
      }
  </code></pre>
  
  <p>is this possible or does the encryption have to share and use the same key?</p>
  
  <p>The main aim is this.</p>
  
  <p>i will have two clients that can send and receive encrypted data to eachother.</p>
  
  <p>For Client A to recieve encrypted data:</p>
  
  <p>Client B requests for Client A's Public key.
  Client B encrypts string and sends it to Client A.
  Client A recieves this encrypted String and then uses its own private key to decrypt it.</p>
  
  <p>Vice versa if Client B wishes to recieve encrypted data.</p>