将3DES存储在String中而不是CipherOutputStream中

时间:2017-08-11 16:40:07

标签: java encryption 3des

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

以下是我使用的方法。

如您所见,它使用CipherOutputStream和CipherInputStream。如何将encrypt()和decrypt()的结果读入String而不是将其写入文件?

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

1 个答案:

答案 0 :(得分:3)

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

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

为了确保最终结果是合理编码的,您实际上应该使用某种Base64OutputStream来反复写入ByteArrayOutputStream