2012-03-07 229 views
27

我想使用PGP密鑰解密文件。PGP使用Java加密和解密

我已經下載了PGP密鑰安裝程序並安裝了。使用我創建的文本文件並使用PGP密鑰加密文本文件。

然後我得到一個加密的.pgp擴展文件。現在我想使用PGP使用Java代碼解密相同的文件。

在Java中,如何解密已使用PGP密鑰加密的文本文件?

回答

1

試着看看JCA CryptoSpec。我不確定PGP,但我認爲您可以在那裏找到適合您的目的的提供商。

至於我記得代碼應該是這樣的:

// get cipher object for password-based encryption 
Cipher cipher1 = Cipher.getInstance("PBEWithMD5AndDES");//You have to pass here algorithm name which PGP uses. May be you have to find and init provider for it. 

// initialize cipher for decryption, using one of the 
// init() methods that takes an AlgorithmParameters 
// object, and pass it the algParams object from above 
cipher1.init(Cipher.DECRYPT_MODE, myKey, algParams); 


FileInputStream fis; 
FileOutputStream fos; 
CipherInputStream cis; 

fis = new FileInputStream("/tmp/a.txt"); 
cis = new CipherInputStream(fis, cipher1); 
fos = new FileOutputStream("/tmp/b.txt"); 
byte[] b = new byte[8]; 
int i = cis.read(b); 
while (i != -1) { 
    fos.write(b, 0, i); 
    i = cis.read(b); 
} 
fos.close(); 
5

嘗試確實看到這個話題。我剛剛看了一下,但我認爲這是你需要的。 http://sloanseaman.com/wordpress/2012/05/13/revisited-pgp-encryptiondecryption-in-java/

+2

最喜歡這裏的其他答案,鏈接到博客條目使用[充氣城堡Java包(https://www.bouncycastle.org /java.html)。 Bouncy Castle代碼庫本身包含很多[PGP示例](https://github.com/bcgit/bc-java/tree/master/pg/src/main/java/org/bouncycastle/openpgp/examples)。如果你想將這些例子分解成一個獨立的項目,並且Maven插入Bouncy Caste的依賴關係,請參閱[openpgp-bc-examples](https://github.com/george-hawkins/openpgp-bc-examples) 。 – 2016-06-21 11:54:50

3

BouncyCastle有OpenPGP的一定的支持(「某些」,因爲他們只提RFC 2440和RFC沒有4880這是更近)。你也可以看看我們的SecureBlackbox(Java版本)的OpenPGPBlackbox包,它提供對OpenPGP的完全支持,包括對密鑰和其他高級功能的LDAP訪問。

+2

BouncyCastle現在也支持RFC4880 .. – Saumyaraj 2016-07-19 10:45:08

5

我已經用BounceCastle API和OpenPGP在Java中編寫了完整的代碼。在這個源代碼中,您將找到如何生成密鑰對,加密和解密文件。看看:https://github.com/damico/OpenPgp-BounceCastle-Example

+0

該項目在輸出沒有ascii掩碼的密鑰文件並「安裝」JCE庫後爲我工作。 – 4F2E4A2E 2014-06-23 11:56:53

4

你可以寫一個簡單的GNU PGP包裝器,它基本上是從Java執行GPG命令。

使用GNU PGP的優勢在於您不會被綁定到特定的庫。在線提供的第三方庫文檔和支持的數量並不像其他加密方案那麼豐富,因爲大多數從命令行調用PGP。 PGP密鑰也將留在一個共同的地方,即用戶特定的密鑰環而不是以多個文件導出。

的GPG命令進行解密是

echo "password" | gpg --passphrase-fd 0 --output plaintext.txt --decrypt encrypted.gpg 

通過指定密碼-FD爲0就可以提供通過標準輸入流的密碼。

下面是Java代碼的樣子 -

public static void decryptFile(String privKeyPass) { 
    String[] cmd = new String[]; 
    int i = 7; 
    cmd[i++] = "gpg"; 
    cmd[i++] = "--passphrase-fd"; 
    cmd[i++] = "0"; 
    cmd[i++] = "--output"; 
    cmd[i++] = "plaintext.txt"; 
    cmd[i++] = "--decrypt"; 
    cmd[i++] = "encrypted.gpg"; 
    Process process = Runtime.getRuntime().exec(cmd); 

    BufferedWriterout = new BufferedWriter(new OutputStreamWriter(process.getOutputStream())); 
    out.write(privKeyPass); 
    try { 
     out.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    // Read process.getInputStream() 
    // Read process.getErrorStream() 
}