PGP шифрование строки Java - PullRequest
0 голосов
/ 04 мая 2018

У меня есть требование зашифровать строку Java (которая является частью файла JSON) с использованием шифрования PGP. Я испробовал довольно много примеров, которые мог бы найти в поисках Google. Во всех этих примерах использовались методы 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?

Кроме бодрящего замка, есть ли другие альтернативы? Я уверен, что это очень распространенный случай, когда люди сталкиваются. Что используется в эти дни, если не надувной открытый openpgp?

Ответы [ 2 ]

0 голосов
/ 05 мая 2018

Я использую список Bouncy Castle следующим образом: enter image description here

У меня такие же исключения, как и у вас, из-за изменения API. Итак, вот ваш пример кода.

private static PGPPublicKey readPublicKey(InputStream in) throws IOException {
    try {
        PGPPublicKeyRing pgpPub = new PGPPublicKeyRing(in, new JcaKeyFingerprintCalculator());
        //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);
    // object that encrypts the data
    PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5)
            .setSecureRandom(new SecureRandom()).setProvider("BC"));
    cPk.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(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();


}

Если говорить о шифровании строк, то от вашего требования зависит, что с ним делать. Вы знаете, что даже кодировка base64 может быть одним из вариантов ..

Вы можете гуглить или искать на этом сайте, их много.

Хорошего кодирования

0 голосов
/ 05 мая 2018

Bouncy Castle - легковесный крипто-API Java и поставщик безопасности Java. Он также предоставляет отдельные библиотеки для определенных функций, в основном CMS (синтаксис криптографических сообщений) и PGP (довольно хорошая конфиденциальность).

Эти библиотеки могут быть загружены отдельно или в составе полного крипто-дистрибутива. Они называются bcpkix-jdk15on-159.jar и bcpg-jdk15on-159.jar соответственно (для версии 1.59). Вам нужно включить эти библиотеки в ваш classpath или в настройки Maven для выполнения компиляции.

На самом деле вы можете не указывать поставщика Bouncy Castle bcprov-... во время компиляции , если ваши проекты не используют расширенный API, но получают доступ ко всему через стандартный Java API. Однако вы можете использовать функциональность PGP только через PGP API самого Bouncy Castle, так что это не сработает для PGP.

...