【问题标题】:Java - Encoding message to StringJava - 将消息编码为字符串
【发布时间】:2018-11-19 20:55:33
【问题描述】:

我正在尝试为 HTTP 请求实施我自己的授权版本。现在我面临一个我不知道如何解决的问题。

如下面的代码所示,我正在使用 RSA 算法加密字符串消息。但问题是,结果我得到了SealedObject 类的对象。我需要有可能使用这个加密的字符串作为标题 - 现在使用像 Postman 这样的 REST 客户端。所以,我的问题是:如何将SealedObject 解析为String?或者我应该怎么做才能将消息加密到String?这甚至可能吗?

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);

提前谢谢你:)

【问题讨论】:

  • 使用序列化接口

标签: java rest encryption httprequest rsa


【解决方案1】:

首先想到的是:

SealedObject 是一个可序列化的对象,这意味着您可以将其转换为字节,然后使用 Base64 将其转换为字符串: 像这样:

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
  }
}

然后当您收到您的请求时,请执行以下操作:

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
  }

}

【讨论】:

    猜你喜欢
    • 2014-02-26
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 2014-10-29
    相关资源
    最近更新 更多