使用PGP公钥块的实例PGPPublicKey

时间:2017-06-01 18:11:52

标签: java encryption bouncycastle pgp

我已经获得了一个PGP公钥块,我应该用它来加密csv文件。使用 BouncyCastle 库,这是我正在使用的方法:

public static void encryptFile(
        OutputStream out,
        String fileName,
        PGPPublicKey encKey,
        boolean armor,
        boolean withIntegrityCheck)
        throws IOException, NoSuchProviderException, PGPException {
    Security.addProvider(new BouncyCastleProvider());

    if (armor) {
        out = new ArmoredOutputStream(out);
    }

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);

    PGPUtil.writeFileToLiteralData(
            comData.open(bOut),
            PGPLiteralData.BINARY,
            new File(fileName));

    comData.close();

    BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.TRIPLE_DES);
    dataEncryptor.setWithIntegrityPacket(withIntegrityCheck);
    dataEncryptor.setSecureRandom(new SecureRandom());

    PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
    encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey));

    byte[] bytes = bOut.toByteArray();
    OutputStream cOut = encryptedDataGenerator.open(out, bytes.length);
    cOut.write(bytes);
    cOut.close();
    out.close();
}

我不太确定如何在PGPPublicKey时提供此方法的参数。如何仅在我的Key块中实例化此对象?

1 个答案:

答案 0 :(得分:1)

将您的密钥文件(假设您的密钥作为文件)传递给此方法,它将返回PGPPublicKey

  /** The fingerprint calculator to use whenever it is needed. */ 
  static final KeyFingerPrintCalculator FP_CALC = new BcKeyFingerprintCalculator(); 

  // Private class method readPublicKeyFromCol
  private static PGPPublicKey readPublicKeyFromCol(InputStream in)
                 throws Exception {
          PGPPublicKeyRing pkRing = null;
          PGPPublicKeyRingCollection pkCol = new PGPPublicKeyRingCollection(in, FP_CALC);
          System.out.println("key ring size=" + pkCol.size());
          Iterator it = pkCol.getKeyRings();
          while (it.hasNext()) {
                  pkRing = (PGPPublicKeyRing) it.next();
                  Iterator pkIt = pkRing.getPublicKeys();
                  while (pkIt.hasNext()) {
                          PGPPublicKey key = (PGPPublicKey) pkIt.next();
                          System.out.println("Encryption key = " + key.isEncryptionKey() + ", Master key = " + 
                                             key.isMasterKey());
                          if (key.isEncryptionKey())
                                  return key;
                  }
          }
          return null;
  }

!!!代码是从sample code

复制的