9

我对 BouncyCastle 和 pgp 很陌生。我在互联网上看到了很多文章和示例。几乎每个加密样本都包含下面的代码

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

看来我的本地测试通过了盔甲和无盔甲。我四处搜索,但发现很少有用,并且 ArmoredOutputStream 的 javadoc 仅显示这是基本输出流。

那么有什么区别以及何时使用它?

完整的代码示例:

public static void encryptFile(String decryptedFilePath,
        String encryptedFilePath,
        String encKeyPath,
        boolean armor,
        boolean withIntegrityCheck)            
        throws Exception{

    OutputStream out = new FileOutputStream(encryptedFilePath);
    FileInputStream pubKey = new FileInputStream(encKeyPath);
    PGPPublicKey encKey = readPublicKeyFromCollection2(pubKey);
    Security.addProvider(new BouncyCastleProvider());

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

    // Init encrypted data generator
    PGPEncryptedDataGenerator encryptedDataGenerator =
            new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5, withIntegrityCheck, new SecureRandom(),"BC");

    encryptedDataGenerator.addMethod(encKey);


    OutputStream encryptedOut = encryptedDataGenerator.open(out, new byte[BUFFER_SIZE]);

    // Init compression  
    PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
    OutputStream compressedOut = compressedDataGenerator.open(encryptedOut);  

    PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
    OutputStream literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, decryptedFilePath, new Date(), new byte[BUFFER_SIZE]);
    FileInputStream inputFileStream = new FileInputStream(decryptedFilePath);
    byte[] buf = new byte[BUFFER_SIZE];  
    int len;
    while((len = inputFileStream.read(buf))>0){
        literalOut.write(buf,0,len);
    }

    literalOut.close();
    literalDataGenerator.close();

    compressedOut.close();
    compressedDataGenerator.close();
    encryptedOut.close();
    encryptedDataGenerator.close();
    inputFileStream.close();
    out.close();

}
}
4

2 回答 2

13

ArmoredOutputStream 使用类似于Base64的编码,以便将二进制不可打印字节转换为文本友好的内容。如果您想通过电子邮件发送数据,或者在网站或其他文本媒体上发布数据,您会这样做。

它在安全性方面没有什么区别。虽然消息大小略有增加。选择实际上仅取决于您要对输出做什么。

于 2014-06-23T05:44:58.697 回答
7

ASCII Armor 是一个通用术语,表示二进制数据表示为纯 ASCII 文本。从技术上讲, ascii-armor二进制数据有很多方法,但在密码学相关领域,PEM 格式很普遍(也可以在 serverfault 上查看这个和相关问题)。

PEM 基本上是一个 Base64 编码的二进制数据,包含在分隔符-----BEGIN SOMETHING----------END SOMETHING-----一组附加标头中,这些标头可以包含有关二进制内容的一些元信息。

于 2014-06-23T06:07:37.527 回答