当使用BouncyCastle时,何时以及为什么要用ArmoredOutputStream装饰OutputStream?

10

我对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();

}
}
2个回答

14

ArmoredOutputStream 使用类似于 Base64 的编码方式,这样二进制的不可打印字节就可以转换成文本友好的形式。如果要通过邮件、发布到网站或其他文本媒介发送数据,您需要这样做。

从安全角度而言,这并没有任何区别。但是消息大小会略微增加,具体取决于您的输出需求


7
ASCII装甲是一个泛指,意思是将二进制数据表示为仅限ASCII的文本。从技术上讲,有很多方法可以将二进制数据ascii-armor,但在与加密相关的领域中,PEM格式是普遍使用的(还可以在serverfault上查看此类和相关问题)。
PEM基本上是一种Base64编码的二进制数据,包含在-----BEGIN SOMETHING----------END SOMETHING-----定界符中以及一组额外的标题,可以包含有关二进制内容的一些元信息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接