2

I have public key sent to me. I want to use it in encryption. But key is in .pub format. So its just a plain text, not a certificate. How do I convert this public key to an object like PublicKey key = ....; In file I see: -----BEGIN PUBLIC KEY----- MIIBIjANB......... HwIDAQAB -----END PUBLIC KEY----- Later I want to use this code:

enter code here
Private static byte[] encrypt(String text, PublicKey key) {
        byte[] cipherText = null;
        try {
          final Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");
          cipher.init(Cipher.ENCRYPT_MODE, key);
          cipherText = cipher.doFinal(text.getBytes());
        } catch (Exception e) {
          e.printStackTrace();
        }
        return cipherText;
      }

Please someone tell me how to use .pub file to have a public key in program code.

babboon
  • 683
  • 3
  • 20
  • 45
  • Have you tried something like the answer provided here? http://stackoverflow.com/questions/11691462/verifying-a-signature-with-a-public-key – Peter Svensson Nov 16 '13 at 21:31
  • In your example it is reading from .pem In my case I have only plain public key in .pub, not an a key pair or certificate. – babboon Nov 17 '13 at 07:52
  • Solution: Security.addProvider(new BouncyCastleProvider()); FileReader fileReader = new FileReader(path); PEMReader r = new PEMReader(fileReader); return (PublicKey) r.readObject(); – babboon Nov 17 '13 at 10:43

0 Answers0