何时以及为什么在使用BouncyCastle时使用ArmoredOutputStream装饰OutputStream

Yug*_*hou 5 java encryption bouncycastle pgp openpgp

我对BouncyCastle和pgp很新.我在互联网上看过很多文章和样本.几乎每个加密样本都包含下面剪切的代码

if (armor) 
        out = new ArmoredOutputStream(out);
Run Code Online (Sandbox Code Playgroud)

似乎我的本地测试通过了护甲和无护甲.我用google搜索但发现很少有用,而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();

}
}
Run Code Online (Sandbox Code Playgroud)

mfa*_*nto 8

ArmoredOutputStream 使用类似于Base64的编码,以便将二进制不可打印字节转换为文本友好的字节.如果您想通过电子邮件发送数据,或在网站或其他文本媒体上发布数据,则可以执行此操作.

它在安全性方面没有任何区别.有消息大小的轻微扩张虽然.选择实际上只取决于您想要对输出做什么.


Ole*_*hin 6

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

所述PEM是基本上包裹在Base64编码的二进制数据-----BEGIN SOMETHING----------END SOMETHING-----分隔符和一组可以包含关于二进制内容一些元信息的附加报头。