【问题标题】:Store 3DES in String instead of CipherOutputStream将 3DES 存储在 String 而不是 CipherOutputStream
【发布时间】:2017-08-11 16:40:07
【问题描述】:

我正在尝试使用this example 对字符串进行 3DES 加密并将其存储在属性文件中。我遇到的问题是我不想直接从方法将 encrypt() 和 decrypt() 的内容写入文件。我想把它存储在一个字符串中以备后用。

以下是我正在使用的方法。

如您所见,这使用了 CipherOutputStream 和 CipherInputStream。我如何将 encrypt() 和 decrypt() 的结果读入字符串而不是将其写入文件?

  public static void encrypt(SecretKey key, InputStream in, OutputStream out)
      throws NoSuchAlgorithmException, InvalidKeyException,
      NoSuchPaddingException, IOException {
    // Create and initialize the encryption engine
    Cipher cipher = Cipher.getInstance("DESede");
    cipher.init(Cipher.ENCRYPT_MODE, key);

    // Create a special output stream to do the work for us
    CipherOutputStream cos = new CipherOutputStream(out, cipher);

    // Read from the input and write to the encrypting output stream
    byte[] buffer = new byte[2048];
    int bytesRead;
    while ((bytesRead = in.read(buffer)) != -1) {
      cos.write(buffer, 0, bytesRead);
    }
    cos.close();

    // For extra security, don't leave any plaintext hanging around memory.
    java.util.Arrays.fill(buffer, (byte) 0);
  }

  /**
   * Use the specified TripleDES key to decrypt bytes ready from the input
   * stream and write them to the output stream. This method uses uses Cipher
   * directly to show how it can be done without CipherInputStream and
   * CipherOutputStream.
   */
  public static void decrypt(SecretKey key, InputStream in, OutputStream out)
      throws NoSuchAlgorithmException, InvalidKeyException, IOException,
      IllegalBlockSizeException, NoSuchPaddingException,
      BadPaddingException {
    // Create and initialize the decryption engine
    Cipher cipher = Cipher.getInstance("DESede");
    cipher.init(Cipher.DECRYPT_MODE, key);

    // Read bytes, decrypt, and write them out.
    byte[] buffer = new byte[2048];
    int bytesRead;
    while ((bytesRead = in.read(buffer)) != -1) {
      out.write(cipher.update(buffer, 0, bytesRead));
    }

    // Write out the final bunch of decrypted bytes
    out.write(cipher.doFinal());
    out.flush();
  }

【问题讨论】:

  • 我会早点投票,但我在屏幕之间切换。但是既然你问了这个问题:即使你说的是直截了当的代码示例,对于可能遇到这个问题的其他人来说,谁是 n00bs 总是一个好主意。
  • 我知道。但是已经很晚了,我这里没有IDE。我尽量避免在最近没有编译的情况下放置代码。但除此之外:一个不知道如何创建这些对象并将它们堆叠在一起的菜鸟......可能还有其他东西要学习;-)
  • 最好我没有放代码。我发誓我已经赞成你的问题。不...我没有。
  • 简单,顺便说一句,谢谢你的回答。

标签: java encryption 3des


【解决方案1】:

简单:而不是将文件输出流传递给这些方法 - 传递不同类型的流,例如 ByteArrayOutputStream。

然后您可以从该流中提取加密数据作为字符串。

为了确保最终结果的编码合理,您实际上应该使用某种Base64OutputStream,而后者又会写入ByteArrayOutputStream

【讨论】:

    猜你喜欢
    • 2014-05-21
    • 2014-01-25
    • 1970-01-01
    • 2016-05-07
    • 2018-12-22
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多