java - Java字符串的PGP加密

标签 java encryption cryptography bouncycastle pgp

我需要使用 PGP 加密来加密 java 字符串(它是 JSON 文件的一部分)。我尝试了很多可以从谷歌搜索中挖掘出来的例子。所有这些示例都使用了 bouncycaSTLe openpgp 方法,该方法已被弃用。下面是我使用的代码:

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPCompressedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPUtil;


public class BouncyCastlePGPTest {

    public static void main(String[] args) {

        // the keyring that holds the public key we're encrypting with
        String publicKeyFilePath = "C:\\pgp6.5.8\\pubring.pkr";

        // init the security provider
        Security.addProvider(new BouncyCastleProvider());

        try {

            System.out.println("Creating a temp file...");

            // create a file and write the string to it
            File outputfile = File.createTempFile("pgp", null);
            FileWriter writer = new FileWriter(outputfile);
            writer.write("the message I want to encrypt".toCharArray());
            writer.close();

            System.out.println("Temp file created at ");
            System.out.println(outputfile.getAbsolutePath());
            System.out.println("Reading the temp file to make sure that the bits were written\n----------------------------");

            BufferedReader isr = new BufferedReader(new FileReader(outputfile));
            String line = "";
            while ((line = isr.readLine()) != null) {
                System.out.println(line + "\n");
            }

            // read the key 
            FileInputStream in = new FileInputStream(publicKeyFilePath);
            PGPPublicKey key = readPublicKey(in);

            // find out a little about the keys in the public key ring
            System.out.println("Key Strength = " + key.getBitStrength());
            System.out.println("Algorithm = " + key.getAlgorithm());

            int count = 0;
            for (java.util.Iterator iterator = key.getUserIDs(); iterator.hasNext();) {
                count++;
                System.out.println((String)iterator.next());    
            }
            System.out.println("Key Count = " + count);
            // create an armored ascii file
            FileOutputStream out = new FileOutputStream(outputfile.getAbsolutePath() + ".asc");

            // encrypt the file
            encryptFile(outputfile.getAbsolutePath(), out, key);

            System.out.println("Reading the encrypted file\n----------------------------");
            BufferedReader isr2 = new BufferedReader(new FileReader(new File(outputfile.getAbsolutePath() + ".asc")));
            String line2 = "";
            while ((line2 = isr2.readLine()) != null) {
                System.out.println(line2);
            }



        } catch (PGPException e) {
            System.out.println(e.toString());
            System.out.println(e.getUnderlyingException().toString());

        } catch (Exception e) {
            System.out.println(e.toString());
        }

    }

    private static PGPPublicKey readPublicKey(InputStream in) throws IOException {
        try {
            PGPPublicKeyRing pgpPub = new PGPPublicKeyRing(in);
            return pgpPub.getPublicKey();
        } catch (IOException io) {
            System.out.println("readPublicKey() threw an IOException");
            System.out.println(io.toString());
            throw io;
        }

    }

    private static void encryptFile(String fileName, OutputStream out, PGPPublicKey encKey)
    throws IOException, NoSuchProviderException, PGPException  
    {

        out = new ArmoredOutputStream(out);

        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        System.out.println("creating comData...");

        // get the data from the original file 
        PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZIP);
        PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(fileName));
        comData.close();

        System.out.println("comData created...");

        System.out.println("using PGPEncryptedDataGenerator...");

        // object that encrypts the data
        PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(PGPEncryptedDataGenerator.CAST5, new SecureRandom(), "BC");
        cPk.addMethod(encKey);

        System.out.println("used PGPEncryptedDataGenerator...");

        // take the outputstream of the original file and turn it into a byte array
        byte[] bytes = bOut.toByteArray();

        System.out.println("wrote bOut to byte array...");

        // write the plain text bytes to the armored outputstream
        OutputStream cOut = cPk.open(out, bytes.length);
        cOut.write(bytes);


        // cOut.close();
        cPk.close();
        out.close();


    }

}

下面是我的错误日志的快照:

BouncyCastlePGPTest.java:96: cannot find symbol                            
symbol  : constructor PGPPublicKeyRing(java.io.InputStream)                
location: class org.bouncycastle.openpgp.PGPPublicKeyRing                  
                        PGPPublicKeyRing pgpPub = new PGPPublicKeyRing(in);
BouncyCastlePGPTest.java:126: cannot find symbol                             
symbol  : constructor PGPEncryptedDataGenerator(int,java.security.SecureRandom,java.lang.String)                                                          
location: class org.bouncycastle.openpgp.PGPEncryptedDataGenerator           
                PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(PGPEncryptedDataGenerator.CAST5, new SecureRandom(), "BC");                 
                                                ^                            
BouncyCastlePGPTest.java:127: addMethod(org.bouncycastle.openpgp.operator.PGP
KeyEncryptionMethodGenerator) in org.bouncycastle.openpgp.PGPEncryptedDataGen
erator cannot be applied to (org.bouncycastle.openpgp.PGPPublicKey)          
                cPk.addMethod(encKey);                                       
                   ^                    

有人可以向我指出一个工作示例代码吗?我可以将其与 https://www.bouncycastle.org/latest_releases.html 中的最新 jar 一起使用。 ?

除了bouncycaSTLe之外,还有其他选择吗?我确信这是人们会遇到的一个非常常见的用例。如果不是 bouncycaSTLe openpgp,现在正在使用什么?

最佳答案

Bouncy CaSTLe 是一个 Java 轻量级加密 API 和 Java 安全提供程序。它还为特定功能提供单独库,主要是 CMS(加密消息语法)和 PGP(良好隐私)。

这些库可以单独下载,也可以在完整的加密发行版中下载。它们分别命名为 bcpkix-jdk15on-159.jarbcpg-jdk15on-159.jar(对于版本 1.59)。您需要将这些库包含在类路径或 Maven 设置中才能执行编译。

如果您的项目不使用扩展 API,而是通过标准 Java API 访问所有内容,您实际上可以省略 Bouncy CaSTLe provider bcprov-... 在编译期间。但是,您只能通过 Bouncy CaSTLe 本身的 PGP API 使用 PGP 功能,因此这不适用于 PGP。

关于java - Java字符串的PGP加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50171339/

相关文章:

java - 深度优先搜索错误

javascript - 如何避免在 http header 中显示表单数据

通过多台主机进行 SSH

c# - 无法使用 MimeKit 解密 p7m

java - 从尚未关闭的服务器套接字读取所有字符串

java - 在Wildfly/Jboss中部署ear时如何防止HTTP 404

java - 在使用 Logback 记录计算数据时,我们应该使用 isDebugEnabled() 吗?

asp.net - viewStateEncryptionMode ="Always"未加密

ruby - ruby 中流的 AES CBC 加密?

java - Java 中的 Keytool 命令?