2017-06-01 43 views
0

我得到了一個PGP公鑰密碼塊,我應該用它加密一個csv文件。使用BouncyCastle的庫,這是我使用的方法:我不太肯定我怎麼能提供的參數這種方法,當談到PGPPublicKey使用PGP公開密鑰塊的實例PGPPublicKey

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

。我怎樣才能實例化這個對象只給我的密鑰塊?

回答

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

+0

感謝複製!讓我測試並回到你身邊。 – Disasterkid

+0

肯定!另外檢查示例代碼鏈接 – Bhavesh

+0

我認爲'PGPPublicKeyRingCollection'對象除了'InputStream'外還需要'KeyFingerPrintCalculator'。 – Disasterkid