2017-08-11 48 views
1

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

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

正如你所看到的,这使用了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(); 
    } 
+0

我会尽快投票,但我是在屏幕之间翻转。但是既然你问了这个问题:即使你所说的直截了当,对于其他可能会遇到问题的人来说,n00bs的代码示例总是一个好主意。 – user316114

+0

我知道。但已经很晚了,我在这里没有IDE。我尽量避免在不编译代码的情况下编写代码。但除此之外:一个不知道如何创建这些对象并将它们堆叠在一起的noob有可能还需要学习其他的东西;-) – GhostCat

+0

这可能是更好的我没有提出代码。我会誓言发誓我已经提出了你的问题。不......我没有。 – GhostCat

回答

3

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

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

为确保最终结果是合理编码的,您应该使用某种Base64OutputStream,然后写入该ByteArrayOutputStream