2015-09-01 63 views
2

目前,我正在使用bouncy castle的圖書館進行實際工作,並在sloanseaman.com上找到一個示例(經過一些調整)與v1.52一起使用。如何通過Java的加密擴展來加密PGP消息?

我也從developer.com得到了一個如何使用JCE接口的例子,甚至可以將bcprov放入其中並使用它的一些算法。

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

但不管我用什麼算法的字符串,我不能讓我的JCE實用工具,該工具BouncyCastle的確實的方式進行加密。

我得到的最遠的是使用「IDEA/PGP/NoPadding」,它允許我在自己內部進行加密和解密,但BC實用程序不會解密它們,並說流中存在未知對象。

Here是我的源代碼

難道你們知道算法,模式的什麼樣的組合,和填充我需要使用呢?是否有其他選項需要我以某種方式應用?我猜我需要使用BC的AlgorithmParametersSpi版本,但我還沒有想出如何創建,但尚未

回答

3

你不能。雖然OpenPGP使用「正常」的公共/私有和對稱加密算法,但麻煩始於模式。 OpenPGP使用自己的模式(a modified CFB mode),並且Java的默認庫不支持整個OpenPGP數據包語法。

您至少需要重新實現Java中的OpenPGP CFB模式,或者某種程度上依賴於Bouncy Castle的實現。

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

+0

我確實看到有OpenPGPCFB模式,所以我的算法字符串是「IDEA/OpenPGPCFB/NoPadding」。那是你在說什麼?當我使用這個字符串時,我也會得到類似的結果。 – mike

+0

我在Java文檔中找不到任何「PGP」或「OpenPGPCFB」模式。你在哪裏找到關於這些信息? –

+0

它是BC執行[這裏]的一部分(http://grepcode.com/file/repo1.maven.org/maven2/org.bouncycastle/bcprov-ext-jdk15on/1.52/org/bouncycastle/jcajce/provider/symmetric /util/BaseBlockCipher.java#287)。但我找不到任何實際使用該模式的示例。使用這種OpenPGPCFB模式本身是可行的,但沒有其他PGP實用程序知道如何解密它。 – mike