0

I'm trying to implement my own version of authorization for HTTP requests. Now I'm facing a problem that I don't know how to resolve.

As shown in code below, I'm encrypting String message using RSA algorithm. But the problem is that as a result I'm getting object of class SealedObject. I need to have the possibility to use this encrypted string as header - for now using REST client like Postman. So, my question is: How can I parse SealedObject to String? Or what should I do to encrypt the message to String? Is this even possible?

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = kpg.generateKeyPair();

String message = "Secret message";

Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());

SealedObject encryptedMessage = new SealedObject(message, cipher);

Thank you in advance :)

1
  • use the serialization interface Commented Nov 19, 2018 at 21:11

1 Answer 1

1

the first thing that comes to mind is:

SealedObject is a Serializable Object which means you can convert it to bytes and then transform it to String using Base64: something like this:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
  out = new ObjectOutputStream(bos);   
  out.writeObject(sealedObject);
  out.flush();
  byte[] yourBytes = bos.toByteArray();
  String base64StringHeader = Base64.encodeBase64String(yourBytes);
} finally {
  try {
    bos.close();
  } catch (IOException ex) {
    // ignore close exception
  }
}

and then when you receive your request do something like this:

byte[] backToBytes = Base64.decodeBase64(base64StringHeader);
ByteArrayInputStream bis = new ByteArrayInputStream(backToBytes);
ObjectInput in = null;
try {
  in = new ObjectInputStream(bis);
  SealedObject = in.readObject(); 
  ...
} finally {
  try {
    if (in != null) {
      in.close();
    }
  } catch (IOException ex) {
    // ignore close exception
  }

}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.