How do I encrypt a PGP message through java's crypto extension?

时间:2015-09-01 20:57:37

标签: encryption pgp java

Currently I'm using bouncy castle's libraries for the actual work and have found an example at sloanseaman.com that (after a little tweaking) works with v1.52.

I've also got a working example from developer.com of how to use the JCE interface and can even drop the bcprov in it and use some of it's algorithms.

public class CryptoUtil {
private static final String ALGORITHM = "IDEA/PGP/NoPadding";

public static void encryptFile(File keyFile, File plainTextFile, File encryptedFile) throws GeneralSecurityException, IOException {
    Cipher desCipher = Cipher.getInstance(ALGORITHM);
    desCipher.init(Cipher.ENCRYPT_MODE, readKeyFromFile(keyFile));
    OutputStream out = new BufferedOutputStream(new FileOutputStream(encryptedFile));
    InputStream in = new BufferedInputStream(new FileInputStream(plainTextFile));
    while (in.available() > 0) {
        // Read the next chunk of bytes...
        byte[] cleartextBytes = new byte[in.available()];
        in.read(cleartextBytes);
        // Now, encrypt them and write them to the encrypted file...
        byte[] encryptedBytes = desCipher.update(cleartextBytes);
        out.write(encryptedBytes, 0, encryptedBytes.length);
    }
    // Take care of any pending padding operations
    out.write(desCipher.doFinal());
    in.close();
    out.flush();
    out.close();

    System.out.println("Encrypted to " + encryptedFile);
}

But no matter what algorithm string I use, I can't get my JCE utility to encrypt the way that the bouncyCastle utility does.

The furthest I've gotten is using "IDEA/PGP/NoPadding" which allows me to encrypt and decrypt within itself, but the BC utility won't decrypt them, saying there's an unknown object in the stream.

Here is my source code

Do you guys know what combination of Algorithm, Mode, and Padding I would need to use for this? Are there other options that I need to apply somehow? I guessing I need to use BC's version of AlgorithmParametersSpi but I haven't figured out how to create that yet

1 个答案:

答案 0 :(得分:4)

你做不到。虽然OpenPGP使用“普通”公共/私有和对称加密算法,但问题始于模式。 OpenPGP使用自己的模式(a modified CFB mode),Java的默认库也不支持整个OpenPGP数据包语法。

您至少需要在Java中重新实现OpenPGP CFB模式,或者某种程度上依赖于Bouncy Castle的实现。

OpenPGP CFB模式已经包含了初始化向量的替代;没有使用/需要额外的填充。