如何加密和解密pdf文件android

时间:2012-05-18 07:09:26

标签: java android encryption

您好我正在搜索免费的api或一些简单的代码来加密和解密pdf文件。加密应该从流中下载文件:

            while ((bufferLength = inputStream.read(buffer)) > 0) {

                /*
                 * Writes bufferLength characters starting at 0 in buffer to the target
                 * 
                 * buffer the non-null character array to write. 0 the index
                 * of the first character in buffer to write. bufferLength the maximum
                 * number of characters to write.
                 */
                fileOutput.write(buffer, 0, bufferLength);


            }

当需要用pdf阅读器打开时解密。也许这里有一些信息,代码或免费的Api? 有人做过这样的事吗?

我发现自己有些代码和api。但现在没什么好处。

感谢。

1 个答案:

答案 0 :(得分:2)

您可以使用CipherOuputStream和CipherInputStream尝试这样:

byte[] buf = new byte[1024];

加密:

public void encrypt(InputStream in, OutputStream out) {
    try {
        // Bytes written to out will be encrypted
        out = new CipherOutputStream(out, ecipher);

        // Read in the cleartext bytes and write to out to encrypt
        int numRead = 0;
        while ((numRead = in.read(buf)) >= 0) {
            out.write(buf, 0, numRead);
        }
        out.close();
    } catch (java.io.IOException e) {
    }
}

解密:

public void decrypt(InputStream in, OutputStream out) {
    try {
        // Bytes read from in will be decrypted
        in = new CipherInputStream(in, dcipher);

        // Read in the decrypted bytes and write the cleartext to out
        int numRead = 0;
        while ((numRead = in.read(buf)) >= 0) {
            out.write(buf, 0, numRead);
        }
        out.close();
    } catch (java.io.IOException e) {
    }
}