title: How to encrypt and decrypt an object in java?
body: <p>I need to encrypt and decrypt an object in java such that I can know who encrypted it.
  Something like a digital signature on an object.</p>
  <p>Example -</p>
  <pre><code>class Animal{
      public String name;
  
      public Animal(String name){
           this.name = name;
      }
  }
  
  class Client {
      public int id;
      // some more fields
      public void encrypt(Animal a){
          // some implementation
      }
  
      public Client(int id) {
          this.id = id;
      }
  }
  
  class Main{
     public static void main(String[] args) {
         Animal lion = new Animal(&quot;Lion&quot;);
         Client client1 = new Client(1);
         Client client2 = new Client(2);
         SomeClass c1 = client1.encrypt(lion);
         SomeClass c2 = client2.encrypt(lion);
         // let's say I have the keys corresponding to client1 and client2
         // now I want to get back the lion object from c1 and c2.
     }
  }
  </code></pre>
  <p>I want something like a key pair, public and private keys. Read online about using the public key for encryption and the private key for decryption.</p>
  <p>I used the wrong approach of using the public key for encryption and exposing only the private key for decryption which I read online is not recommended.</p>
  <p>I want the client class to encrypt the object and then expose some keys that can decrypt the object this client encrypted.</p>